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 |
|---|---|---|---|---|---|
function varargout = mygui(varargin)
% MYGUI Brief description of GUI.
% Comments displayed at the command line in response
% to the help command.
% (Leave a blank line following the help.)
% Initialization tasks
global main_gui;
main_gui = figure('Name', 'Gesture Classification', 'Position', [0 800 1000 500]);
set(main_gui, 'CloseRequestFcn', @close_fcn);
init();
delta = 30;
% Construct the components
button_settings = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Settings', 'Position', [30-delta 110 80 30]);
button_activation = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Activate', 'Position', [140-delta 110 80 30]);
button_restpos = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'RestPos', 'Position', [140-delta 70 80 30]);
button_training = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Add gesture', 'Callback', @callback_gesture, 'Position', [250-delta 110 150 30]);
static_name = uicontrol(main_gui, 'Style', 'text', 'String', 'name', 'Position', [250-delta 85 75 20]);
static_units = uicontrol(main_gui, 'Style', 'text', 'String', 'units', 'Position', [250-delta 60 75 20]);
dynamic_name = uicontrol(main_gui, 'Style', 'edit', 'Tag', 'name', 'String', 'name', 'Min', 1, 'Max', 0, 'Position', [325-delta 85 75 20]);
dynamic_units = uicontrol(main_gui, 'Style', 'edit', 'Tag', 'units', 'String', '3', 'Min', 1, 'Max', 0, 'Position', [325-delta 60 75 20]);
button_gestures = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Show gestures', 'Position', [430-delta 110 150 30]);
button_HMMs = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Show HMMs', 'Position', [430-delta 70 150 30]);
button_confusion = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Confusion matrix', 'Position', [430-delta 30 150 30]);
button_classification = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Classify', 'Callback', @callback_classification, 'Position', [610-delta 30 100 30]);
button_load = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Load gestures', 'Callback', @callback_load, 'Position', [610-delta 110 110 30]);
button_save = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Save gestures', 'Callback', @callback_save, 'Position', [610-delta 70 110 30]);
dynamic_load = uicontrol(main_gui, 'Style', 'edit', 'Tag', 'load', 'String', 'matlab.mat', 'Min', 1, 'Max', 0, 'Position', [720-delta 110 100 30]);
dynamic_save = uicontrol(main_gui, 'Style', 'edit', 'Tag', 'save', 'String', 'matlab.mat', 'Min', 1, 'Max', 0, 'Position', [720-delta 70 100 30]);
global axes_signal;
axes_signal = axes('Parent', main_gui, 'Position', [0.06 0.4 0.4 0.5]);
set(get(axes_signal, 'Title'), 'String', 'x/y/z signals');
set(get(axes_signal, 'XLabel'), 'String', 'time');
set(get(axes_signal, 'YLabel'), 'String', 'a [mg]');
global axes_mag;
axes_mag = axes('Parent', main_gui, 'Position', [0.56 0.4 0.4 0.5]);
set(get(axes_mag, 'Title'), 'String', 'magnitude');
set(get(axes_mag, 'XLabel'), 'String', 'time');
set(get(axes_mag, 'YLabel'), 'String', 'a [mg]');
% Initialization tasks
% Callbacks for MYGUI
set(button_settings, 'Callback', 'settingsGUI');
set(button_activation, 'Callback', 'newStream');
set(button_gestures, 'Callback', 'show_gestures');
set(button_confusion, 'Callback', 'show_confusion');
set(button_HMMs, 'Callback', 'select_HMM');
set(button_restpos, 'Callback', 'restposGUI');
function varargout = callback_gesture(h, eventData)
handles = guihandles;
name = get(handles.name, 'String');
units = get(handles.units, 'String');
units = str2double(units);
units = cast(units, 'uint8');
recordGUI(name, units);
function varargout = callback_classification(h, eventdata)
global CLASSIFICATION;
CLASSIFICATION = 1;
classificationGUI();
function varargout = callback_load(h, eventdata)
global gestures;
global gestures_initialized;
global DATA_DIR;
handles = guihandles(h);
filename = get(handles.load, 'String');
file = sprintf('%s/%s', DATA_DIR, filename);
load(file, 'gestures');
g = gestures{1, 1};
len = size(g);
len = len(1);
if (len ~= 0)
gestures_initialized = 1;
end
function varargout = callback_save(h, eventdata)
global DATA_DIR;
global gestures;
handles = guihandles(h);
filename = get(handles.save, 'String');
file = sprintf('%s/%s', DATA_DIR, filename);
save(file, 'gestures');
function varargout = close_fcn(h, eventdata)
global TERMINATE;
TERMINATE = 1;
fclose all;
delete(h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OLD
function varargout = callback_gesture_OLD(h, eventData)
handles = guihandles;
name = get(handles.name, 'String');
units = get(handles.units, 'String');
units = str2double(units);
units = cast(units, 'uint8');
fprintf(1, '%s\t%d\n', name, units);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% create gui for gesture training dynamically
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
new_gui_file = strcat(name, 'GUI.m');
new_gui_name = strcat(name, 'GUI');
new_gui = fopen(new_gui_file, 'w');
win_width = 1500;
button_width = 80;
command = strcat('function varargout = ', new_gui_name, '(varargin)\n');
fprintf(new_gui, command);
command = strcat('gui = figure(''Name'', ''', name, ''', ''Position'', [100,0,',int2str(win_width),',300]);\n');
fprintf(new_gui, command);
% create components
for i=1:units
% plot
space = 0.1; % space between graphs in total
space_btw_plots = space / cast(units + 1, 'double');
plot_width = (1.0 - space) / cast(units, 'double')
plot_height = 0.6;
plot_left = space_btw_plots * cast(i, 'double') + plot_width * cast(i - 1, 'double')
plot_bottom = 0.2;
plot_width_s = sprintf('%f', plot_width);
plot_height_s = sprintf('%f', plot_height);
plot_left_s = sprintf('%f', plot_left);
plot_bottom_s = sprintf('%f', plot_bottom);
command = strcat('axes_handle_', int2str(i), ' = axes(''Parent'', gui, ''Position'', [',plot_left_s, ', ', plot_bottom_s, ', ', plot_width_s, ', ', plot_height_s, ']);\n');
fprintf(1, '%s', plot_left_s);
fprintf(1, '%s', command);
fprintf(new_gui, command);
% start button
xpos = cast(plot_left * win_width, 'int32');
fprintf(new_gui, command);
% end button
xpos = xpos + button_width;
command = strcat('button_end_',int2str(i),' = uicontrol(gui,''Style'',''pushbutton'',''String'',''End'',''Position'', [',int2str(xpos),',10,',int2str(button_width),',20]);\n');
fprintf(new_gui, command);
% clear button
xpos = xpos + button_width;
command = strcat('button_clear_',int2str(i),' = uicontrol(gui,''Style'',''pushbutton'',''String'',''Clear'',''Position'', [',int2str(xpos),',10,',int2str(button_width),',20]);\n');
fprintf(new_gui, command);
end
% create callback functions
for i=1:units
% start button
function_code = '';
fprintf(new_gui, function_code)
% end button
function_code = '';
fprintf(new_gui, function_code)
% clear button
function_code = '';
fprintf(new_gui, function_code);
end
fclose(new_gui);
fopen(new_gui_file, 'r');
% load new gui
run(new_gui_name);
| 113mant-matges | Matlab/mygui2.m | MATLAB | gpl2 | 7,780 |
function [training_units, discrete] = create_units(object, feature_count_mag, int_width_mag)
segments = object.segments;
speed = object.anglespeed01;
len = size(segments);
len = len(2);
units = len / 2;
training_units = cell(units, 4);
discrete = cell(units, 4);
for i = 1:units
for k = 1:4
start_index = segments(1, 2 * i - 1);
end_index = segments(1, 2 * i);
seg = speed(start_index:end_index);
training_units{i, k} = (seg + 2) * 10;
discrete{i, k} = discretizePositive(training_units{i, k}, feature_count_mag, int_width_mag);
end
end
| 113mant-matges | Matlab/create_units.m | MATLAB | gpl2 | 593 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function x = printBuffer(x)
len = size(x, 2);
for i = 1:len
fprintf(1, '%d ', x(i));
end | 113mant-matges | Matlab/printBuffer.m | MATLAB | gpl2 | 821 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function varargout = show_gestures()
global gestures;
global gestures_initialized;
% maximum number of training units displayed
global UNITS;
win_width = 1400;
win_height = 900;
space = 0.1; % space (%) between gestures in total
top = 0.02; % space (%) between top row and upper edge of window
info_width = 250; % width (distance) of info boxes
space_vert = 0.3;
start_vert = 0.94;
name_width = 100;
name_height = 15;
buttons = cell(1, 1);
axis_handle = cell(1, 1);
tables = cell(1, 1);
% create LL matrix
columnName = cell(1,1);
columnName{1, 1} = 'x';
columnName{1, 2} = 'y';
columnName{1, 3} = 'z';
columnName{1, 4} = 'mag';
rowName = cell(1, 1);
if (gestures_initialized)
gui = figure('Name', 'Recorded gestures', 'Position', [0, 40, win_width, win_height]);
len = size(gestures);
len = len(2);
% determine max. number of units per gesture
maxi = 0;
for i = 1:len
gesture = gestures{1, i};
units = gesture.Units;
if (units > UNITS)
units = UNITS;
end
maxi = max(units, maxi);
rowName{1, i} = gesture.Name;
end
space_gestures_per = space / cast(len + 1, 'double');
gesture_width = (1 - space) * win_width / cast(len, 'double');
gesture_width_per = gesture_width / cast(win_width, 'double');
plot_width = (gesture_width - info_width) / cast(win_width, 'double');
plot_height = (start_vert - space_vert) / maxi;
space_plots_per = (start_vert - maxi * plot_height ) / cast(maxi + 1, 'double');
h = waitbar(0,'Please wait ...');
for i = 1:len
gesture = gestures{1, i};
units = gesture.Units;
if (units > UNITS)
units = UNITS;
end
plot_left = space_gestures_per * i + gesture_width_per * (i - 1);
name_left = plot_left * win_width;
name_bottom = win_height - name_height - top * win_height;
buttons{1, i} = uicontrol(gui, 'Style', 'text', 'String', gesture.Name, 'Position', [name_left name_bottom name_width name_height]);
log_left = (plot_left + plot_width) * win_width + 10;
buttons{1, i} = uicontrol(gui, 'Style', 'text', 'String', 'Log-Likelihood', 'Position', [log_left name_bottom name_width name_height]);
for k = 1:units
waitbar(((i-1)*units+k)/(len*units),h);
plot_bottom = start_vert - k * (plot_height + space_plots_per);
axis_handle{i, k} = axes('Parent', gui, 'Position', [plot_left, plot_bottom, plot_width, plot_height]);
% plot data
x = gesture.Discrete_data{k, 1};
y = gesture.Discrete_data{k, 2};
z = gesture.Discrete_data{k, 3};
mag = gesture.Discrete_data{k, 4};
plot_len = size(x);
plot_len = plot_len(2);
plot_data = zeros(3, plot_len);
plot_data(1,:) = x;
plot_data(2,:) = y;
plot_data(3,:) = z;
plot(axis_handle{i, k},plot_data');
% create training data object to be evaluated for all classes
data = cell(4, 1);
data{1, 1} = gesture.Discrete_data{k, 1};
data{2, 1} = gesture.Discrete_data{k, 2};
data{3, 1} = gesture.Discrete_data{k, 3};
data{4, 1} = gesture.Discrete_data{k, 4};
LL = zeros(len, 4);
table_left = (plot_left + plot_width) * win_width + 10;
table_bottom = plot_bottom * win_height;
table_width = info_width;
table_height = plot_height * win_height;
for m = 1:len
current_gesture = gestures{1, m}
LL(m, :) = round(current_gesture.evaluate(data));
end
tables{i, k} = uitable(gui, 'Data', LL, 'ColumnName', columnName, 'ColumnWidth',{46},'RowName', rowName,...
'Position', [table_left, table_bottom, table_width, table_height]);
end
end
close(h);
end
| 113mant-matges | Matlab/show_gestures.m | MATLAB | gpl2 | 4,918 |
function B = mk_dhmm_obs_lik(data, obsmat, obsmat1)
% MK_DHMM_OBS_LIK Make the observation likelihood vector for a discrete HMM.
% B = mk_dhmm_obs_lik(data, obsmat, obsmat1)
%
% Inputs:
% data(t) = y(t) = observation at time t
% obsmat(i,o) = Pr(Y(t)=o | Q(t)=i)
% obsmat1(i,o) = Pr(Y(1)=o | Q(1)=i). Defaults to obsmat if omitted.
%
% Output:
% B(i,t) = Pr(y(t) | Q(t)=i)
if nargin < 3, obsmat1 = obsmat; end
[Q O] = size(obsmat);
T = length(data);
B = zeros(Q,T);
t = 1;
B(:,t) = obsmat1(:, data(t));
for t=2:T
B(:,t) = obsmat(:, data(t));
end
| 113mant-matges | Matlab/mk_dhmm_obs_lik.m | MATLAB | gpl2 | 575 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function varargout = settingsGUI(varargin)
width = 1400;
height = 500;
settings_gui = figure('Name', 'Settings', 'Position', [0 100 width height]);
global sensor_src;
global baud_rate;
global window_size
global window_offset;
global ENERGY_TH;
global DISTANCE_TH;
global baseline;
global feature_count;
global int_width;
global feature_count_mag;
global int_width_mag;
global TYPE_HMM;
global STATES;
global IT_SP;
global IT_BW;
% SENSOR
static_sensor = uicontrol(settings_gui, 'Style', 'text', 'String', 'Sensor', 'FontWeight', 'bold', 'FontSize', 12,...
'Position', [20 460 300 25]);
static_dev = uicontrol(settings_gui, 'Style', 'text', 'String', 'Sensor source device', ...
'Position', [20 420 300 20]);
dynamic_dev = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'sensor', 'String', sensor_src, 'Min', 1, 'Max', 0, ...
'Position', [20 400 300 20]);
static_baud = uicontrol(settings_gui, 'Style', 'text', 'String', 'Sensor baud rate', ...
'Position', [20 360 300 20]);
dynamic_baud = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'baud', 'String', baud_rate, 'Min', 1, 'Max', 0, ...
'Position', [20 340 300 20]);
% SEGMENTATION
static_segmentation = uicontrol(settings_gui, 'Style', 'text', 'String', 'Segmentation', 'FontWeight', 'bold', 'FontSize', 12,...
'Position', [350 460 300 25]);
static_win_size = uicontrol(settings_gui, 'Style', 'text', 'String', 'Sliding window size', ...
'Position', [350 420 300 20]);
dynamic_win_size = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'win_size', 'String', sprintf('%d', window_size), 'Min', 1, 'Max', 0, ...
'Position', [350 400 300 20]);
static_win_off = uicontrol(settings_gui, 'Style', 'text', 'String', 'Sliding window offset', ...
'Position', [350 360 300 20]);
dynamic_win_off = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'win_off', 'String', sprintf('%d', window_offset), 'Min', 1, 'Max', 0, ...
'Position', [350 340 300 20]);
% group_seg = uibuttongroup('Parent', settings_gui, 'Title', 'Approach', 'Tag', 'seg',...
% 'Position', [350 / width, (320 / height) - 0.15, 300 / width, 0.15]);
% seg1 = uicontrol(group_seg, 'Style', 'radiobutton', 'Tag', '0', 'String', 'Energy-based', 'Units', 'normalized',...
% 'Position', [0.1, 0.7, 0.6, 0.3]);
% seg2 = uicontrol(group_seg, 'Style', 'radiobutton', 'Tag', '1', 'String', 'Distance-based', 'Units', 'normalized', 'Position',...
% [0.1, 0.2, 0.6, 0.3]);
static_energy = uicontrol(settings_gui, 'Style', 'text', 'String', 'Energy threshold',...
'Position', [350 300 300 20]);
dynamic_energy = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'energy', 'String', sprintf('%d', ENERGY_TH), 'Min', 1, 'Max', 0, ...
'Position', [350 280 300 20]);
static_distance = uicontrol(settings_gui, 'Style', 'text', 'String', 'Distance threshold',...
'Position', [350 240 300 20]);
dynamic_distance = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'distance', 'String', sprintf('%d', DISTANCE_TH), 'Min', 1, 'Max', 0, ...
'Position', [350 220 300 20]);
% DISCRETIZATION
static_discretization = uicontrol(settings_gui, 'Style', 'text', 'String', 'Discretization', 'FontWeight', 'bold', 'FontSize', 12,...
'Position', [680 460 300 25]);
static_mag = uicontrol(settings_gui, 'Style', 'text', 'String', 'xyz',...
'Position', [680 280 90 160]);
static_baseline = uicontrol(settings_gui, 'Style', 'text', 'String', 'magnitude',...
'Position', [680 160 90 100]);
static_baseline = uicontrol(settings_gui, 'Style', 'text', 'String', 'Baseline for features (R)',...
'Position', [780 420 200 20]);
dynamic_baseline = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'baseline', 'String', sprintf('%d', baseline), 'Min', 1, 'Max', 0, ...
'Position', [780 400 200 20]);
static_features = uicontrol(settings_gui, 'Style', 'text', 'String', 'Number of features', ...
'Position', [780 360 200 20]);
dynamic_features = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'feature_count', 'String', sprintf('%d', feature_count), 'Min', 1, 'Max', 0, ...
'Position', [780 340 200 20]);
static_interval_width = uicontrol(settings_gui, 'Style', 'text', 'String', 'Interval width (dR)',...
'Position', [780 300 200 20]);
dynamic_interval_width = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'int_width', 'String', sprintf('%d', int_width), 'Min', 1, 'Max', 0, ...
'Position', [780 280 200 20]);
static_features = uicontrol(settings_gui, 'Style', 'text', 'String', 'Number of features', ...
'Position', [780 240 200 20]);
dynamic_features = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'feature_count_mag', 'String', sprintf('%d', feature_count_mag), 'Min', 1, 'Max', 0, ...
'Position', [780 220 200 20]);
static_interval_width = uicontrol(settings_gui, 'Style', 'text', 'String', 'Interval width (dR)',...
'Position', [780 180 200 20]);
dynamic_interval_width = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'int_width_mag', 'String', sprintf('%d', int_width_mag), 'Min', 1, 'Max', 0, ...
'Position', [780 160 200 20]);
% CLASSIFICATION
static_hmm = uicontrol(settings_gui, 'Style', 'text', 'String', 'HMMs', 'FontWeight', 'bold', 'FontSize', 12,...
'Position', [1010 460 300 25]);
bgh = uibuttongroup('Parent', settings_gui, 'Title', 'Type of HMM', 'Tag', 'group',...
'Position', [1010 / width, (440 / height) - 0.15, 300 / width, 0.15]);
rbh1 = uicontrol(bgh, 'Style', 'radiobutton', 'Tag', '0', 'String', 'Fully connected', 'Units', 'normalized',...
'Position', [0.1, 0.7, 0.6, 0.3]);
rbh2 = uicontrol(bgh, 'Style', 'radiobutton', 'Tag', '1', 'String', 'Left-right', 'Units', 'normalized', 'Position',...
[0.1, 0.2, 0.6, 0.3]);
if (TYPE_HMM == 0)
set(bgh, 'SelectedObject', rbh1);
else
set(bgh, 'SelectedObject', rbh2);
end
static_states = uicontrol(settings_gui, 'Style', 'text', 'String', 'Number of states',...
'Position', [1010 300 300 20]);
dynamic_states = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'states', 'String', sprintf('%d', STATES), 'Min', 1, 'Max', 0, ...
'Position', [1010 280 300 20]);
static_sp_iterations = uicontrol(settings_gui, 'Style', 'text', 'String', 'Number of iterations for initial starting point',...
'Position', [1010 240 300 20]);
dynamic_sp_iterations = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'it_sp', 'String', sprintf('%d', IT_SP), 'Min', 1, 'Max', 0, ...
'Position', [1010 220 300 20]);
static_BW_iterations = uicontrol(settings_gui, 'Style', 'text', 'String', 'Number of Baum-Welch iterations',...
'Position', [1010 180 300 20]);
dynamic_BW_iterations = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'it_bw', 'String', sprintf('%d', IT_BW), 'Min', 1, 'Max', 0, ...
'Position', [1010 160 300 20]);
% LOAD
button_load = uicontrol(settings_gui, 'Style', 'pushbutton', 'String', 'OK', 'Position', [20 40 1290 30]);
set(button_load, 'Callback', {@callback_load});
function varargout = callback_load(h, eventdata)
handles = guihandles(h);
global sensor_src;
global baud_rate;
global window_size;
global window_offset;
global ENERGY_TH;
global DISTANCE_TH;
global baseline;
global feature_count;
global int_width;
global feature_count_mag;
global int_width_mag;
global TYPE_HMM;
global STATES;
global IT_SP;
global IT_BW;
% SENSOR
sensor_src = get(handles.sensor, 'String');
baud_rate = convert( get(handles.baud, 'String'), 'uint16' );
% SEGMENTATION
% rb = get(handles.seg, 'SelectedObject');
% string = get(rb, 'Tag');
% segmentation_approach = str2double(string);
ENERGY_TH = convert( get(handles.energy, 'String'), 'uint16' );
DISTANCE_TH = convert( get(handles.distance, 'String'), 'uint16' );
window_size = convert( get(handles.win_size, 'String'), 'uint16' );
window_offset = convert( get(handles.win_off, 'String'), 'uint16' );
% DISCRETIZATION
baseline = convert( get(handles.baseline, 'String'), 'uint16' );
baseline = cast(baseline, 'double');
feature_count = convert( get(handles.feature_count, 'String'), 'uint16' );
feature_count = cast(feature_count, 'double');
int_width = convert( get(handles.int_width, 'String'), 'uint16' );
int_width = cast(int_width, 'double');
feature_count_mag = convert( get(handles.feature_count_mag, 'String'), 'uint16' );
feature_count_mag = cast(feature_count_mag, 'double');
int_width_mag = convert( get(handles.int_width_mag, 'String'), 'uint16' );
int_width_mag = cast(int_width_mag, 'double');
% CLASSIFICATION
rb = get(handles.group, 'SelectedObject');
string = get(rb, 'Tag');
type = str2double(string);
TYPE_HMM = cast(type, 'uint8');
STATES = convert( get(handles.states, 'String'), 'uint16' );
IT_SP = convert( get(handles.it_sp, 'String'), 'uint16' );
IT_BW = convert( get(handles.it_bw, 'String'), 'uint16' );
close();
% if (segmentation_approach == 1)
% restPosGUI();
% else
% global gesture_rest_position;
% gesture_rest_position = [-Inf -Inf -Inf];
% end
function x = convert(data, type)
data = str2double(data);
data = cast(data, type);
x = data;
| 113mant-matges | Matlab/settingsGUI.m | MATLAB | gpl2 | 9,745 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function y = shiftRight(x, offset)
len = size(x, 2);
y = zeros(1, len);
for k=1:len
swap_index = mod((k - 1 - offset), len) + 1;
y(k) = x(swap_index);
end
| 113mant-matges | Matlab/shiftRight.m | MATLAB | gpl2 | 905 |
function [M, c] = normalise(M)
% NORMALISE Make the entries of a (multidimensional) array sum to 1
% [M, c] = normalise(M)
%
% This function uses the British spelling to avoid any confusion with
% 'normalize_pot', which is a method for potentials.
c = sum(M(:));
% Set any zeros to one before dividing
d = c + (c==0);
M = M / d;
| 113mant-matges | Matlab/normalise.m | MATLAB | gpl2 | 343 |
function [alpha, xi, loglik] = forwards(prior, transmat, obslik)
% FORWARDS Compute the filtered probs. in an HMM using the forwards algo.
% [alpha, xi, loglik] = forwards_backwards(prior, transmat, obslik)
% Use obslik = mk_dhmm_obs_lik(data, B) or obslik = mk_ghmm_obs_lik(data, mu, Sigma) first.
%
% Inputs:
% prior(i) = Pr(Q(1) = i)
% transmat(i,j) = Pr(Q(t+1)=j | Q(t)=i)
% obslik(i,t) = Pr(y(t) | Q(t)=i)
%
% Outputs:
% alpha(i,t) = Pr(X(t)=i | O(1:t))
% xi(i,j,t) = Pr(X(t)=i, X(t+1)=j | O(1:t+1)), t <= T-1
% loglik
T = size(obslik, 2);
Q = length(prior);
scaled = 1;
scale = ones(1,T);
% scale(t) = 1/Pr(O(t) | O(1:t-1))
% Hence prod_t 1/scale(t) = Pr(O(1)) Pr(O(2)|O(1)) Pr(O(3) | O(1:2)) ... = Pr(O(1), ... ,O(T)) = P
% or log P = - sum_t log scale(t)
%
% Note, scale(t) = 1/c(t) as defined in Rabiner
% Hence we divide beta(t) by scale(t).
% Alternatively, we can just normalise beta(t) at each step.
loglik = 0;
prior = prior(:);
alpha = zeros(Q,T);
xi = zeros(Q,Q,T);
t = 1;
alpha(:,1) = prior .* obslik(:,t);
if scaled
[alpha(:,t), n] = normalise(alpha(:,t));
scale(t) = 1/n; % scale(t) = 1/(sum_i alpha(i,t))
end
transmat2 = transmat';
for t=2:T
alpha(:,t) = (transmat2 * alpha(:,t-1)) .* obslik(:,t);
if scaled
[alpha(:,t), n] = normalise(alpha(:,t));
scale(t) = 1/n;
end
xi(:,:,t-1) = normalise((alpha(:,t-1) * obslik(:,t)') .* transmat);
end
if scaled
loglik = -sum(log(scale));
else
[dummy, lik] = normalise(alpha(:,T));
loglik = log(lik);
end
| 113mant-matges | Matlab/forwards.m | MATLAB | gpl2 | 1,563 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function x = show_confusion()
global gestures_initialized;
if (gestures_initialized)
global gestures;
len = size(gestures);
len = len(2);
confusion_matrix = zeros(len, len);
confusion_matrix_mag = zeros(len, len);
columnName = cell(1, 1);
h = waitbar(0,'Calculating confusion matrix. Please wait ...');
for i = 1:len
gesture = gestures{1, i};
units = gesture.Units;
columnName{1, i} = gesture.Name;
for k = 1:units
waitbar(((i-1)*units+k)/(len*units),h);
% create training data object to be evaluated for all classes
data = cell(4, 1);
data{1, 1} = gesture.Discrete_data{k, 1};
data{2, 1} = gesture.Discrete_data{k, 2};
data{3, 1} = gesture.Discrete_data{k, 3};
data{4, 1} = gesture.Discrete_data{k, 4};
[winner, winner_mag, LL] = classify(data);
if (winner ~= 0)
confusion_matrix(i, winner) = confusion_matrix(i, winner) + 1;
end
if (winner_mag ~= 0)
confusion_matrix_mag(i, winner_mag) = confusion_matrix_mag(i, winner_mag) + 1;
end
end
end
close(h);
win_height = 300;
win_width = 1000;
confusion_gui = figure('Name', 'Confusion matrices', 'Position', [0, 40, win_width, win_height]);
rowName = columnName;
table_confusion = uitable(confusion_gui,...
'Data', confusion_matrix,...
'ColumnName', columnName,...
'RowName', rowName,...
'Position', [50 20 400 200]);
static_confusion = uicontrol(confusion_gui, 'Style', 'text', 'String', 'x/y/z signal', ...
'Position', [50 250 400 20]);
table_confusion_mag = uitable(confusion_gui,...
'Data', confusion_matrix_mag,...
'ColumnName', columnName,...
'RowName', rowName,...
'Position', [500 20 400 200]);
static_confusion_mag = uicontrol(confusion_gui, 'Style', 'text', 'String', 'magnitude', ...
'Position', [500 250 400 20]);
end
| 113mant-matges | Matlab/show_confusion.m | MATLAB | gpl2 | 2,831 |
function loglik = log_lik_dhmm(data, prior, transmat, obsmat)
% LOG_LIK_DHMM Compute the log-likelihood of a dataset using a discrete HMM
% loglik = log_lik_dhmm(data, prior, transmat, obsmat)
[ncases T] = size(data);
loglik = 0;
for m=1:ncases
obslik = mk_dhmm_obs_lik(data, obsmat);
[alpha, xi, LL] = forwards(prior, transmat, obslik);
loglik = loglik + LL;
end
| 113mant-matges | Matlab/log_lik_dhmm.m | MATLAB | gpl2 | 382 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
% computes the new index in an array (first index: 1) of the current position is to be
% modified by an offset
function x = new_buffer_index(current_index, buffer_len, offset, debug)
if (debug)
offset
end
x = mod( (current_index - 1 + offset), buffer_len) + 1;
if (debug == 1)
current_index
offset
buffer_len
current_index - 1 + offset
mod( (current_index - 1 + offset), buffer_len)
mod( (current_index - 1 + offset), buffer_len) + 1
x
end | 113mant-matges | Matlab/new_buffer_index.m | MATLAB | gpl2 | 1,207 |
function y = shiftLeft(x, offset)
len = size(x, 2);
y = shiftRight(x, len - offset); | 113mant-matges | Matlab/shiftLeft.m | M | gpl2 | 86 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
classdef Gesture
properties
Name;
Recorded_data;
States;
It_bw;
It_sp;
Type;
Discrete_data;
Compressed_data;
Units;
Signal_count;
Transition_matrix;
Observation_matrix;
Prior_matrix;
LL;
end
methods
% constructor
function obj = Gesture(name, recorded_data, discrete_data, states, it_sp, it_bw, type)
obj.Name = name;
obj.States = states;
obj.It_sp = it_sp;
obj.It_bw = it_bw;
obj.Recorded_data = recorded_data;
obj.Type = type;
obj.Discrete_data = discrete_data;
obj.Units = size(discrete_data);
obj.Units = obj.Units(1);
len = size(discrete_data);
len = len(2);
obj.Signal_count = len;
obj.Transition_matrix = cell(1, len);
obj.Observation_matrix = cell(1, len);
obj.Prior_matrix = cell(1, len);
obj.LL = zeros(1, len);
for i = 1:4
obj.Transition_matrix{1,i} = zeros(states, states);
obj.Prior_matrix {1,i} = zeros(states, 1);
global feature_count_mag;
global feature_count;
count = feature_count;
if (i == 4)
count = feature_count_mag;
end
obj.Observation_matrix{1,i} = zeros(states, count);
end
end
function obj = set_prior_matrix(obj, i, k, matrix)
obj.Prior_matrix{i, k} = matrix;
end
function obj = set_obs_matrix(obj, i, k, matrix)
obj.Observation_matrix{i, k} = matrix;
end
function obj = set_trans_matrix(obj, i, k, matrix)
obj.Transition_matrix{i, k} = matrix;
end
% train the HMM with the given parameters
function obj = train(obj)
global feature_count_mag;
global feature_count;
global ONLY_MAG;
lower = 1;
if (ONLY_MAG == 1)
lower = 4;
end
for i = lower:obj.Signal_count
count = feature_count;
if (i == 4)
count = feature_count_mag;
end
fprintf(1, 'started training %s (%d)\n', obj.Name, i);
[obj.LL(1, i), obj.Prior_matrix{1, i}, obj.Transition_matrix{1, i}, obj.Observation_matrix{1, i}] = ...
train_HMM(obj.Discrete_data(1:obj.Units, i), obj.States, count, obj.It_sp, obj.It_bw, obj.Type);
fprintf(1, 'finished training %s (%d)\n', obj.Name, i);
end
end
% evaluate HMM for the given observed data
function x = evaluate(obj, observed_data)
x = zeros(1, obj.Signal_count);
for i = 1:obj.Signal_count
x(1, i) = log_lik_dhmm(observed_data{i, 1}, obj.Prior_matrix{1, i}, obj.Transition_matrix{1, i}, obj.Observation_matrix{1, i});
end
end
% normalize HMM matrices
function obj = normalize(obj)
for i = 1:obj.Signal_count
obj.Prior_matrix{1, i} = mk_stochastic(obj.Prior_matrix{1, i});
transmat = obj.Transition_matrix{1, i};
obsmat = obj.Observation_matrix{1, i};
for k = 1:obj.States
transmat(k,:) = mk_stochastic(transmat(k,:));
obsmat(k,:) = mk_stochastic(obsmat(k,:));
end
obj.Transition_matrix{1, i} = transmat;
obj.Observation_matrix{1, i} = obsmat;
end
end
end
end | 113mant-matges | Matlab/Gesture.m | MATLAB | gpl2 | 4,996 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function discretized = discretizePositive(data, int_count, int_width)
dataSize = size(data);
discretized = zeros(dataSize);
for i = 1:dataSize(2)
tmp = floor(data(i) / int_width);
discretized(i) = tmp;
if (discretized(i) >= int_count)
discretized(i) = int_count - 1;
end
discretized(i) = discretized(i) + 1;
end
| 113mant-matges | Matlab/discretizePositive.m | MATLAB | gpl2 | 1,090 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function x = extract_from_buffer(buffer, start_ind, end_ind)
len = size(buffer);
buffer_len = len(2);
if (start_ind <= end_ind)
x = buffer(start_ind:end_ind);
else
partOne = buffer(start_ind:buffer_len);
partTwo = buffer(1:end_ind);
x = [partOne, partTwo];
end | 113mant-matges | Matlab/extract_from_buffer.m | MATLAB | gpl2 | 1,005 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function varargout = retrainGUI()
global gestures_initialized;
if (~gestures_initialized)
return;
end
width = 700;
height = 500;
settings_gui = figure('Name', 'Settings', 'Position', [0 100 width height]);
global window_size
global window_offset;
global ENERGY_TH;
global DISTANCE_TH;
global baseline;
global feature_count;
global int_width;
global feature_count_mag;
global int_width_mag;
global TYPE_HMM;
global STATES;
global IT_SP;
global IT_BW;
mydata = guidata(settings_gui);
mydata.gui = settings_gui;
guidata(settings_gui, mydata);
% DISCRETIZATION
static_discretization = uicontrol(settings_gui, 'Style', 'text', 'String', 'Discretization', 'FontWeight', 'bold', 'FontSize', 12,...
'Position', [20 460 300 25]);
static_mag = uicontrol(settings_gui, 'Style', 'text', 'String', 'xyz',...
'Position', [20 280 90 160]);
static_baseline = uicontrol(settings_gui, 'Style', 'text', 'String', 'magnitude',...
'Position', [20 160 90 100]);
static_baseline = uicontrol(settings_gui, 'Style', 'text', 'String', 'Baseline for features (R)',...
'Position', [120 420 200 20]);
dynamic_baseline = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'baseline', 'String', sprintf('%d', baseline), 'Min', 1, 'Max', 0, ...
'Position', [120 400 200 20]);
static_features = uicontrol(settings_gui, 'Style', 'text', 'String', 'Number of features', ...
'Position', [120 360 200 20]);
dynamic_features = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'feature_count', 'String', sprintf('%d', feature_count), 'Min', 1, 'Max', 0, ...
'Position', [120 340 200 20]);
static_interval_width = uicontrol(settings_gui, 'Style', 'text', 'String', 'Interval width (dR)',...
'Position', [120 300 200 20]);
dynamic_interval_width = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'int_width', 'String', sprintf('%d', int_width), 'Min', 1, 'Max', 0, ...
'Position', [120 280 200 20]);
static_features = uicontrol(settings_gui, 'Style', 'text', 'String', 'Number of features', ...
'Position', [120 240 200 20]);
dynamic_features = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'feature_count_mag', 'String', sprintf('%d', feature_count_mag), 'Min', 1, 'Max', 0, ...
'Position', [120 220 200 20]);
static_interval_width = uicontrol(settings_gui, 'Style', 'text', 'String', 'Interval width (dR)',...
'Position', [120 180 200 20]);
dynamic_interval_width = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'int_width_mag', 'String', sprintf('%d', int_width_mag), 'Min', 1, 'Max', 0, ...
'Position', [120 160 200 20]);
% CLASSIFICATION
static_hmm = uicontrol(settings_gui, 'Style', 'text', 'String', 'HMMs', 'FontWeight', 'bold', 'FontSize', 12,...
'Position', [350 460 300 25]);
bgh = uibuttongroup('Parent', settings_gui, 'Title', 'Type of HMM', 'Tag', 'group',...
'Position', [350 / width, (440 / height) - 0.15, 300 / width, 0.15]);
rbh1 = uicontrol(bgh, 'Style', 'radiobutton', 'Tag', '0', 'String', 'Fully connected', 'Units', 'normalized',...
'Position', [0.1, 0.7, 0.6, 0.3]);
rbh2 = uicontrol(bgh, 'Style', 'radiobutton', 'Tag', '1', 'String', 'Left-right', 'Units', 'normalized', 'Position',...
[0.1, 0.2, 0.6, 0.3]);
if (TYPE_HMM == 0)
set(bgh, 'SelectedObject', rbh1);
else
set(bgh, 'SelectedObject', rbh2);
end
static_states = uicontrol(settings_gui, 'Style', 'text', 'String', 'Number of states',...
'Position', [350 300 300 20]);
dynamic_states = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'states', 'String', sprintf('%d', STATES), 'Min', 1, 'Max', 0, ...
'Position', [350 280 300 20]);
static_sp_iterations = uicontrol(settings_gui, 'Style', 'text', 'String', 'Number of iterations for initial starting point',...
'Position', [350 240 300 20]);
dynamic_sp_iterations = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'it_sp', 'String', sprintf('%d', IT_SP), 'Min', 1, 'Max', 0, ...
'Position', [350 220 300 20]);
static_BW_iterations = uicontrol(settings_gui, 'Style', 'text', 'String', 'Number of Baum-Welch iterations',...
'Position', [350 180 300 20]);
dynamic_BW_iterations = uicontrol(settings_gui, 'Style', 'edit', 'Tag', 'it_bw', 'String', sprintf('%d', IT_BW), 'Min', 1, 'Max', 0, ...
'Position', [350 160 300 20]);
check_box = uicontrol(settings_gui, 'Style', 'checkbox', 'String', 'Retrain only magnitude', 'Value', 0, 'Tag', 'cb',...
'Position', [350 120 300 20]);
% LOAD
button_retrain = uicontrol(settings_gui, 'Style', 'pushbutton', 'String', 'Retrain', 'Position', [20 40 630 30]);
set(button_retrain, 'Callback', {@callback_retrain});
function varargout = callback_retrain(h, eventdata)
handles = guihandles(h);
mydata = guidata(h);
global baseline;
global feature_count;
global int_width;
global feature_count_mag;
global int_width_mag;
global TYPE_HMM;
global STATES;
global IT_SP;
global IT_BW;
global ONLY_MAG;
% DISCRETIZATION
baseline = convert( get(handles.baseline, 'String'), 'uint16' );
baseline = cast(baseline, 'double');
feature_count = convert( get(handles.feature_count, 'String'), 'uint16' );
feature_count = cast(feature_count, 'double');
int_width = convert( get(handles.int_width, 'String'), 'uint16' );
int_width = cast(int_width, 'double');
feature_count_mag = convert( get(handles.feature_count_mag, 'String'), 'uint16' );
feature_count_mag = cast(feature_count_mag, 'double');
int_width_mag = convert( get(handles.int_width_mag, 'String'), 'uint16' );
int_width_mag = cast(int_width_mag, 'double');
% CLASSIFICATION
rb = get(handles.group, 'SelectedObject');
string = get(rb, 'Tag');
type = str2double(string);
TYPE_HMM = cast(type, 'uint8');
STATES = convert( get(handles.states, 'String'), 'uint16' );
IT_SP = convert( get(handles.it_sp, 'String'), 'uint16' );
IT_BW = convert( get(handles.it_bw, 'String'), 'uint16' );
ONLY_MAG = get(handles.cb, 'Value');
% retrain gestures
global gestures;
len = size(gestures);
len = len(2);
new_gestures = cell(1, len);
waiting = uicontrol(mydata.gui, 'Style', 'text', 'String', '',...
'Position', [20 80 630 20]);
for i = 1:len
g = gestures{1, i};
units = g.Units;
recorded_data = g.Recorded_data;
discrete_data = cell(units, 4);
for k = 1:units
x = discretize(recorded_data{k, 1}, baseline, feature_count, int_width);
y = discretize(recorded_data{k, 2}, baseline, feature_count, int_width);
z = discretize(recorded_data{k, 3}, baseline, feature_count, int_width);
m = discretizePositive(recorded_data{k, 4}, feature_count_mag, int_width_mag);
discrete_data{k, 1} = x;
discrete_data{k, 2} = y;
discrete_data{k, 3} = z;
discrete_data{k, 4} = m;
end
% please-wait button
display = sprintf('Training %s. Please wait ...', g.Name);
set(waiting, 'String', display);
drawnow;
new_g = Gesture(g.Name, g.Recorded_data, discrete_data, STATES, IT_SP, IT_BW, TYPE_HMM);
new_g = new_g.train();
new_gestures{1, i} = new_g;
end
% save retrained gestures
gestures = new_gestures;
mydata = guidata(h);
close(mydata.gui);
function x = convert(data, type)
data = str2double(data);
data = cast(data, type);
x = data;
| 113mant-matges | Matlab/retrainGUI.m | MATLAB | gpl2 | 7,933 |
load('data.mat')
file = 'data/default.mat';
window_size = 64;
window_offset = 32;
ENERGY_TH = 10000;
DISTANCE_TH = 6400;
gesture_rest_position = [-Inf -Inf -Inf];
baseline = 20;
feature_count = 3;
int_width = 10;
feature_count_mag = 3;
int_width_mag = 11;
TYPE_HMM = 0;
STATES = 4;
IT_SP = 10;
IT_BW = 10;
% BOOK
[book_recorded, book_discrete] = create_units(book, feature_count_mag, int_width_mag);
book = Gesture('book', book_recorded, book_discrete, STATES, IT_SP, IT_BW, TYPE_HMM);
priorbook = [1.0 0 0 0 0]';
transmatbook = zeros(5,5);
transmatbook(1,:) = [0.5 0.49 0.005 0.005 0];
transmatbook(2,:) = [0.005 0.5 0.49 0.005 0];
transmatbook(3,:) = [0.005 0.005 0.5 0.49 0];
transmatbook(4,:) = [0.49 0.005 0.005 0.5 0];
transmatbook(5,:) = [0 0 0 0 0];
obsmatbook = [0.2 0.79 0.01;
0.3 0.4 0.3;
0.05 0.9 0.05;
0.01 0.79 0.2;
0 0 0
];
for i = 1:4
book = book.set_prior_matrix(1, i, priorbook);
book = book.set_trans_matrix(1, i, transmatbook);
book = book.set_obs_matrix(1, i, obsmatbook);
end
% DRINK
[drink_recorded, drink_discrete] = create_units(drink, feature_count_mag, int_width_mag);
drink = Gesture('drink', drink_recorded, drink_discrete, STATES, IT_SP, IT_BW, TYPE_HMM);
priordrink = [1.0 0 0 0 0]';
transmatdrink = zeros(5,5);
transmatdrink(1,:) = [0.5 0.485 0.005 0.005 0.005];
transmatdrink(2,:) = [0.001 0.5 0.497 0.001 0.001];
transmatdrink(3,:) = [0.005 0.005 0.5 0.485 0.005];
transmatdrink(4,:) = [0.005 0.005 0.005 0.5 0.485];
transmatdrink(5,:) = [0.485 0.005 0.005 0.005 0.5];
obsmatdrink = [0.2 0.79 0.01;
0.05 0.9 0.05;
0.3 0.4 0.3;
0.05 0.9 0.05;
0.01 0.79 0.2;
];
for i = 1:4
drink = drink.set_prior_matrix(1, i, priordrink);
drink = drink.set_trans_matrix(1, i, transmatdrink);
drink = drink.set_obs_matrix(1, i, obsmatdrink);
end
% save gestures
gestures = cell(1, 2);
gestures{1, 1} = book;
gestures{1, 2} = drink;
save(file, 'gestures', 'window_size', 'window_offset', 'ENERGY_TH', 'DISTANCE_TH', 'gesture_rest_position', 'baseline', ...
'feature_count', 'int_width', 'feature_count_mag', 'int_width_mag', 'TYPE_HMM', 'STATES', 'IT_SP', 'IT_BW'); | 113mant-matges | Matlab/converter.m | MATLAB | gpl2 | 2,307 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function varargout = mygui(varargin)
global main_gui;
main_gui = figure('Name', 'Gesture Classification', 'Position', [0 100 1000 500]);
set(main_gui, 'CloseRequestFcn', @close_fcn);
init();
% Construct the components
button_settings = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Settings', 'Position', [30 110 80 30]);
button_activation = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Activate', 'Position', [140 110 80 30]);
button_restpos = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'RestPos', 'Position', [140 70 80 30]);
static_name = uicontrol(main_gui, 'Style', 'text', 'String', 'name', 'Position', [250 120 75 20]);
static_units = uicontrol(main_gui, 'Style', 'text', 'String', 'units', 'Position', [250 95 75 20]);
dynamic_name = uicontrol(main_gui, 'Style', 'edit', 'Tag', 'name', 'String', 'name', 'Min', 1, 'Max', 0, 'Position', [325 120 75 20]);
dynamic_units = uicontrol(main_gui, 'Style', 'edit', 'Tag', 'units', 'String', '3', 'Min', 1, 'Max', 0, 'Position', [325 95 75 20]);
button_training = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Add gesture', 'Callback', @callback_gesture, 'Position', [250 60 150 30]);
button_remove = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Remove gesture', 'Position', [250 20 150 30]);
button_gestures = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Show gestures', 'Position', [430 110 150 30]);
button_HMMs = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Show HMMs', 'Position', [430 70 150 30]);
button_confusion = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Confusion matrix', 'Position', [430 30 150 30]);
button_classification = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Classify', 'Callback', @callback_classification, 'Position', [850 110 100 30]);
dynamic_load = uicontrol(main_gui, 'Style', 'edit', 'Tag', 'load', 'String', 'matlab.mat', 'Min', 1, 'Max', 0, 'Position', [610 110 100 30]);
dynamic_save = uicontrol(main_gui, 'Style', 'edit', 'Tag', 'save', 'String', 'matlab.mat', 'Min', 1, 'Max', 0, 'Position', [610 70 100 30]);
button_load = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Load gestures', 'Callback', @callback_load, 'Position', [710 110 110 30]);
button_save = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Save gestures', 'Callback', @callback_save, 'Position', [710 70 110 30]);
button_retrain = uicontrol(main_gui, 'Style', 'pushbutton', 'String', 'Retrain gestures', 'Position', [610 30 210 30]);
global axes_signal;
axes_signal = axes('Parent', main_gui, 'Position', [0.06 0.4 0.4 0.5]);
set(get(axes_signal, 'Title'), 'String', 'x/y/z signals');
set(get(axes_signal, 'XLabel'), 'String', 'time');
set(get(axes_signal, 'YLabel'), 'String', 'a [mg]');
global axes_mag;
axes_mag = axes('Parent', main_gui, 'Position', [0.56 0.4 0.4 0.5]);
set(get(axes_mag, 'Title'), 'String', 'magnitude');
set(get(axes_mag, 'XLabel'), 'String', 'time');
set(get(axes_mag, 'YLabel'), 'String', 'a [mg]');
% Callbacks for MYGUI
set(button_settings, 'Callback', 'settingsGUI');
set(button_activation, 'Callback', 'newStream');
set(button_gestures, 'Callback', 'show_gestures');
set(button_remove, 'Callback', 'remove_gesture');
set(button_confusion, 'Callback', 'show_confusion');
set(button_HMMs, 'Callback', 'select_gesture');
set(button_restpos, 'Callback', 'restPosGUI');
set(button_retrain, 'Callback', 'retrainGUI');
function varargout = callback_gesture(h, eventData)
handles = guihandles;
name = get(handles.name, 'String');
units = get(handles.units, 'String');
units = str2double(units);
units = cast(units, 'uint8');
recordGUI(name, units);
function varargout = callback_classification(h, eventdata)
global CLASSIFICATION;
CLASSIFICATION = 1;
classificationGUI();
function varargout = callback_load(h, eventdata)
global gestures;
global gestures_initialized;
global DATA_DIR;
handles = guihandles(h);
filename = get(handles.load, 'String');
file = sprintf('%s/%s', DATA_DIR, filename);
load(file, 'gestures');
global window_size;
global window_offset;
global ENERGY_TH;
global DISTANCE_TH;
global gesture_rest_position;
global baseline;
global feature_count;
global int_width;
global feature_count_mag;
global int_width_mag;
global TYPE_HMM;
global STATES;
global IT_SP;
global IT_BW;
load(file, 'window_size');
load(file, 'window_offset');
load(file, 'ENERGY_TH');
load(file, 'DISTANCE_TH');
load(file, 'gesture_rest_position');
load(file, 'baseline');
load(file, 'feature_count');
load(file, 'int_width');
load(file, 'feature_count_mag');
load(file, 'int_width_mag');
load(file, 'TYPE_HMM');
load(file, 'STATES');
load(file, 'IT_SP');
load(file, 'IT_BW');
g = gestures{1, 1};
len = size(g);
len = len(1);
if (len ~= 0)
gestures_initialized = 1;
end
function varargout = callback_save(h, eventdata)
global DATA_DIR;
global gestures;
global window_size;
global window_offset;
global ENERGY_TH;
global DISTANCE_TH;
global gesture_rest_position;
global baseline;
global feature_count;
global int_width;
global feature_count_mag;
global int_width_mag;
global TYPE_HMM;
global STATES;
global IT_SP;
global IT_BW;
handles = guihandles(h);
filename = get(handles.save, 'String');
file = sprintf('%s/%s', DATA_DIR, filename);
save(file, 'gestures', 'window_size', 'window_offset', 'ENERGY_TH', 'DISTANCE_TH', 'gesture_rest_position', 'baseline', ...
'feature_count', 'int_width', 'feature_count_mag', 'int_width_mag', 'TYPE_HMM', 'STATES', 'IT_SP', 'IT_BW');
function varargout = close_fcn(h, eventdata)
global TERMINATE;
TERMINATE = 1;
fclose all;
delete(h);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OLD
function varargout = callback_gesture_OLD(h, eventData)
handles = guihandles;
name = get(handles.name, 'String');
units = get(handles.units, 'String');
units = str2double(units);
units = cast(units, 'uint8');
fprintf(1, '%s\t%d\n', name, units);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% create gui for gesture training dynamically
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
new_gui_file = strcat(name, 'GUI.m');
new_gui_name = strcat(name, 'GUI');
new_gui = fopen(new_gui_file, 'w');
win_width = 1500;
button_width = 80;
command = strcat('function varargout = ', new_gui_name, '(varargin)\n');
fprintf(new_gui, command);
command = strcat('gui = figure(''Name'', ''', name, ''', ''Position'', [100,0,',int2str(win_width),',300]);\n');
fprintf(new_gui, command);
% create components
for i=1:units
% plot
space = 0.1; % space between graphs in total
space_btw_plots = space / cast(units + 1, 'double');
plot_width = (1.0 - space) / cast(units, 'double')
plot_height = 0.6;
plot_left = space_btw_plots * cast(i, 'double') + plot_width * cast(i - 1, 'double')
plot_bottom = 0.2;
plot_width_s = sprintf('%f', plot_width);
plot_height_s = sprintf('%f', plot_height);
plot_left_s = sprintf('%f', plot_left);
plot_bottom_s = sprintf('%f', plot_bottom);
command = strcat('axes_handle_', int2str(i), ' = axes(''Parent'', gui, ''Position'', [',plot_left_s, ', ', plot_bottom_s, ', ', plot_width_s, ', ', plot_height_s, ']);\n');
fprintf(1, '%s', plot_left_s);
fprintf(1, '%s', command);
fprintf(new_gui, command);
% start button
xpos = cast(plot_left * win_width, 'int32');
fprintf(new_gui, command);
% end button
xpos = xpos + button_width;
command = strcat('button_end_',int2str(i),' = uicontrol(gui,''Style'',''pushbutton'',''String'',''End'',''Position'', [',int2str(xpos),',10,',int2str(button_width),',20]);\n');
fprintf(new_gui, command);
% clear button
xpos = xpos + button_width;
command = strcat('button_clear_',int2str(i),' = uicontrol(gui,''Style'',''pushbutton'',''String'',''Clear'',''Position'', [',int2str(xpos),',10,',int2str(button_width),',20]);\n');
fprintf(new_gui, command);
end
% create callback functions
for i=1:units
% start button
function_code = '';
fprintf(new_gui, function_code)
% end button
function_code = '';
fprintf(new_gui, function_code)
% clear button
function_code = '';
fprintf(new_gui, function_code);
end
fclose(new_gui);
fopen(new_gui_file, 'r');
% load new gui
run(new_gui_name);
| 113mant-matges | Matlab/mygui.m | MATLAB | gpl2 | 9,679 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function x = callback_classification(winner, winner_mag)
| 113mant-matges | Matlab/callback_classification.m | MATLAB | gpl2 | 786 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function x = newStream()
global buffer_len;
global out_buffer;
global out_buffer_update_rate;
global out_buffer_period;
global out_buffer_len;
global out_buffer_ctr;
global out_buffer_mag;
global large_buffer;
global large_buffer_update_rate;
global large_buffer_len;
global large_buffer_ind;
global discretized_buffer;
global baseline;
global feature_count;
global int_width;
global feature_count_mag;
global int_width_mag;
global axes_signal;
global axes_mag;
global axes_classification;
global axes_image;
% array containing axes handles of recorded gestures
% reset after every successful training step
global axes_training;
% global data structure holding recorded and discretized data
% needed for communication with infinite loop
global recorded_gesture;
recorded_gesture.recorded_data = cell(1,1);
recorded_gesture.discretized_data = cell(1,1);
global gesture_rest_position;
global ENERGY_TH;
global DISTANCE_TH;
global CLASSIFICATION;
global TRAINING;
global window_size;
global window_offset;
global sensor;
global sensor_src;
global baud_rate;
global main_gui;
global TERMINATE;
global ACTIVE_SENSOR;
% plot data initially ...
plot_buffer = out_buffer';
axes(axes_signal);
plot(plot_buffer);
title(axes_signal, 'x/y/z signals');
xlabel(axes_signal, 'time');
ylabel(axes_signal, 'a [mg]');
plot_buffer_mag = out_buffer_mag';
axes(axes_mag);
plot(plot_buffer_mag);
title(axes_mag, 'magnitude');
xlabel(axes_mag, 'time');
ylabel(axes_mag, 'a [mg]');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% sensor setup
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set up sensor (this was used for bluetooth sensor)
%system(sprintf('stty -F %s %d raw', sensor_src, baud_rate));
%system(sprintf('stty -F %s', sensor_src));
% pause to allow Bluetooth setup! (not needed for USB sensor)
%pause(2);
% open sensor (this works for Windows and Linux!)
sensor = serial(sensor_src);
set(sensor,'BaudRate',baud_rate);
fopen(sensor);
% sensor is now active
ACTIVE_SENSOR = 1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% prepare input buffer
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% load buffer initially
buffer = fread(sensor, buffer_len, 'int8');
% transpose buffer
buffer = buffer';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% infinite loop
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% flag indicating whether the user is currently in a rest position or not
restPosition = 1;
% number of iterations left until new sliding window has to be evaluated
to_go = 0;
% buffer index of start of gesture
gesture_start_ind = 0;
% buffer index of end of gesture
gesture_end_ind = 0;
% start index of gesture in output buffer
gesture_out_start = 0;
% end index of gesture in output buffer
gesture_out_end = 0;
% init line counter
i = 0;
while (~TERMINATE)
i = i + 1;
% synchronize data stream, i.e. find prefix 'DX1' or 'DX3'
while (~(buffer(1) == 'D' && buffer(2) == 'X' && (buffer(3) == '1' || buffer(3) == '3')))
buffer = shiftLeft(buffer, 1);
buffer(buffer_len) = fread(sensor, 1, 'int8');
end
% get data from stream
id = fread(sensor, 1, 'int8');
if (buffer(3) == '3') % This format ('DX3') is usually used for USB sensor
button = fread(sensor, 1, 'int8');
x_u = fread(sensor, 1, 'int16');
y_u = fread(sensor, 1, 'int16');
z_u = fread(sensor, 1, 'int16');
elseif (buffer(3) == '1') % This format ('DX1') is usually used for Bluetooth sensor
button = fread(sensor, 1, 'int16');
x_u = 0; y_u = 0; z_u = 0;
end
x = fread(sensor, 1, 'int16');
x = cast(x, 'double');
y = fread(sensor, 1, 'int16');
y = cast(y, 'double');
z = fread(sensor, 1, 'int16');
z = cast(z, 'double');
mag = sqrt(x * x + y * y + z * z);
mag = cast(mag, 'double');
if (abs(x) > 6000 || abs(y) > 6000 || abs(z) > 6000)
fprintf(1, 'ERROR: %d, %d, %d, %d, %d, %d, %d, %d, %d\n', i, id, button, x_u, y_u, z_u, x, y, z);
% drop first character in buffer
buffer = shiftLeft(buffer, 1);
buffer(buffer_len) = fread(sensor, 1, 'int8');
continue;
end
% update output buffer
% if (out_buffer_ctr < out_buffer_len)
% out_buffer_ctr = out_buffer_ctr + 1;
% else
% out_buffer(1,:) = shiftLeft(out_buffer(1,:), 1);
% out_buffer(2,:) = shiftLeft(out_buffer(2,:), 1);
% out_buffer(3,:) = shiftLeft(out_buffer(3,:), 1);
%
% out_buffer_mag(1,:) = shiftLeft(out_buffer_mag(1,:), 1);
% end
out_buffer(1,:) = shiftLeft(out_buffer(1,:), 1);
out_buffer(2,:) = shiftLeft(out_buffer(2,:), 1);
out_buffer(3,:) = shiftLeft(out_buffer(3,:), 1);
out_buffer_mag(1,:) = shiftLeft(out_buffer_mag(1,:), 1);
out_buffer(1, out_buffer_ctr) = x;
out_buffer(2, out_buffer_ctr) = y;
out_buffer(3, out_buffer_ctr) = z;
out_buffer_mag(1, out_buffer_ctr) = mag;
% update large buffer
large_buffer_ind = new_buffer_index(large_buffer_ind, large_buffer_len, 1, 0);
large_buffer(1, large_buffer_ind) = x;
large_buffer(2, large_buffer_ind) = y;
large_buffer(3, large_buffer_ind) = z;
large_buffer(4, large_buffer_ind) = mag;
% update discretized buffer
discretized_buffer(1, large_buffer_ind) = discretize(x, baseline, feature_count, int_width);
discretized_buffer(2, large_buffer_ind) = discretize(y, baseline, feature_count, int_width);
discretized_buffer(3, large_buffer_ind) = discretize(z, baseline, feature_count, int_width);
discretized_buffer(4, large_buffer_ind) = discretizePositive(mag, feature_count_mag, int_width_mag);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% classification
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if (CLASSIFICATION || TRAINING)
global gestures;
global classification_gui;
if (to_go == 0) % evaluate current sliding window
% get window indices in large buffer
window_end = large_buffer_ind;
% !!!
% when using sensor Bluetooth 6, 8 and 9, the function call
% fails as -window_size is interpreted as UNSIGNED!
% WHY?
% !!!
%window_start = new_buffer_index(large_buffer_ind, large_buffer_len, offset, 0);
window_start = mod( (large_buffer_ind - 1 - window_size), large_buffer_len) + 1;
% get contents of window
window = extract_from_buffer(large_buffer(4,:), window_start, window_end);
window_x = extract_from_buffer(large_buffer(1,:), window_start, window_end);
window_y = extract_from_buffer(large_buffer(2,:), window_start, window_end);
window_z = extract_from_buffer(large_buffer(3,:), window_start, window_end);
% determine energy
energy = var(window);
fprintf(1, 'ENERGY: %f\n', energy);
threshold = energy;
THRESHOLD = ENERGY_TH;
if (gesture_rest_position(1) ~= -Inf)
% determine distance to rest position if applicable
% use distance for segmentation decision
len = size(window);
len = len(2);
u = zeros(1,len);
u = u + 1;
dist_x = norm(window_x - u * gesture_rest_position(1,1));
dist_y = norm(window_y - u * gesture_rest_position(1,2));
dist_z = norm(window_z - u * gesture_rest_position(1,3));
threshold = dist_x + dist_y + dist_z;
fprintf(1, 'SUM(DIST): %f\n', threshold);
THRESHOLD = DISTANCE_TH;
end
% find out if a restPosition change occurred
if (threshold >= THRESHOLD && restPosition)
% start of gesture
restPosition = 0;
gesture_start_ind = large_buffer_ind;
gesture_out_start = out_buffer_ctr;
gesture_out_end = out_buffer_ctr;
if (CLASSIFICATION)
% update status in classification window
handles = guihandles(classification_gui);
set(handles.status, 'String', 'gesture');
elseif (TRAINING)
% nothing
end
elseif (threshold < THRESHOLD && ~restPosition)
% end of gesture
restPosition = 1;
gesture_end_ind = large_buffer_ind;
gesture_out_end = out_buffer_ctr;
% extract discretized gesture signals from buffer
current_gesture = cell(4,1);
for k = 1:4
current_gesture{k, 1} = extract_from_buffer(discretized_buffer(k,:), gesture_start_ind, gesture_end_ind);
end
% plot recorded gesture
len = mod(gesture_end_ind - gesture_start_ind, large_buffer_len) + 1;
recorded_data = zeros(3, len);
for k = 1:4
recorded_data(k,:) = extract_from_buffer(large_buffer(k,:), gesture_start_ind, gesture_end_ind);
end
plotData = recorded_data(1:3,:);
if (TRAINING)
plot(axes_training(TRAINING), plotData', 'LineWidth', 2);
for k = 1:4
recorded_gesture.recorded_data{TRAINING, k} = recorded_data(k,:);
recorded_gesture.discretized_data{TRAINING, k} = current_gesture{k, 1};
end
TRAINING = 0;
elseif (CLASSIFICATION)
[winner, winner_mag, LL] = classify(current_gesture);
handles = guihandles(classification_gui);
set(handles.LL, 'Data', LL);
if (winner_mag == 0)
name = 'n.a.';
else
g = gestures{1, winner_mag};
name = g.Name;
end
set(handles.result_mag, 'String', name);
if (winner == 0)
name = 'n.a.';
else
g = gestures{1, winner};
name = g.Name;
plot(axes_classification, plotData', 'LineWidth', 2);
end
set(handles.result_xyz, 'String', name);
% update status in classification window
set(handles.status, 'String', 'rest');
% DISPLAY IMAGE
% image_name = sprintf('images/%s.jpg', name);
% RGB = imread(image_name);
% image(RGB, 'Parent', axes_image);
% call classification callback script
callback_classification(winner, winner_mag);
end
else
% nothing
end
% reset count-down
to_go = window_offset;
else
to_go = to_go - 1;
end
end
% print only a fraction of the measured values
if (mod(i, out_buffer_update_rate) == 0)
fprintf(1, '%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n', id, button, x_u, y_u, z_u, x, y, z);
% create output data
plot_data = out_buffer';
plot_data_mag = out_buffer_mag';
% XYZ
% plot data
plot(axes_signal, plot_data);
% plot segmentation bar if required
if (~restPosition)
hold(axes_signal, 'on');
start = max(0, gesture_out_start);
line('Parent', axes_signal, 'LineWidth', 10, 'Color', 'y', 'XData', [start out_buffer_ctr], 'YData', [0 0]);
hold(axes_signal, 'off');
elseif (gesture_out_end > 0)
hold(axes_signal, 'on');
start = max(0, gesture_out_start);
line('Parent', axes_signal, 'LineWidth', 10, 'Color', 'y', 'XData', [start gesture_out_end], 'YData', [0 0]);
hold(axes_signal, 'off');
end
% plot titles
title(axes_signal, 'x/y/z signals');
xlabel(axes_signal, 'time');
ylabel(axes_signal, 'a [mg]');
% MAGNITUDE
% plot data
plot(axes_mag, plot_data_mag);
% plot segmentation bar if required
if (~restPosition)
hold(axes_mag, 'on');
start = max(0, gesture_out_start);
line('Parent', axes_mag, 'LineWidth', 10, 'Color', 'y', 'XData', [start out_buffer_ctr], 'YData', [1000 1000]);
hold(axes_mag, 'off');
elseif (gesture_out_end > 0)
hold(axes_mag, 'on');
start = max(0, gesture_out_start);
line('Parent', axes_mag, 'LineWidth', 10, 'Color', 'y', 'XData', [start gesture_out_end], 'YData', [1000 1000]);
hold(axes_mag, 'off');
end
% plot titles
title(axes_mag, 'magnitude');
xlabel(axes_mag, 'time');
ylabel(axes_mag, 'a [mg]');
drawnow;
%plot(plot_data); refreshdata(data_stream, 'caller'); drawnow; %pause(0.1);
end
% drop first character in buffer
buffer = shiftLeft(buffer, 1);
buffer(buffer_len) = fread(sensor, 1, 'int8');
%decrement start and end point of bar in output buffer
gesture_out_start = max(gesture_out_start - 1, 0);
gesture_out_end = max(gesture_out_end - 1, 0);
end
% close sensor
fclose(sensor);
| 113mant-matges | Matlab/newStream.m | MATLAB | gpl2 | 15,427 |
function varargout = trainingGUI(name, recorded_data, discretized_data)
% PARAMETERGUI Brief description of GUI.
% Comments displayed at the command line in response
% to the help command.
% (Leave a blank line following the help.)
% Initialization tasks
param_gui = figure('Name', 'Parameters', 'Position', [1000, 300, 400, 500]);
set(param_gui, 'CloseRequestFcn', @close_fcn);
myhandles = guidata(param_gui);
myhandles.gui = param_gui;
myhandles.name = name;
myhandles.recorded_data = recorded_data;
myhandles.discretized_data = discretized_data;
guidata(param_gui, myhandles);
% Construct the components
bgh = uibuttongroup('Parent', param_gui, 'Title', 'Type of HMM', 'Tag', 'group',...
'Position', [0.05, 0.85, 0.7, 0.15]);
rbh1 = uicontrol(bgh, 'Style', 'radiobutton', 'Tag', '0', 'String', 'Fully connected', 'Units', 'normalized',...
'Position', [0.1, 0.7, 0.6, 0.3]);
rbh2 = uicontrol(bgh, 'Style', 'radiobutton', 'Tag', '1', 'String', 'Left-right', 'Units', 'normalized', 'Position',...
[0.1, 0.2, 0.6, 0.3]);
global TYPE_HMM;
if (TYPE_HMM == 0)
set(bgh, 'SelectedObject', rbh1);
else
set(bgh, 'SelectedObject', rbh2);
end
static_states = uicontrol(param_gui, 'Style', 'text', 'String', 'Number of states',...
'Position', [10 400 300 20]);
dynamic_states = uicontrol(param_gui, 'Style', 'edit', 'Tag', 'states', 'String', '5', 'Min', 1, 'Max', 0, ...
'Position', [10 380 300 20]);
static_sp_iterations = uicontrol(param_gui, 'Style', 'text', 'String', 'Number of iterations for initial starting point',...
'Position', [10 340 300 20]);
dynamic_sp_iterations = uicontrol(param_gui, 'Style', 'edit', 'Tag', 'it_sp', 'String', '4', 'Min', 1, 'Max', 0, ...
'Position', [10 320 300 20]);
static_BW_iterations = uicontrol(param_gui, 'Style', 'text', 'String', 'Number of Baum-Welch iterations',...
'Position', [10 280 300 20]);
dynamic_BW_iterations = uicontrol(param_gui, 'Style', 'edit', 'Tag', 'it_bw', 'String', '10', 'Min', 1, 'Max', 0, ...
'Position', [10 260 300 20]);
button_load = uicontrol(param_gui, 'Style', 'pushbutton', 'String', 'Train', 'Position', [10 20 300 30]);
set(button_load, 'Callback', {@callback_load});
% load all user-entered parameters
function varargout = callback_load(h, eventdata)
fprintf(1, 'LOADING\n');
handles = guihandles(h);
mydata = guidata(h);
% please wait button
waiting = uicontrol(mydata.gui, 'Style', 'text', 'String', 'Training. Please wait ...',...
'Position', [10 120 300 20]);
drawnow;
states = convert( get(handles.states, 'String'), 'uint16' );
it_sp = convert( get(handles.it_sp, 'String'), 'uint16' );
it_bw = convert( get(handles.it_bw, 'String'), 'uint16' );
rb = get(handles.group, 'SelectedObject');
string = get(rb, 'Tag');
type = str2double(string);
type = cast(type, 'uint8');
mydata = guidata(h);
recorded_data = mydata.recorded_data;
discretized_data = mydata.discretized_data;
name = mydata.name;
gesture = Gesture(name, recorded_data, discretized_data, states, it_sp, it_bw, type);
gesture = gesture.train();
% add object to global gestures
% append gesture to global array of recorded gestures
global gestures;
global gestures_initialized;
if (gestures_initialized == 0)
gestures{1, 1} = gesture;
gestures_initialized = 1;
obj.Index = 1;
else
len = size(gestures);
len = len(2);
gestures{1, len + 1} = gesture;
end
close(mydata.gui);
%
function varargout = close_fcn(h, eventdata)
global RECORD_GUI_COUNT;
RECORD_GUI_COUNT = 0;
global recorded_gesture;
recorded_gesture.recorded_data = cell(1,1);
recorded_gesture.discretized_data = cell(1,1);
delete(h);
% convert data (String) to the desired data type
function x = convert(data, type)
data = str2double(data);
data = cast(data, type);
x = data;
| 113mant-matges | Matlab/trainingGUI.m | MATLAB | gpl2 | 4,019 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function varargout = recordGUI(name, units)
% only open GUI if sensor is active!
global ACTIVE_SENSOR;
if (ACTIVE_SENSOR == 0)
return;
end
% allow only one training window to be open!
% neccessary to keep global variable recorded_gesture consistent!
global RECORD_GUI_COUNT;
if (RECORD_GUI_COUNT == 1)
return;
else
RECORD_GUI_COUNT = 1;
end
win_width = 1400;
win_height = 370;
button_width = 80;
space = 0.1; % space between graphs in total
space_btw_plots = space / cast(units + 1, 'double'); % space between plots
gui = figure('Name', name, 'Position', [0, 40, win_width, win_height]);
set(gui, 'CloseRequestFcn', @close_fcn);
myhandles = guihandles(gui);
myhandles.gui = gui;
myhandles.name = name;
myhandles.units = units;
myhandles.space = space;
myhandles.space_btw_plots = space_btw_plots;
myhandles.axes_handle = zeros(1, units);
% cell array storing recorded gesture
myhandles.recorded_data = cell(units, 4);
% cell array storing descretized values of gesture
myhandles.discretized_data = cell(units, 4);
button_train = uicontrol(gui, 'Style', 'pushbutton', 'String', 'Train', 'Position', [40, win_height - 50, (win_width - 80) / 2, 30]);
set(button_train, 'Callback', {@callback_train, win_width, win_height});
button_train_indiv = uicontrol(gui, 'Style', 'pushbutton', 'String', 'Train individually', 'Position', [40 + (win_width - 80) / 2, win_height - 50, (win_width - 80) / 2, 30]);
set(button_train_indiv, 'Callback', {@callback_train_individually});
% define buttons and axes
for i = 1:units
plot_width = (1.0 - space) / cast(units, 'double');
plot_height = 0.5;
plot_left = space_btw_plots * cast(i, 'double') + plot_width * cast(i - 1, 'double');
plot_bottom = 0.2;
myhandles.axes_handle(i) = axes('Parent', gui, 'Position', [plot_left, plot_bottom, plot_width, plot_height]);
xpos = cast(plot_left * win_width, 'int32');
button_start(i) = uicontrol('Parent', gui, 'Value', i, 'Style', 'pushbutton', 'String','Start',...
'Position', [xpos, 10, button_width, 20]);
set(button_start(i), 'Callback', {@callback_start, i});
xpos = xpos + button_width;
button_clear(i) = uicontrol(gui, 'Value', i, 'Style', 'pushbutton', 'String', 'Clear',...
'Position', [xpos, 10, button_width, 20]);
set(button_clear(i), 'Callback', {@callback_clear, i});
end
guidata(gui, myhandles);
% make training axes visible globally
global axes_training;
axes_training = myhandles.axes_handle;
% initialize recorded gesture
global recorded_gesture;
recorded_gesture.recorded_data = cell(units, 4);
recorded_gesture.discretized_data = cell(units, 4);
% callback functions
function varargout = callback_start(h, eventdata, index)
global TRAINING;
TRAINING = index;
function varargout = callback_clear(h, eventdata, index)
global recorded_gesture;
mydata = guidata(h);
diagram = mydata.axes_handle(index);
axes(diagram);
plot(1);
% remove recorded data
for k = 1:4
recorded_gesture.recorded_data{index,k}=[];
end
% load new data
guidata(h, mydata);
function varargout = callback_train(h, eventdata, win_width, win_height)
global recorded_gesture;
mydata = guidata(h);
% check if recorded gestures available at all
if (size(recorded_gesture.recorded_data) == 0)
return;
end
% check if all training units are available
for i = 1:mydata.units
if (size(recorded_gesture.recorded_data{i, 1}) == 0)
return; % training unit is missing
end
end
waiting = uicontrol(mydata.gui, 'Style', 'text', 'String', 'Training. Please wait ...', 'Position', [40, win_height - 80, win_width - 80, 20]);
drawnow;
global TYPE_HMM;
global STATES;
global IT_SP;
global IT_BW;
gesture = Gesture(mydata.name, recorded_gesture.recorded_data, recorded_gesture.discretized_data, STATES, IT_SP, IT_BW, TYPE_HMM);
gesture = gesture.train();
% add object to global gestures
% append gesture to global array of recorded gestures
global gestures;
global gestures_initialized;
if (gestures_initialized == 0)
gestures{1, 1} = gesture;
gestures_initialized = 1;
obj.Index = 1;
else
len = size(gestures);
len = len(2);
gestures{1, len + 1} = gesture;
end
% here: use close! and not delete, as the counter for open windows has to
% be decreased
close(mydata.gui);
% open parameter settings for training
%trainingGUI(mydata.name, recorded_gesture.recorded_data, recorded_gesture.discretized_data);
recorded_gesture.recorded_data = cell(1,1);
recorded_gesture.discretized_data = cell(1,1);
function varargout = callback_train_individually(h, eventdata)
global recorded_gesture;
mydata = guidata(h);
% check if recorded gestures available at all
if (size(recorded_gesture.recorded_data) == 0)
return;
end
% check if all training units are available
for i = 1:mydata.units
if (size(recorded_gesture.recorded_data{i, 1}) == 0)
return; % training unit is missing
end
end
delete(mydata.gui);
% open parameter settings for training
trainingGUI(mydata.name, recorded_gesture.recorded_data, recorded_gesture.discretized_data);
recorded_gesture.recorded_data = cell(1,1);
recorded_gesture.discretized_data = cell(1,1);
function varargout = close_fcn(h, eventdata)
global RECORD_GUI_COUNT;
RECORD_GUI_COUNT = 0;
global TRAINING;
TRAINING = 0;
global recorded_gesture;
recorded_gesture.recorded_data = cell(1,1);
recorded_gesture.discretized_data = cell(1,1);
delete(h);
| 113mant-matges | Matlab/recordGUI.m | MATLAB | gpl2 | 6,223 |
function [converged, decrease] = em_converged(loglik, previous_loglik, threshold)
% EM_CONVERGED Has EM converged?
% [converged, decrease] = em_converged(loglik, previous_loglik, threshold)
%
% We have converged if the slope of the log-likelihood function falls below 'threshold',
% i.e., |f(t) - f(t-1)| / avg < threshold,
% where avg = (|f(t)| + |f(t-1)|)/2 and f(t) is log lik at iteration t.
% 'threshold' defaults to 1e-4.
%
% This stopping criterion is from Numerical Recipes in C p423
%
% If we are doing MAP estimation (using priors), the likelihood can decrase,
% even though the mode of the posterior is increasing.
if nargin < 3
threshold = 1e-4;
end
converged = 0;
decrease = 0;
if loglik - previous_loglik < -1e-3 % allow for a little imprecision
fprintf(1, '******likelihood decreased from %6.4f to %6.4f!\n', previous_loglik, loglik);
decrease = 1;
end
delta_loglik = abs(loglik - previous_loglik);
avg_loglik = (abs(loglik) + abs(previous_loglik) + eps)/2;
if (delta_loglik / avg_loglik) < threshold, converged = 1; end
| 113mant-matges | Matlab/em_converged.m | MATLAB | gpl2 | 1,076 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function varargout = restPosGUI()
% only open GUI if sensor is active!
global ACTIVE_SENSOR;
if (ACTIVE_SENSOR == 0)
return;
end
global large_buffer_ind;
win_width = 800;
win_height = 370;
button_width = 80;
units = 1;
space = 0.1; % space between graphs in total
space_btw_plots = space / cast(units + 1, 'double'); % space between plots
gui = figure('Name', 'Rest position', 'Position', [0, 40, win_width, win_height]);
myhandles = guihandles(gui);
myhandles.gui = gui;
myhandles.units = units;
myhandles.space = space;
myhandles.space_btw_plots = space_btw_plots;
myhandles.start_time = zeros(1, units);
myhandles.end_time = zeros(1, units);
myhandles.axes_handle = zeros(1, units);
% cell array storing recorded gesture
myhandles.recorded_data = cell(units, 4);
% cell array storing descretized values of gesture
myhandles.discretized_data = cell(units, 4);
button_ok = uicontrol(gui, 'Style', 'pushbutton', 'String', 'OK', 'Position', [40, win_height - 50, win_width - 80, 30]);
set(button_ok, 'Callback', {@callback_ok});
% define buttons and axes
for i = 1:units
plot_width = (1.0 - space) / cast(units, 'double');
plot_height = 0.6;
plot_left = space_btw_plots * cast(i, 'double') + plot_width * cast(i - 1, 'double');
plot_bottom = 0.2;
myhandles.axes_handle(i) = axes('Parent', gui, 'Position', [plot_left, plot_bottom, plot_width, plot_height]);
xpos = cast(plot_left * win_width, 'int32');
button_start(i) = uicontrol('Parent', gui, 'Value', i, 'Style', 'pushbutton', 'String','Start',...
'Position', [xpos, 10, button_width, 20]);
set(button_start(i), 'Callback', {@callback_start, i});
xpos = xpos + button_width;
button_end(i) = uicontrol(gui, 'Value', i, 'Style', 'pushbutton', 'String', 'End',...
'Position', [xpos, 10, button_width, 20]);
set(button_end(i), 'Callback', {@callback_end, i});
xpos = xpos + button_width;
button_clear(i) = uicontrol(gui, 'Value', i, 'Style', 'pushbutton', 'String', 'Clear',...
'Position', [xpos, 10, button_width, 20]);
set(button_clear(i), 'Callback', {@callback_clear, i});
end
guidata(gui, myhandles);
% callback functions
function varargout = callback_start(h, eventdata, index)
global large_buffer_ind;
mydata = guidata(h);
mydata.start_time(1, index) = large_buffer_ind;
guidata(h, mydata);
function varargout = callback_end(h, eventdata, index)
global large_buffer;
global large_buffer_ind;
global large_buffer_len;
mydata = guidata(h);
mydata.end_time(1, index) = large_buffer_ind;
mystart = mydata.start_time(1, index);
myend = large_buffer_ind;
if (mystart ~= 0)
record_len = mod((myend - 1) - (mystart - 1), large_buffer_len) + 1;
record = zeros(4, record_len);
% copy data from buffer
i = mystart - 1;
ctr = 1;
%fprintf(1, 'start: %d, end: %d\n', mystart, myend);
while (ctr <= record_len)
% get buffer contents
for k = 1:4
record(k, ctr) = large_buffer(k, i + 1);
end
% update indices
i = mod(i + 1, large_buffer_len);
ctr = ctr + 1;
end
% save recorded data
for k = 1:4
mydata.recorded_data{index, k} = record(k,:);
end
% plot recorded gesture
diagram = mydata.axes_handle(index);
axes(diagram);
record_plot = record(1:3,:);
record_plot = record_plot';
plot(record_plot);
% reset start and end index
mydata.start_time(1, index) = 0;
mydata.end_time(1, index) = 0;
else
% nothing, as start button has not yet been pressed
end
guidata(h, mydata);
function varargout = callback_clear(h, eventdata, index)
mydata = guidata(h);
diagram = mydata.axes_handle(index);
axes(diagram);
plot(1);
% reset rest position
global gesture_rest_position;
gesture_rest_position = [-Inf -Inf -Inf];
% remove recorded data
for k = 1:4
mydata.recorded_data{index,k}=[];
end
% load new data
guidata(h, mydata);
function varargout = callback_ok(h, eventdata)
mydata = guidata(h);
% check if all training units are available
for i = 1:mydata.units
if (size(mydata.recorded_data{i, 1}) == 0)
return; % training unit is missing
end
end
mean_x = mean(mydata.recorded_data{1,1})
mean_y = mean(mydata.recorded_data{1,2})
mean_z = mean(mydata.recorded_data{1,3})
global gesture_rest_position;
gesture_rest_position(1) = mean_x;
gesture_rest_position(2) = mean_y;
gesture_rest_position(3) = mean_z;
close(mydata.gui);
| 113mant-matges | Matlab/restPosGUI.m | MATLAB | gpl2 | 5,735 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function x = select_gesture()
global gestures;
global gestures_initialized;
if (gestures_initialized)
len = size(gestures);
len = len(2);
buttons = cell(1, len);
select_gui = figure('Name', 'HMM modification', 'Position', [0, 300, 400, len * 50 + 200]);
bgh = uibuttongroup('Parent', select_gui, 'Title', 'Gesture selection', 'Tag', 'group', 'Position', [0.1, 0.2, 0.7, 0.7]);
button_select = uicontrol(select_gui, 'Style', 'pushbutton', 'String', 'Select', 'Position', [10 20 300 30]);
set(button_select, 'Callback', {@callback_select});
name_space_vert_per = 0.1;
name_height_per = (1 - name_space_vert_per) / cast(len, 'double');
name_left_per = 0.1;
name_width_per = 0.7;
name_space_single = name_space_vert_per / cast(len + 1, 'double');
for i = 1:len
gesture = gestures{1, i};
tag = sprintf('%d', i);
inv = len - i + 1;
name_bottom_per = inv * name_space_single + (inv - 1) * name_height_per;
buttons{1, i} = uicontrol(bgh, 'Style', 'radiobutton', 'Tag', tag, 'String', gesture.Name, 'Units', 'normalized',...
'Position', [name_left_per, name_bottom_per, name_width_per, name_height_per]);
end
end
function varargout = callback_select(h, eventdata)
handles = guihandles(h);
mydata = guidata(h);
rb = get(handles.group, 'SelectedObject');
string = get(rb, 'Tag');
type = str2double(string);
type = cast(type, 'uint8');
close();
show_HMMs(type);
| 113mant-matges | Matlab/select_gesture.m | MATLAB | gpl2 | 2,313 |
function T = mk_stochastic(T)
% MK_STOCHASTIC Ensure the argument is a stochastic matrix, i.e., the sum over the last dimension is 1.
% T = mk_stochastic(T)
%
% If T is a vector, it will sum to 1.
% If T is a matrix, each row will sum to 1.
% If T is a 3D array, then sum_k T(i,j,k) = 1 for all i,j.
% Set zeros to 1 before dividing
% This is valid since S(j) = 0 iff T(i,j) = 0 for all j
if (ndims(T)==2) & (size(T,1)==1 | size(T,2)==1) % isvector
T = normalise(T);
elseif ndims(T)==2 % matrix
S = sum(T,2);
S = S + (S==0);
norm = repmat(S, 1, size(T,2));
T = T ./ norm;
else % multi-dimensional array
ns = size(T);
T = reshape(T, prod(ns(1:end-1)), ns(end));
S = sum(T,2);
S = S + (S==0);
norm = repmat(S, 1, ns(end));
T = T ./ norm;
T = reshape(T, ns);
end
| 113mant-matges | Matlab/mk_stochastic.m | MATLAB | gpl2 | 814 |
rfcomm -i hci0 bind /dev/rfcomm26 08:00:17:2D:4F:9A
| 113mant-matges | Matlab/startSensor.sh | Shell | gpl2 | 56 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function [ll, prior_matrix, transition_matrix, observation_matrix] = train_HMM(data, states, count, it_sp, it_bw, type)
% current log likelihood
ll = -Inf;
for k = 1:it_sp
prior_matrix_0 = rand(1, states);
transition_matrix_0 = rand(states, states);
observation_matrix_0 = rand(states, count);
if (type == 1) % left-right model
for i = 1:states
for j = 1:(i - 1)
transition_matrix_0(i, j) = 0;
end
end
end
prior_matrix_0 = mk_stochastic(prior_matrix_0);
transition_matrix_0 = mk_stochastic(transition_matrix_0);
observation_matrix_0 = mk_stochastic(observation_matrix_0);
% train HMM
[LL, prior_matrix_0, transition_matrix_0, observation_matrix_0] = learn_dhmm(data, prior_matrix_0, transition_matrix_0, observation_matrix_0, it_bw, 1e-4, 0);
% if current log likelihood is better than previous maximum
if (LL(end) > ll)
% store matrices
ll = LL(end);
prior_matrix = prior_matrix_0;
transition_matrix = transition_matrix_0;
observation_matrix = observation_matrix_0;
end
end
| 113mant-matges | Matlab/train_HMM.m | MATLAB | gpl2 | 1,971 |
function [winner, winner_mag, LL] = classify(current_gesture)
fprintf(1, 'CLASSIFYING\n');
global gestures;
len = size(gestures);
len = len(2);
LL = zeros(len, 4);
% determine LL of recorded data for all gestures
for i = 1:len
LL(i,:) = gestures{1, i}.evaluate(current_gesture);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% magnitude classification
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
winner_mag = 1;
for i = 2:len
if (LL(i, 4) > LL(winner_mag, 4))
winner_mag = i;
end
end
if (LL(winner_mag, 4) == -Inf)
% no winner
winner_mag = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% x/y/z majority vote
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
maxMat = [1 1 1];
% determine maxima of LLs
for signal = 1:3
for i = 1:len
if (LL(i, signal) > LL(maxMat(1, signal), signal))
maxMat(1, signal) = i;
end
end
end
% determine vote of each signal
votes = zeros(1, len);
for signal = 1:3
ind = maxMat(1, signal);
if (LL(ind, signal) ~= -Inf)
votes(1, ind) = votes(1, ind) + 1;
end
end
% the winner is the first gesture in the list with the maximum number of
% votes, i.e. if there are two gestures A and B with 1 vote each, A is
% chosen
% maybe introduce random selection in the future
winner = 1;
for i = 2:len
if (votes(1, i) > votes(1, winner))
winner = i;
end
end
% if there are no votes for the winner, there is no winner
if (votes(1, winner) == 0)
winner = 0;
end
% remove all impossible gestures from LL matrix, i.e. rows with infinity
% values!
% LL_clean = zeros(1,3);
% remove_row = zeros(1, len);
% inf_row = [-Inf -Inf -Inf];
%
% for i = 1:len
%
% for k = 1:3
% if (LL(i, k) == -Inf)
% remove_row(1, i) = 1;
% end
% end
%
% if (remove_row(1, i))
% invalidate row
% LL_clean(i, :) = inf_row;
% else
% add line to cleaned matrix
% LL_clean(i, :) = LL(i, 1:3);
% end
%
% end
%
%
% % determine maxima of LLs
% for signal = 1:3
% for i = 1:len
% if (LL_clean(i, signal) > LL_clean(max(1, signal), signal))
% max(1, signal) = i;
% end
% end
% end
%
%
% % determine winning gesture
% winner = 0;
%
% % if all rows have been removed => no classification possible
% if (sum(remove_row) == len)
%
% fprintf(1, 'no classification possible\n');
%
% else
%
% % determine vote of each signal
% votes = zeros(1, len);
%
% for signal = 1:3
% ind = max(1, signal);
% votes(1, ind) = votes(1, ind) + 1;
% end
%
% for i = 1:len
% if (votes(1, i) == 2 || votes(1, i) == 3)
% winner = i;
% end
% end
%
% end
| 113mant-matges | Matlab/classify.m | MATLAB | gpl2 | 2,895 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function discretized = discretize(data, baseline, features, int_width)
dataSize = size(data);
discretized = zeros(dataSize);
for i = 1:dataSize(2)
% determine discretization interval of value
if (mod(features, 2) == 0)
k = features / 2;
lowest = baseline - (k - 1) * int_width;
% % (-N/2) (-1) (1) (2) (N/2)
% % ]-00; -(N/2)*dR], ... ]-dR; 0[, [0; dR[, [dR;2dR[, ... [(N/2)*dR;+00[
%
% tmp = (data(i) - baseline) / int_width;
% if (tmp >= 0)
% tmp = floor(tmp) + 1;
% else
% tmp = -(floor(-tmp) + 1); % symmetric to positive approach
% end
%
% % last intervals are open
% if (tmp > features / 2)
% tmp = features / 2;
% elseif (tmp < - features / 2)
% tmp = - features / 2;
% end
%
% % shift interval (such that first interval has index 1)
% if (tmp > 0)
% tmp = tmp + features/2;
% else
% tmp = tmp + features/2 + 1;
% end
else
k = floor(features / 2);
lowest = baseline - int_width / 2.0 - (k - 1) * int_width;
% % (-(N-1)/2) (-1) (0) (1)
% % ]-00;-(N-1)/2*dR], ..., ]-dR/2-dR,-dR/2[, [-dR/2,dR/2[, [dR/2,dR/2+R[,
% % ((N-1)/2)
% % ... [dR/2+(N-1)/2*dR,+00[
% tmp = (data(i) - (baseline - int_width/2.)) / int_width
% if (tmp > 0)
% tmp = ceil(tmp);
% else
% tmp = floor(tmp);
% end
%
% % last intervals are open
% boundary = (features - 1) / 2;
% if (tmp > boundary)
% tmp = boundary;
% elseif (tmp < - boundary)
% tmp = - boundary;
% end
%
% % shift interval (such that first interval has index 1)
% tmp = tmp + (features - 1)/2 + 1;
%
end
diff = data(i) - lowest;
tmp = 1;
if (diff > 0)
tmp = diff / int_width;
tmp = floor(tmp);
tmp = tmp + 2;
if (tmp > features)
tmp = features;
end
end
discretized(i) = tmp;
end
| 113mant-matges | Matlab/discretize.m | MATLAB | gpl2 | 3,059 |
function [gamma, xi, loglik] = forwards_backwards(prior, transmat, obslik, filter_only)
% FORWARDS_BACKWARDS Compute the posterior probs. in an HMM using the forwards backwards algo.
% [gamma, xi, loglik] = forwards_backwards(prior, transmat, obslik, filter_only)
% 'filter_only' is an optional argument (default: 0). If 1, we do filtering, if 0, smoothing.
% Use obslik = mk_dhmm_obs_lik(data, b) or obslik = mk_ghmm_obs_lik(data, mu, sigma) first.
%
% Inputs:
% PRIOR(I) = Pr(Q(1) = I)
% TRANSMAT(I,J) = Pr(Q(T+1)=J | Q(T)=I)
% OBSLIK(I,T) = Pr(Y(T) | Q(T)=I)
%
% Outputs:
% gamma(i,t) = Pr(X(t)=i | O(1:T))
% xi(i,j,t) = Pr(X(t)=i, X(t+1)=j | O(1:T)) t <= T-1
if nargin < 4, filter_only = 0; end
T = size(obslik, 2);
Q = length(prior);
scale = ones(1,T);
loglik = 0;
alpha = zeros(Q,T);
gamma = zeros(Q,T);
xi = zeros(Q,Q,T-1);
t = 1;
alpha(:,1) = prior(:) .* obslik(:,t);
[alpha(:,t), scale(t)] = normalise(alpha(:,t));
transmat2 = transmat';
for t=2:T
[alpha(:,t),scale(t)] = normalise((transmat2 * alpha(:,t-1)) .* obslik(:,t));
if filter_only
xi(:,:,t-1) = normalise((alpha(:,t-1) * obslik(:,t)') .* transmat);
end
end
loglik = sum(log(scale));
if filter_only
gamma = alpha;
return;
end
beta = zeros(Q,T); % beta(i,t) = Pr(O(t+1:T) | X(t)=i)
gamma = zeros(Q,T);
beta(:,T) = ones(Q,1);
gamma(:,T) = normalise(alpha(:,T) .* beta(:,T));
t=T;
for t=T-1:-1:1
b = beta(:,t+1) .* obslik(:,t+1);
beta(:,t) = normalise((transmat * b));
gamma(:,t) = normalise(alpha(:,t) .* beta(:,t));
xi(:,:,t) = normalise((transmat .* (alpha(:,t) * b')));
end
| 113mant-matges | Matlab/forwards_backwards.m | MATLAB | gpl2 | 1,631 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function init()
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% set parameters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
global rate;
global large_buffer;
global large_buffer_update_rate;
global large_buffer_period;
global large_buffer_ind;
global large_buffer_len;
global out_buffer;
global out_buffer_update_rate;
global out_buffer_period;
global out_buffer_len;
global out_buffer_ctr;
global out_buffer_mag;
global buffer_len;
global discretized_buffer;
global baseline;
global feature_count;
global int_width;
global feature_count_mag;
global int_width_mag;
global gestures;
global gestures_initialized;
global gesture_rest_position;
global TRAINING;
global CLASSIFICATION;
global ENERGY_TH;
global DISTANCE_TH;
global window_size;
global window_offset;
global DATA_DIR;
global RECORD_GUI_COUNT;
global TERMINATE;
global sensor_src;
global baud_rate;
global ACTIVE_SENSOR;
global TYPE_HMM;
global STATES;
global IT_SP;
global IT_BW;
global UNITS;
global ONLY_MAG;
% flag indicating only magnitude signal is to be trained
ONLY_MAG = 0;
% maximum number of training units that can be displayed
UNITS = 10;
% number of open record guis
RECORD_GUI_COUNT = 0;
% directory in which recorded gestures are stored
DATA_DIR = 'data';
% flag indicating index of instance currently being recorded
TRAINING = 0;
% flag indicating whether classification was activated
CLASSIFICATION = 0;
% cell array containing recorded reference gestures
gestures = cell(1,1);
% flag indicating whether gesture array has already been initialized with a
% first gesture
gestures_initialized = 0;
% SENSOR
sensor_src = '/dev/ttyUSB0';
baud_rate = 19200;
%sensor_src = '/dev/rfcomm8';
%baud_rate = 38400;
% flag indicating whether sensor is active
ACTIVE_SENSOR = 0;
% flag indicating desired termination of sensor stream;
TERMINATE = 0;
% SEGMENTATION
% size of sliding window
window_size = 64;
% offset of sliding window
window_offset = 32;
% threshold for energy-based segmentation
ENERGY_TH = 10000;
% threshold for distance-based segmentation
DISTANCE_TH = window_size * 100;
% array with average values in rest position
gesture_rest_position = [-Inf -Inf -Inf];
% DISCRETIZATION
% baseline for feature determination (R)
baseline = 0;
% there are 2 * feature_count intervals for discretization of the input
% signal
feature_count = 5;
% interval width for discretization (except for the first and last one,
% which are infinite)
int_width = 500;
% number of features for magnitude
feature_count_mag = 10;
% interval width for magnitude
int_width_mag = 500;
% CLASSIFICATION
% type of HMM
TYPE_HMM = 1;
% number of HMM states
STATES = 5;
% number of iterations for starting point determination
IT_SP = 4;
% number of Baum-Welch iterations
IT_BW = 10;
% size of sensor buffer
buffer_len = 3;
% update rate, i.e. every rate_th value of the sensor data stream is
% plotted
out_buffer_update_rate = 20;
% duration of the plot in seconds
out_buffer_period = 10;
% frequency of sensor [Hertz]
frequency = 64;
% length of output buffer
out_buffer_len = out_buffer_period * frequency;
% output buffer
out_buffer = zeros(3, out_buffer_len);
% number of elements in output buffer
out_buffer_ctr = out_buffer_len;
% output buffer for magnitude
out_buffer_mag = zeros(1, out_buffer_len);
% update rate of large buffer
large_buffer_update_rate = 1;
% maximum duration of gesture
% i.e. gestures whose recording takes more than <period> seconds will be
% partially lost
large_buffer_period = 60;
% size of large buffer
large_buffer_len = large_buffer_period * frequency;
% large buffer
large_buffer = zeros(4, large_buffer_len);
% current index in large buffer
% large buffer is a round buffer, i.e. once the buffer is full, incoming
% elements overwrite the elements in the buffer from the beginning
large_buffer_ind = 1;
% buffer containing discretized values of all 4 data streams (x, y, z,
% magnitude)
discretized_buffer = zeros(4, large_buffer_len);
function x = determine_buffer_len(period, rate, update_rate)
x = period * rate / update_rate;
| 113mant-matges | Matlab/init.m | MATLAB | gpl2 | 4,892 |
% Gesture recognition with Matlab.
% Copyright (C) 2008 Thomas Holleczek, ETH Zurich
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
function x = remove_gesture()
global gestures;
global gestures_initialized;
if (gestures_initialized)
len = size(gestures);
len = len(2);
buttons = cell(1, len);
select_gui = figure('Name', 'HMM modification', 'Position', [1100, 550, 400, len * 100 + 300]);
bgh = uibuttongroup('Parent', select_gui, 'Title', 'Gesture removal', 'Tag', 'group', 'Position', [0.1, 0.2, 0.7, 0.7]);
button_select = uicontrol(select_gui, 'Style', 'pushbutton', 'String', 'Remove', 'Position', [10 20 300 30]);
set(button_select, 'Callback', {@callback_remove});
name_space_vert_per = 0.1;
name_height_per = (1 - name_space_vert_per) / cast(len, 'double');
name_left_per = 0.1;
name_width_per = 0.7;
name_space_single = name_space_vert_per / cast(len + 1, 'double');
for i = 1:len
gesture = gestures{1, i};
tag = sprintf('%d', i);
inv = len - i + 1;
name_bottom_per = inv * name_space_single + (inv - 1) * name_height_per;
buttons{1, i} = uicontrol(bgh, 'Style', 'radiobutton', 'Tag', tag, 'String', gesture.Name, 'Units', 'normalized',...
'Position', [name_left_per, name_bottom_per, name_width_per, name_height_per]);
end
end
function varargout = callback_remove(h, eventdata)
handles = guihandles(h);
mydata = guidata(h);
rb = get(handles.group, 'SelectedObject');
string = get(rb, 'Tag');
index = str2double(string);
index = cast(index, 'uint8');
global gestures;
global gestures_initialized;
len = size(gestures);
len = len(2);
if (len == 1)
gestures = cell(1, 1);
gestures_initialized = 0;
else
new_gestures = cell(1, len - 1);
% remove selected gesture
k = 1;
for i = 1:len
if (i ~= index)
new_gestures{1, k} = gestures{1, i};
k = k + 1;
end
end
gestures = new_gestures;
end
close();
| 113mant-matges | Matlab/remove_gesture.m | MATLAB | gpl2 | 2,788 |
Imports System
Imports System.Reflection
Imports 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.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("doan")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("doan")>
<Assembly: AssemblyCopyright("Copyright © 2012")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("d75f1637-6464-4a53-8379-bd897f3de0e5")>
' 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")>
| 09ct2 | trunk/doan/My Project/AssemblyInfo.vb | Visual Basic .NET | art | 1,161 |
Imports System.Media 'doc file âm thanh
Public Class Form1
Const maxcauhoi As Integer = 25
Dim tienthuong As String() = {"$100", "$200", "$300", "$500", "$1000", "$2000", "$3600", "$6000", "$9000", "$15000",
"$25000", "$35000", "$50000", "$80000", "$120000"}
Dim usecauhoi(maxcauhoi) As String
Dim livecount As Integer = 0 'mức thưởng đang đạt được
Dim player As New SoundPlayer ' doi tượng chơi nhạc
Dim count As Integer ' đếm số lần trả lời
Dim r As New Random ' đối tượng sinh số ngẫu nhiên
Dim idx As Integer ' số câu hỏi được chọn trong mảng
Dim choice(3) As String 'mảng chứa 4 câu trả lời
Dim arrlabels As New ArrayList ' các nhãn thể h
Dim cauhoi() As String = {
"Da gồm có mấy lớp?",
"Đại dương có diện tích nhỏ nhất trong 5 đại dương trên thế giới?",
"Hiện tượng gây ra bởi sự tán sắc ánh " & vbNewLine & "sáng mặt trời qua các giọt nước mưa có tên là gì?",
"Diện tích nước Việt Nam rộng khoảng" & vbNewLine & " bao nhiêu km²:",
"Loài chim nào bay nhanh nhất?",
"Hiện tượng khi mặt trời, quả đất và mặt trăng" & vbNewLine & " theo thứ tự cùng nằm trên đường thẳng:",
"Bạn cho biết tên hệ thống núi lớn nhất thế giới?",
"Văn Miếu, trường đại học đầu tiên của Việt Nam," & vbNewLine & " được xây dựng dưới triều đại nào?",
"Trong hệ mặt trời hành tinh nào" & vbNewLine & " không có mặt trăng?",
"Bạn cho biết truyền thuyết nào" & vbNewLine & " thuộc thời kỳ Âu Lạc?",
"Bạn cho biết tác phẩm nào được viết và đóng" & vbNewLine & " thành sách nặng nhất ở Việt Nam?",
"Vị trạng nguyên nhỏ tuổi nhất trong" & vbNewLine & " lịch sử thi cử Việt Nam ?",
"Cầu thủ có biệt hiệu chiếc chân trái ma thuật " & vbNewLine & "bạn có biết cầu thủ này là ai?",
"Bạn cho biết Thẻ vàng, thẻ đỏ được sử dụng " & vbNewLine & "lần đầu tiên tại World Cup vào năm nào?",
"Tim dẫn máu đi nuôi các tế bào trong cơ thể,vậy " & vbNewLine & "cái gì sẽ nuôi tim?",
"Cho đến năm 2001, thứ hạng cao nhất của đòan" & vbNewLine & " Việt Nam qua các kỳ Sea Games là hạng mấy?",
"Việt Nam trở thành thành viên của Liên Hợp " & vbNewLine & "Quốc năm nào?",
"Bạn cho biết thủ môn duy nhất trong " & vbNewLine & "lịch sử bóng đá từng giành quả bóng " & vbNewLine & "vàng châu Âu là người nước nào?",
"Loại cờ nào nhắc đến trong truyện Kiều của" & vbNewLine & " Nguyễn Du?",
"Hồ nước mặn nào lớn nhất thế giới?",
"CLB nào duy nhất chưa từng vắng mặt ở các" & vbNewLine & " cúp châu Âu kể từ khi giải này được khởi tranh (1955).",
"Lò phản ứng hạt nhân đầu tiên của nước ta" & vbNewLine & " nằm ở đâu?",
"Bạn có biết thành phố nào của Hoa Kỳ có số " & vbNewLine & "đông người Mỹ gốc Việt?",
"Vùng có tỉ lệ người biết chữ thấp nhất nước ta là:",
"Tên dân gian của Venus -Kim tinh"}
Dim traloi() As String = {
"*3;2;5;4",
"*Bắc Băng Dương;Thái Bình Dương;Đại Tây Dương;Ấn Độ Dương",
"*cầu vồng;phản xạ;cực quang;ảo giác",
"300.000;*330.000;260.000;250.000",
"Đại bàng;*Chim ưng;Chim cắt;Chim cú mèo",
"*Nguyệt thực;Hoàng hôn;Giao thừa;Nhật thực",
"Andes;Alps;Trường Sơn;*Himalaya",
"*Triều đại nhà " & vbNewLine & "họ Lý;Triều đại nhà" & vbNewLine & " họ Trần;Triều đại nhà" & vbNewLine & " họ Ngô;Triều đại nhà" & vbNewLine & " họ Nguyễn",
"Trái đất;Mộc tinh;Thủy tinh;*Thủy tinh và Kim tinh",
"*An Dương Vương;Thánh Gióng;Sơn Tinh-Thủy Tinh;Lạc Long Quân-Âu Cơ",
"Lục Vân Tiên;Văn tế nghĩa sĩ Cần Giuộc;Số đỏ;*Truyện kiều",
"Lê Văn Thịnh;*Nguyễn Hiền;Vũ Tuấn Chiêu;Nguyễn Kì",
"*Rivaldo;Zinédine Zidane;Thierry Henry;Roberto Carlos",
"1930;1950;*1970;1982",
"Máu do tâm nhĩ;*Màng mao mạch bao" & vbNewLine & " quanh tim;Oxi;Máu",
"3;*4;5;6",
"1989;1979;*1977;1972",
"Anh;*Nga;Ý;Đức",
"Cờ tướng;Cờ vua;*Cờ vây;Cờ Othello",
"*Great Salt Lake;Hồ Victoria;Hồ Michigan;Hồ Thanh Hải",
"Manchester United;Juventus;*Barcelona;Real Madrid",
"Hà Nội;Đồng Nai; *Đà Lạt; TP Hồ Chí Minh",
"San Francisco, California;Houston, Texas;*San Jose,California;Boston,Massachusetts",
"*Tây Bắc;Đông Bắc;Tây Nguyên;Bắc Trung Bộ",
"sao khuê;sao chức nữ;sao Mai;*sao mai và sao hôm"
}
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
player = New SoundPlayer("aitrieuphu.mp3") ' Nhạc nền
'tạo mới và đặt các nhãn vào khung groupbox
For i As Integer = 0 To tienthuong.Length - 1
Dim lb As New Label
lb.Text = tienthuong(i)
lb.Font = New Font("arial", 14, FontStyle.Regular)
lb.Left = 45
lb.Top = gpthangdiem.Height - i * lb.Height - 45
gpthangdiem.Controls.Add(lb)
arrlabels.Add(lb)
Next
thaydoi()
End Sub
Private Sub thaydoi()
For i As Integer = tienthuong.Length - 1 To 0 Step -1
'đổi màu sau 5 mức thưởng
If (i + 1) Mod 5 = 0 Then
arrlabels(i).forecolor = Color.FromArgb(255, 255, 255)
Else
arrlabels(i).forecolor = Color.FromArgb(255, 128, 0)
End If
arrlabels(i).backcolor = Me.BackColor
If i = livecount Then
arrlabels(i).backcolor = Color.Gold
End If
Next
End Sub
Private Sub gpthangdiem_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles gpthangdiem.Enter
End Sub
Private Sub btbatdau_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btbatdau.Click
btbatdau.Enabled = False ' ko cho tac dong lan nua
btdoicau.Enabled = True ' kich hoat 3su tro giup
bt2lan.Enabled = True
bt5050.Enabled = True
hienthicauhoi() 'hiển thị câu hỏi mới
AddHandler rdA.CheckedChanged, AddressOf hienthicauhoi
AddHandler RdB.CheckedChanged, AddressOf hienthicauhoi
AddHandler RdC.CheckedChanged, AddressOf hienthicauhoi
AddHandler RdD.CheckedChanged, AddressOf hienthicauhoi
End Sub
Private Sub hienthicauhoi() 'chọn câu hỏi khác
Do
idx = r.Next(maxcauhoi)
Loop Until usecauhoi(idx) = ""
'tách câu trả lời thành 4
choice = traloi(idx).Split(";") 'gán nôi dung các đạp án cho nút button
rdA.Text = choice(0).Replace("*", "") 'loại bỏ ký tự * là ký tự đánh dấu câu trả lời đúng
rdA.Checked = False
RdB.Text = choice(1).Replace("*", "")
RdB.Checked = False
RdC.Text = choice(2).Replace("*", "")
RdC.Checked = False
RdD.Text = choice(3).Replace("*", "")
RdD.Checked = False
'Hiển thị câu hỏi
lbcauhoi.Text = cauhoi(idx)
'lưu lại câu hỏi để lần sau không trùng
usecauhoi(idx) = cauhoi(idx)
End Sub
'tra loi
Private Sub hienthicauhoi(ByVal sender As Object, ByVal e As EventArgs)
Dim rd As RadioButton = sender
Dim i As Integer = rd.Tag
If rd.Checked Then
If choice(i).IndexOf("*") >= 0 Then
'trả lời đúng
MsgBox(" Bạn Trả lời đúng rồi !")
'chọn câu hỏi khác
lbtienthuong.Text = String.Format("Tổng số tiền đạt được {0}", tienthuong(livecount))
'nâng mức thang điểm
livecount = livecount + 1
'tạo câu hỏi mới
hienthicauhoi()
'cập nhật lại màu sắc các thang điểm
thaydoi()
Else
'trả lời 2 lần
If bt2lan.Enabled = False Then
count = count + 1
End If
MsgBox("Sai rồi bạn ơi !")
If count = 2 Or bt2lan.Enabled Then
'dừng cuộc chơi nếu trả lời lần 1 hoặc lần 2 bị sai
'dungchoi()
End If
End If
'nếu đã đạt được 15 câu hỏi
If livecount = 15 Then
'Timecount.Enabled = False
player = New SoundPlayer("I_Win.wav")
player.PlayLooping()
MsgBox("Xin chúc mừng - Bạn là triệu phú ")
End If
End If
End Sub
Private Sub bt2lan_Click(sender As System.Object, e As System.EventArgs) Handles bt2lan.Click
sender.enabled = False
sender.text = "X"
End Sub
Private Sub bt5050_Click(sender As System.Object, e As System.EventArgs) Handles bt5050.Click
sender.enabled = False
sender.text = "X"
'loại bỏ 2 câu sai
Dim t As Integer = 0
For n As Integer = 0 To 3
If choice(n).IndexOf("*") < 0 Then
choice(n) = "-------------"
t = t + 1
End If
If t = 2 Then Exit For
Next
rdA.Text = choice(0).Replace("*", "")
RdB.Text = choice(0).Replace("*", "")
RdC.Text = choice(0).Replace("*", "")
RdD.Text = choice(0).Replace("*", "")
End Sub
Private Sub btdoicau_Click(sender As System.Object, e As System.EventArgs) Handles btdoicau.Click
sender.enabled = False
sender.text = "X"
'tạo câu hỏi mới
hienthicauhoi()
End Sub
'chấm dứt chương trình
Private Sub dungchoi()
'Timecount.Enabled = False
livecount = Math.Max(livecount - 1, 0)
Dim WinPrice As Decimal = cauhoi(livecount).Replace("$", "")
'giải thưởng là tổng số điểm đạt được chia đôi
MsgBox(String.Format("Số tiền bạn nhận được là {0} - Lần sau bạn sẽ may mắn hơn.", WinPrice / 2))
Me.Close()
End Sub
End Class
| 09ct2 | trunk/doan/Form1.vb | Visual Basic .NET | art | 11,274 |
package hocusPocus.Controllers;
import hocusPocus.IHM.NombreJoueurs;
import hocusPocus.IHM.TypeDePartie;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
public class ControllerTypeDePartie implements ActionListener {
TypeDePartie typePartie;
NombreJoueurs nbJoueur;
public ControllerTypeDePartie(TypeDePartie typePartie) {
this.typePartie = typePartie;
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == typePartie.normale){
TypeDePartie.partieNormale = true;
TypeDePartie.partieRapide = false;
}
if(e.getSource() == typePartie.rapide){
TypeDePartie.partieRapide = true;
TypeDePartie.partieNormale = false;
}
if(e.getSource()==typePartie.ok){
if(TypeDePartie.partieRapide == false && TypeDePartie.partieNormale == false)
JOptionPane.showMessageDialog(null,"Erreur : pas de Type de partie choisi", "Erreur", JOptionPane.ERROR_MESSAGE);
else{
if(TypeDePartie.partieRapide)
System.out.println("Selection : partie rapide");
else
System.out.println("Selection : partie normale");
typePartie.dispose();
new NombreJoueurs(); // Demander le nombre de joueurs
}
}
if(e.getSource() == typePartie.annuler){
typePartie.dispose();
}
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Controllers/ControllerTypeDePartie.java | Java | mit | 1,355 |
package hocusPocus.Controllers;
import hocusPocus.IHM.ChoixFinTour;
import hocusPocus.IHM.EchangerMainGrimoire;
import hocusPocus.IHM.LimiteCarteMain;
import hocusPocus.IHM.InteractionJoueur;
import hocusPocus.IHM.InterfacePlateau;
import hocusPocus.Partie.AnalyseZoneDeJeu;
import hocusPocus.Partie.Plateau;
import hocusPocus.Partie.ResoudrePouvoirHocus;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
public class ControllerInterfacePlateau implements ActionListener{
private InterfacePlateau interfacePlateau;
private boolean isPossible;
private Plateau plateau;
public ControllerInterfacePlateau(InterfacePlateau interfacePlateau) {
this.interfacePlateau = interfacePlateau;
this.plateau = Plateau.getInstance();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()!=null) {
if(e.getSource() == interfacePlateau.btnJouerCarte) { // Clic sur JouerCarte
isPossible = plateau.getJoueurCourant().jouerCarte(interfacePlateau.getCarteSelectionee());
if(!isPossible) {
JOptionPane.showMessageDialog(null,"Impossible de joueur ce type de carte.\n Pour plus de detail: Aide>RegleDuJeu ","ERREUR",JOptionPane.ERROR_MESSAGE);
}else {
if(plateau.getJoueurReagissant() == null || plateau.getJoueurCourant().equals(plateau.getJoueurReagissant()))
interfacePlateau.rafraichirPanelJoueurCourant(); // On rafraichit apres pose de la carte
else
interfacePlateau.rafraichirPanelJoueurReagissant();
interfacePlateau.rafraichirPanelZoneDeJeu();
interfacePlateau.rafraichirPanelListeJoueurs();
AnalyseZoneDeJeu analyse = new AnalyseZoneDeJeu();
analyse.Analyse(); //
interfacePlateau.btnJouerCarte.setEnabled(false); // On desactive le bouton jusqu'a ce qu'une carte soit selectionnnee
}
}
if(e.getSource() == interfacePlateau.btnPasserTour) {
System.out.println("Terminer le tour");
new ChoixFinTour(interfacePlateau);
}
if(e.getSource() == interfacePlateau.btnEchangerCartes) {
new EchangerMainGrimoire(interfacePlateau);
}
}
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Controllers/ControllerInterfacePlateau.java | Java | mit | 2,177 |
package hocusPocus.Controllers;
import hocusPocus.IHM.DesignerJoueur;
import hocusPocus.IHM.InteractionJoueur;
import hocusPocus.Partie.Plateau;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ControllerDesignerJoueur implements ActionListener{
DesignerJoueur designerJoueur;
public ControllerDesignerJoueur(DesignerJoueur designerJoueur) {
this.designerJoueur = designerJoueur;
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == designerJoueur.btnOk) {
for(javax.swing.JRadioButton button : designerJoueur.bNom) {
if(button.isSelected()) {
Plateau.getInstance().setJoueurCible(designerJoueur.listeJoueurs.get(button));
new InteractionJoueur();
designerJoueur.dispose();
}
}
}
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Controllers/ControllerDesignerJoueur.java | Java | mit | 823 |
package hocusPocus.Controllers;
import hocusPocus.Cartes.Carte;
import hocusPocus.IHM.InteractionJoueur;
import hocusPocus.IHM.InterfacePlateau;
import hocusPocus.Partie.AnalyseZoneDeJeu;
import hocusPocus.Partie.Jeu;
import hocusPocus.Partie.Joueur;
import hocusPocus.Partie.Plateau;
import hocusPocus.Partie.ResoudrePouvoirHocus;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ControllerInteractionJoueur implements ActionListener{
private InteractionJoueur interactionJoueur;
private InterfacePlateau interfacePlateau;
public ControllerInteractionJoueur(InteractionJoueur interactionJoueur) {
this.interactionJoueur = interactionJoueur;
this.interfacePlateau = Jeu.getInstance().getInterfacePlateau();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() != null) {
if(e.getSource() == interactionJoueur.btnOk) {
for(int i = 0; i < interactionJoueur.tableIndexJoueur.size(); i ++) {
if(interactionJoueur.tableIndexJoueur.get(i).isSelected()){ // Joueur voulant reagir
Plateau.getInstance().setJoueurReagissant(Jeu.getListeJoueurs().get(i));
interfacePlateau.rafraichirPanelJoueurReagissant();
interfacePlateau.rafraichirPanelActionJoueur();
interactionJoueur.dispose();
}
}
}
if(e.getSource() == interactionJoueur.btnResoudreCartes) { // Resolution des cartes
AnalyseZoneDeJeu analyseZoneDeJeu = new AnalyseZoneDeJeu();
analyseZoneDeJeu.Resolution();
Plateau.getInstance().setJoueurReagissant(Plateau.getInstance().getJoueurCourant());
interfacePlateau.rafraichirPanelJoueurCourant();
interfacePlateau.rafraichirPanelActionJoueur();
interactionJoueur.dispose();
// Pose d'une nouvelle Hocus ou fin du tour
}
}
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Controllers/ControllerInteractionJoueur.java | Java | mit | 1,825 |
package hocusPocus.Controllers;
import hocusPocus.IHM.ChoixFinTour;
import hocusPocus.IHM.InterfacePlateau;
import hocusPocus.IHM.LimiteCarteMain;
import hocusPocus.Partie.Plateau;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
public class ControllerChoixFinTour implements ActionListener {
private ChoixFinTour choixFinTour;
private InterfacePlateau interfacePlateau;
private Plateau plateau;
public ControllerChoixFinTour(ChoixFinTour choixFinTour, InterfacePlateau interfacePlateau) {
this.choixFinTour = choixFinTour;
this.interfacePlateau = interfacePlateau;
this.plateau = Plateau.getInstance();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == choixFinTour.cartes){
ChoixFinTour.piocherCarte = true;
ChoixFinTour.piocherGemmes = false;
}
if(e.getSource() == choixFinTour.gemme){
ChoixFinTour.piocherCarte = false;
ChoixFinTour.piocherGemmes = true;
}
if(e.getSource() == choixFinTour.ok){
if(ChoixFinTour.piocherGemmes == false && ChoixFinTour.piocherCarte == false)
JOptionPane.showMessageDialog(null,"Erreur : pas de pioche choisie", "Erreur", JOptionPane.ERROR_MESSAGE);
else{
if(ChoixFinTour.piocherGemmes) {
System.out.println("Selection : pioche gemme");
plateau.getJoueurCourant().ajouterUnGemme(plateau.getChaudron().piocherUnGemme());
}
else {
System.out.println("Selection : pioche cartes");
plateau.getJoueurCourant().ajouterCartesMain(plateau.getBibliotheque().piocherCarte(2));
if(plateau.getJoueurCourant().getMain().size() > 5) {
new LimiteCarteMain(interfacePlateau);
}
}
plateau.joueurSuivant(plateau.getJoueurCourant()); // Changement de joueur courant
plateau.setJoueurReagissant(plateau.getJoueurCourant());
plateau.defausserZDJ(); // ON VIDE LA ZDJ POUR LE MOMENT
choixFinTour.dispose();
ChoixFinTour.piocherCarte = false;
ChoixFinTour.piocherGemmes = false;
}
JOptionPane.showMessageDialog(null, "A " + plateau.getJoueurCourant().getNom() + " de jouer.");
interfacePlateau.rafraichirPlateauEntier();
}
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Controllers/ControllerChoixFinTour.java | Java | mit | 2,238 |
package hocusPocus.Controllers;
import hocusPocus.IHM.InformationJoueur;
import hocusPocus.IHM.NombreJoueurs;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ControllerNbJoueur implements ActionListener {
public NombreJoueurs nbJoueur;
public InformationJoueur infoJoueur;
public ControllerNbJoueur(NombreJoueurs nbJoueur) {
this.nbJoueur = nbJoueur;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == nbJoueur.btnOk) {
if (nbJoueur.radioButton.isSelected())
nbJoueur.setNbJoueurs(2);
if (nbJoueur.radioButton_1.isSelected())
nbJoueur.setNbJoueurs(3);
if (nbJoueur.radioButton_2.isSelected())
nbJoueur.setNbJoueurs(4);
if (nbJoueur.radioButton_3.isSelected())
nbJoueur.setNbJoueurs(5);
if (nbJoueur.radioButton_4.isSelected())
nbJoueur.setNbJoueurs(6);
nbJoueur.dispose();
infoJoueur = new InformationJoueur(nbJoueur.getNbJoueurs());
}
if (e.getSource() == nbJoueur.btnAnnuler) {
nbJoueur.dispose();
}
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Controllers/ControllerNbJoueur.java | Java | mit | 1,076 |
package hocusPocus.Cartes;
public class PBaguetteMagique extends Carte{
public PBaguetteMagique(int puissance) {
this.recto = this.getClass().getName() + puissance +".png";
this.typecarte = typeCarte.POCUS;
this.puissance = puissance;
this.infoBulle = "<html>POCUS Baguette Magique<br/>Doublez le chiffre d'une carte HOCUS<br/>(Une seule baguette magique par carte HOCUS)";
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Cartes/PBaguetteMagique.java | Java | mit | 403 |
package hocusPocus.Cartes;
public class HHibou extends Carte{
public HHibou(int puissance) {
this.recto = this.getClass().getName() + puissance +".png";
this.typecarte = typeCarte.HOCUS;
this.puissance = puissance;
this.infoBulle = "<html>HOCUS Hiboux<br/>Volez " + getPuissance() + " carte(s) du<br/>grimoire d'un joueur de votre choix.";
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Cartes/HHibou.java | Java | mit | 369 |
package hocusPocus.Cartes;
import java.util.ArrayList;
/**
* Permet de decrire l'ensemble des cartes a instancier
* suivant le nombre de joueurs (nom, nombre, pouvoir)
* @author Quentin
*
*/
public class DescriptionCartes {
public String nomCarte;
public int[] pouvoir;
public int nbExemplaire;
public static ArrayList<DescriptionCartes> partieDeuxJoueurs() {
ArrayList<DescriptionCartes> descriptionGlobale = new ArrayList<DescriptionCartes>();
for(int i = 0; i < 16; i++) {
DescriptionCartes description = new DescriptionCartes();
if(i == 0) {
description.nomCarte = "HAbracadabra";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 1) {
description.nomCarte = "HBouleDeCristal";
description.nbExemplaire = 3;
description.pouvoir = new int[] {0, 0, 0};
}
if(i == 2) {
description.nomCarte = "HHibou";
description.nbExemplaire = 3;
description.pouvoir = new int[] {1, 1, 2};
}
if(i == 3) {
description.nomCarte = "HInspiration";
description.nbExemplaire = 5;
description.pouvoir = new int[] {2, 2, 2, 3, 3};
}
if(i == 4) {
description.nomCarte = "HMalediction";
description.nbExemplaire = 3;
description.pouvoir = new int[] {1, 1, 2};
}
if(i == 5) {
description.nomCarte = "HSacrifice";
description.nbExemplaire = 2;
description.pouvoir = new int[] {2, 2};
}
if(i == 6) {
description.nomCarte = "HSortilege";
description.nbExemplaire = 15;
description.pouvoir = new int[] {1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5};
}
if(i == 7) {
description.nomCarte = "HVoleur";
description.nbExemplaire = 15;
description.pouvoir = new int[] {1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5};
}
if(i == 8) {
description.nomCarte = "HVortex";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 9) {
description.nomCarte = "PAmulette";
description.nbExemplaire = 7;
description.pouvoir = new int[] {0, 0, 0, 0, 0, 0, 0};
}
if(i == 10) {
description.nomCarte = "PBaguetteMagique";
description.nbExemplaire = 4;
description.pouvoir = new int[] {0, 0, 0, 0};
}
if(i == 11) {
description.nomCarte = "PChatNoir";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 12) {
description.nomCarte = "PCitrouille";
description.nbExemplaire = 3;
description.pouvoir = new int[] {0, 0, 0};
}
if(i == 13) {
description.nomCarte = "PContreSort";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 14) {
description.nomCarte = "PEclair";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 15) {
description.nomCarte = "PSablier";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
descriptionGlobale.add(description);
}
return descriptionGlobale;
}
public static ArrayList<DescriptionCartes> partiePlusDeDeuxJoueurs() {
ArrayList<DescriptionCartes> descriptionGlobale = new ArrayList<DescriptionCartes>();
for(int i = 0; i < 17; i++) {
DescriptionCartes description = new DescriptionCartes();
if(i == 0) {
description.nomCarte = "HAbracadabra";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 1) {
description.nomCarte = "HBouleDeCristal";
description.nbExemplaire = 3;
description.pouvoir = new int[] {0, 0, 0};
}
if(i == 2) {
description.nomCarte = "HHibou";
description.nbExemplaire = 3;
description.pouvoir = new int[] {1, 1, 2};
}
if(i == 3) {
description.nomCarte = "HInspiration";
description.nbExemplaire = 5;
description.pouvoir = new int[] {2, 2, 2, 3, 3};
}
if(i == 4) {
description.nomCarte = "HMalediction";
description.nbExemplaire = 3;
description.pouvoir = new int[] {1, 1, 2};
}
if(i == 5) {
description.nomCarte = "HSacrifice";
description.nbExemplaire = 2;
description.pouvoir = new int[] {2, 2};
}
if(i == 6) {
description.nomCarte = "HSortilege";
description.nbExemplaire = 15;
description.pouvoir = new int[] {1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5};
}
if(i == 7) {
description.nomCarte = "HVoleur";
description.nbExemplaire = 15;
description.pouvoir = new int[] {1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5};
}
if(i == 8) {
description.nomCarte = "HVortex";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 9) {
description.nomCarte = "PAmulette";
description.nbExemplaire = 4; // Retirer 3
description.pouvoir = new int[] {0, 0, 0, 0};
}
if(i == 10) {
description.nomCarte = "PBaguetteMagique";
description.nbExemplaire = 4;
description.pouvoir = new int[] {0, 0, 0, 0};
}
if(i == 11) {
description.nomCarte = "PChatNoir";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 12) {
description.nomCarte = "PCitrouille";
description.nbExemplaire = 3;
description.pouvoir = new int[] {0, 0, 0};
}
if(i == 13) {
description.nomCarte = "PContreSort";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 14) {
description.nomCarte = "PEclair";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
if(i == 15) {
description.nomCarte = "PMiroirEnchante";
description.nbExemplaire = 3;
description.pouvoir = new int[] {0, 0, 0};
}
if(i == 16) {
description.nomCarte = "PSablier";
description.nbExemplaire = 2;
description.pouvoir = new int[] {0, 0};
}
descriptionGlobale.add(description);
}
return descriptionGlobale;
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Cartes/DescriptionCartes.java | Java | mit | 6,058 |
package hocusPocus.Cartes;
public class HAbracadabra extends Carte{
public HAbracadabra(int puissance) {
this.recto = this.getClass().getName() + puissance +".png";
this.typecarte = typeCarte.HOCUS;
this.puissance = puissance;
this.infoBulle = "<html>HOCUS Abracadabra<br/>Echangez votre main avec celle<br/>d'un joueur de votre choix.";
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Cartes/HAbracadabra.java | Java | mit | 373 |
package hocusPocus.Cartes;
public class HVoleur extends Carte{
public HVoleur(int puissance) {
this.recto = this.getClass().getName() + puissance +".png";
this.typecarte = typeCarte.HOCUS;
this.puissance = puissance;
this.infoBulle = "<html>HOCUS Voleur<br/>Volez " + getPuissance() + " gemme(s) d'un joueur<br/>de votre choix";
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Cartes/HVoleur.java | Java | mit | 358 |
package hocusPocus.Cartes;
import hocusPocus.Partie.Joueur;
public class Carte {
protected int puissance; // Correspond au numero en haut a droite de la carte Hocus -> '0' pour Pocus
protected String recto; // Nom du fichier image de la carte
protected String verso = "verso.png";
protected typeCarte typecarte; // Hocus ou Pocus
protected String localisation; // Stocker l'endroit de la carte : main, grimoire, zonedejeu,bibliotheque
protected boolean estJouable; //permettant de verifier qu'une carte peut etre jouee dans le tour actuel
protected Joueur joueurPossesseur;
protected String infoBulle;
public String getRecto() {
return recto;
}
public String getVerso() {
return verso;
}
public String getLocalisation() {
return localisation;
}
public void setLocalisation(String localisation) {
this.localisation = localisation;
}
public int getPuissance() {
return puissance;
}
public String getInfoBulle() {
return infoBulle;
}
public Joueur getJoueurPossesseur() {
return joueurPossesseur;
}
public void setJoueurPossesseur(Joueur joueurPossesseur) {
this.joueurPossesseur = joueurPossesseur;
}
public typeCarte getTypecarte() {
return typecarte;
}
public void setTypecarte(typeCarte typecarte) {
this.typecarte = typecarte;
}
public void setPuissance(int puissance) {
this.puissance = puissance;
}
@Override
public String toString() {
return "\nCarte [puissance=" + puissance + ",\n recto=" + recto
+ ",\n verso=" + verso + ",\n typecarte=" + typecarte
+ ",\n localisation=" + localisation + ",\n estJouable="
+ estJouable + ",\n joueurPossesseur=" + joueurPossesseur + "]\n";
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Cartes/Carte.java | Java | mit | 1,728 |
package hocusPocus.Cartes;
public enum typeCarte {
HOCUS,
POCUS;
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Cartes/typeCarte.java | Java | mit | 70 |
package hocusPocus.IHM;
import hocusPocus.Controllers.ControllerTypeDePartie;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.WindowConstants;
import java.awt.Toolkit;
public class TypeDePartie extends JDialog {
private static final long serialVersionUID = 1L;
public static boolean partieNormale = true;
public static boolean partieRapide = false;
public JRadioButton normale;
public JRadioButton rapide;
public ButtonGroup group;
public JButton ok;
public JButton annuler;
/**
* Creer la fenetre qui permet de selectionner le
* type de partie: normale ou rapide
*/
public TypeDePartie(){
setIconImage(Toolkit.getDefaultToolkit().getImage(TypeDePartie.class.getResource("/images/icone.gif")));
setResizable(false);
setTitle("Hocus Pocus");
ControllerTypeDePartie controleTypeDePartie = new ControllerTypeDePartie(this);
this.setBounds(100, 100, 299, 207);
this.setLocationRelativeTo(this.getParent());
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.getContentPane().setLayout(null);
JLabel label = new JLabel("Type de partie : ");
label.setBounds(22, 11, 178, 14);
this.getContentPane().add(label);
group = new ButtonGroup();
normale = new JRadioButton("Normale");
normale.setBounds(97, 37, 109, 23);
normale.setSelected(true);
normale.addActionListener(controleTypeDePartie);
this.getContentPane().add(normale);
rapide= new JRadioButton("Rapide");
rapide.setBounds(97, 74, 109, 23);
rapide.addActionListener(controleTypeDePartie);
this.getContentPane().add(rapide);
group.add(normale);
group.add(rapide);
ok = new JButton("OK");
ok.setBounds(47, 133, 89, 23);
ok.addActionListener(controleTypeDePartie);
this.getContentPane().add(ok);
annuler = new JButton("Annuler");
annuler.setBounds(165, 133, 89, 23);
this.getContentPane().add(annuler);
annuler.addActionListener(controleTypeDePartie);
this.setVisible(true);
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/IHM/TypeDePartie.java | Java | mit | 2,138 |
package hocusPocus.IHM;
import hocusPocus.Controllers.ControllerNbJoueur;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.WindowConstants;
import java.awt.Toolkit;
/**
* Fenetre permettant de demander a l'utilisateur le nombre
* de joueurs a inclure dans la partie
* @author Quentin
*
*/
public class NombreJoueurs extends JFrame{
private static final long serialVersionUID = 1L;
public int nbJoueurs = 2;
public JButton btnOk;
public JButton btnAnnuler;
public JRadioButton radioButton, radioButton_1, radioButton_2, radioButton_3, radioButton_4;
public NombreJoueurs() throws HeadlessException {
setIconImage(Toolkit.getDefaultToolkit().getImage(NombreJoueurs.class.getResource("/images/icone.gif")));
setResizable(false);
recupererNombreJoueurs();
}
public void recupererNombreJoueurs() {
ControllerNbJoueur controle = new ControllerNbJoueur(this);
final ButtonGroup buttonGroup = new ButtonGroup();
this.setTitle("Hocus Pocus");
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBounds(100, 100, 297, 293);
this.setLocationRelativeTo(this.getParent()); // Centrer la fenetre
getContentPane().setLayout(null);
JLabel lblNbJoueurs = new JLabel("Veuillez s\u00E9lectionner le nombre de joueurs");
lblNbJoueurs.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblNbJoueurs.setBounds(10, 11, 292, 28);
getContentPane().add(lblNbJoueurs);
radioButton = new JRadioButton("2");
radioButton.setSelected(true);
buttonGroup.add(radioButton);
radioButton.setBounds(44, 47, 109, 25);
getContentPane().add(radioButton);
radioButton_1 = new JRadioButton("3");
buttonGroup.add(radioButton_1);
radioButton_1.setBounds(44, 107, 109, 25);
getContentPane().add(radioButton_1);
radioButton_2 = new JRadioButton("4");
buttonGroup.add(radioButton_2);
radioButton_2.setBounds(44, 167, 127, 25);
getContentPane().add(radioButton_2);
radioButton_3 = new JRadioButton("5");
buttonGroup.add(radioButton_3);
radioButton_3.setBounds(156, 47, 127, 25);
getContentPane().add(radioButton_3);
radioButton_4 = new JRadioButton("6");
buttonGroup.add(radioButton_4);
radioButton_4.setBounds(156, 107, 127, 25);
getContentPane().add(radioButton_4);
btnOk = new JButton("Ok");
btnOk.addActionListener(controle);
btnOk.setBounds(25, 219, 97, 25);
getContentPane().add(btnOk);
btnAnnuler = new JButton("Annuler");
btnAnnuler.addActionListener(controle);
btnAnnuler.setBounds(157, 219, 97, 25);
getContentPane().add(btnAnnuler);
this.setVisible(true);
}
public void setNbJoueurs(int nbJoueurs) {
this.nbJoueurs = nbJoueurs;
}
public int getNbJoueurs() {
return nbJoueurs;
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/IHM/NombreJoueurs.java | Java | mit | 3,031 |
package hocusPocus.IHM;
import hocusPocus.Controllers.ControllerChoixFinTour;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.WindowConstants;
import java.awt.Toolkit;
public class ChoixFinTour extends JFrame {
private static final long serialVersionUID = 1L;
public static boolean piocherCarte = false;
public static boolean piocherGemmes = false;
public JRadioButton cartes;
public JRadioButton gemme;
public ButtonGroup group;
public JButton ok;
/**
* Creer la fenetre qui permet de choisir le
* type de pioche du joueur gaganant le tour
*/
public ChoixFinTour(InterfacePlateau interfacePlateau){
setIconImage(Toolkit.getDefaultToolkit().getImage(ChoixFinTour.class.getResource("/images/icone.gif")));
setResizable(false);
setTitle("Hocus Pocus");
ControllerChoixFinTour controleChoixFinTour = new ControllerChoixFinTour(this, interfacePlateau);
this.setBounds(100, 100, 299, 207);
this.setLocationRelativeTo(this.getParent());
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.getContentPane().setLayout(null);
JLabel label = new JLabel("Fin du tour, choisir type de pioche : ");
label.setBounds(22, 11, 219, 14);
this.getContentPane().add(label);
group = new ButtonGroup();
cartes = new JRadioButton("2 cartes");
cartes.setBounds(91, 48, 109, 23);
cartes.addActionListener(controleChoixFinTour);
this.getContentPane().add(cartes);
gemme= new JRadioButton("1 gemme");
gemme.setBounds(91, 85, 109, 23);
gemme.addActionListener(controleChoixFinTour);
this.getContentPane().add(gemme);
group.add(cartes);
group.add(gemme);
ok = new JButton("OK");
ok.setBounds(98, 135, 89, 23);
ok.addActionListener(controleChoixFinTour);
this.getContentPane().add(ok);
this.setVisible(true);
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/IHM/ChoixFinTour.java | Java | mit | 1,965 |
package hocusPocus.IHM;
import hocusPocus.Controllers.ControllerEcranAccueil;
import hocusPocus.Partie.Jeu;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
/**
* Affichage de la fenetre d'acceuil au demarrage
*
*/
public class EcranAccueil extends JFrame {
private Jeu jeu;
private static EcranAccueil _instance = null;
public JMenuItem mntmNouvellePartie;
public JMenuBar menuBar;
public JMenu mnPartie;
public JMenuItem mntmQuitter;
public JMenu mnAide;
public JMenuItem mntmRgleDuJeu;
public JMenu menu;
public JMenuItem mntmAPropos;
public JPanel contentPane;
private EcranAccueil() {
this.jeu = Jeu.getInstance();
lancerIHM();
}
public static EcranAccueil getInstance(){
if(_instance == null)
_instance = new EcranAccueil();
return _instance;
}
/**
* Creation de la fenetre principale avec la
* barre de menu
*/
public void lancerIHM() {
int width = Toolkit.getDefaultToolkit().getScreenSize().width;
int heigh = Toolkit.getDefaultToolkit().getScreenSize().height;
ControllerEcranAccueil controle = new ControllerEcranAccueil(this);
setIconImage(new ImageIcon(this.getClass().getResource("/images/icone.gif")).getImage());
setResizable(false);
setBackground(Color.WHITE);
setTitle("Hocus Pocus");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
setSize(width, heigh);
setLocation(0, 0);
menuBar = new JMenuBar();
setJMenuBar(menuBar);
mnPartie = new JMenu("Partie");
menuBar.add(mnPartie);
mntmNouvellePartie = new JMenuItem("Nouvelle Partie");
mnPartie.add(mntmNouvellePartie);
mntmNouvellePartie.addActionListener(controle);
mntmQuitter = new JMenuItem("Quitter");
mntmQuitter.addActionListener(controle);
mnPartie.add(mntmQuitter);
mnAide = new JMenu("Aide");
menuBar.add(mnAide);
mntmRgleDuJeu = new JMenuItem("Regles du jeu");
mntmRgleDuJeu.addActionListener(controle);
mnAide.add(mntmRgleDuJeu);
menu = new JMenu("?");
menuBar.add(menu);
mntmAPropos = new JMenuItem("A Propos");
mntmAPropos.addActionListener(controle);
menu.add(mntmAPropos);
contentPane = new JPanel();
contentPane.setBackground(Color.YELLOW);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setIcon(new ImageIcon(EcranAccueil.class.getResource("/images/BoiteDuJeu.gif")));
contentPane.add(lblNewLabel, BorderLayout.WEST);
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setIcon(new ImageIcon(EcranAccueil.class.getResource("/images/carte.gif")));
contentPane.add(lblNewLabel_1, BorderLayout.EAST);
this.setVisible(true);
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/IHM/EcranAccueil.java | Java | mit | 3,196 |
package hocusPocus.IHM;
import hocusPocus.Cartes.Carte;
import hocusPocus.Controllers.ControllerLimiteCarteMain;
import hocusPocus.Partie.Joueur;
import hocusPocus.Partie.Plateau;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.border.TitledBorder;
import com.mortennobel.imagescaling.experimental.ImprovedMultistepRescaleOp;
public class LimiteCarteMain extends JFrame {
private static final long serialVersionUID = 1L;
private Plateau plateau;
private Joueur joueurCourant;
public Hashtable<JToggleButton, Carte> tableCorrespondance;
public static Carte carteSelectionneeMain;
public JButton btnDefausser;
public JToggleButton jbutton;
public JPanel panelMain;
private InterfacePlateau interfacePlateau;
private ControllerLimiteCarteMain controller;
public LimiteCarteMain(InterfacePlateau interfacePlateau) {
setIconImage(Toolkit.getDefaultToolkit().getImage(
LimiteCarteMain.class.getResource("/images/icone.gif")));
setResizable(false);
plateau = Plateau.getInstance();
joueurCourant = plateau.getJoueurCourant();
tableCorrespondance = new Hashtable<JToggleButton, Carte>();
this.interfacePlateau = interfacePlateau;
getContentPane().setLayout(new GridLayout(1, 1, 0, 0));
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setSize(990, 506);
this.setTitle("Mettre en Defausse des cartes en Main");
this.setLocationRelativeTo(this.getParent()); // Centrer la fenetre
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(new GridLayout(2, 1, 0, 0));
panelMain = new JPanel();
panelMain.setBorder(new TitledBorder(null, "Cartes en Main",
TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel.add(panelMain);
JPanel Boutons = new JPanel();
panel.add(Boutons);
Boutons.setLayout(null);
controller = new ControllerLimiteCarteMain(this, joueurCourant, tableCorrespondance);
btnDefausser = new JButton("D\u00E9fausser");
btnDefausser.addActionListener(controller);
btnDefausser.setBounds(437, 79, 117, 23);
Boutons.add(btnDefausser);
JLabel lblVousNePouvez = new JLabel(
"Vous ne pouvez avoir que 5 cartes en Main Maximum !");
lblVousNePouvez.setHorizontalAlignment(SwingConstants.CENTER);
lblVousNePouvez.setBounds(10, 11, 964, 14);
Boutons.add(lblVousNePouvez);
JLabel lblVeuillezSlectionnerLes = new JLabel(
"Veuillez s\u00E9lectionner les cartes que vous souhaitez mettre sur la pile de d\u00E9fausse.");
lblVeuillezSlectionnerLes.setHorizontalAlignment(SwingConstants.CENTER);
lblVeuillezSlectionnerLes.setBounds(10, 42, 964, 14);
Boutons.add(lblVeuillezSlectionnerLes);
afficherMain();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public void afficherMain() {
BufferedImage imageCarte = null;
final ButtonGroup groupeBoutonsCartesMain = new ButtonGroup();
for (int i = 0; i < joueurCourant.getMain().size(); i++) { // Affichage
// main
jbutton = new JToggleButton("");
imageCarte = resize(joueurCourant.getMain().get(i).getRecto(), 95,
160);
jbutton.setIcon(new ImageIcon(imageCarte));
jbutton.setToolTipText(joueurCourant.getMain().get(i)
.getInfoBulle());
panelMain.add(jbutton);
groupeBoutonsCartesMain.add(jbutton);
tableCorrespondance.put(jbutton, joueurCourant.getMain().get(i));
jbutton.addActionListener(controller);
}
}
public void rafraichirAfficherMain() {
panelMain.removeAll();
panelMain.revalidate();
afficherMain();
}
public static BufferedImage resize(String nomImageCarte, int width,
int height) {
BufferedImage img = null;
ImprovedMultistepRescaleOp resampleOp = new ImprovedMultistepRescaleOp(
width, height);
try {
img = ImageIO.read(new File("./src/images/"
+ nomImageCarte.replace("hocusPocus.Cartes.", "")));
} catch (IOException e) {
e.printStackTrace();
}
return resampleOp.filter(img, null);
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/IHM/LimiteCarteMain.java | Java | mit | 4,558 |
package hocusPocus.IHM;
import hocusPocus.Cartes.Carte;
import hocusPocus.Controllers.ControllerInterfacePlateau;
import hocusPocus.Partie.Joueur;
import hocusPocus.Partie.Plateau;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import net.miginfocom.swing.MigLayout;
import com.mortennobel.imagescaling.experimental.ImprovedMultistepRescaleOp;
import java.awt.Component;
import java.awt.Color;
public class InterfacePlateau extends JPanel{
public JButton btnJouerCarte, btnPasserTour, btnEchangerCartes;
public final HashMap<JToggleButton, Carte> tableCorrespondance = new HashMap<JToggleButton, Carte>();
private Plateau plateau ;
private Joueur joueurCourant, joueurReagissant ;
private JPanel panelListeJoueur, panelCartesJoueurCourant, panelChaudron, panelBibliotheque, panelZoneDeJeu, panelPlateauDeJeu, panelActionJoueur;
private Carte carteSelectionnee;
private int widthGrimoireJoueurAtt = 80; // Largeur cartes grimoire
private int heightGrimoireJoueurAtt = 110; // Hauteur cartes grimoire
private BufferedImage imageCarte ;
private JPanel grimoire;
private JPanel main;
private JPanel panelDefausse;
private JLabel lblCarteDefausse;
private JLabel imageCarteDefausse;
public InterfacePlateau() {
this.plateau = Plateau.getInstance();
this.joueurCourant = plateau.getJoueurCourant();
this.joueurReagissant = plateau.getJoueurReagissant();
setLayout(new BorderLayout(0, 0));
panelListeJoueur = new JPanel();
add(panelListeJoueur, BorderLayout.WEST);
GridBagLayout gbl_listeJoueur = new GridBagLayout();
gbl_listeJoueur.columnWidths = new int[] { 0, 0 };
gbl_listeJoueur.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0 };
gbl_listeJoueur.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
gbl_listeJoueur.rowWeights = new double[] { 1.0, 1.0, 1.0, 1.0, 1.0,
1.0, Double.MIN_VALUE };
panelListeJoueur.setLayout(gbl_listeJoueur);
afficherPanelListeJoueurs();
panelPlateauDeJeu = new JPanel();
add(panelPlateauDeJeu, BorderLayout.CENTER);
panelPlateauDeJeu.setLayout(new GridLayout(2, 1, 0, 0));
panelZoneDeJeu = new JPanel();
panelZoneDeJeu.setBackground(new Color(34, 139, 34));
panelZoneDeJeu.setBorder(new TitledBorder(null, "Zone de jeu",
TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelPlateauDeJeu.add(panelZoneDeJeu);
afficherPanelZoneDeJeu();
panelCartesJoueurCourant = new JPanel();
panelCartesJoueurCourant.setLayout(new GridLayout(2, 1, 0, 0));
grimoire = new JPanel();
grimoire.setBorder(new TitledBorder(null, "Grimoire", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelCartesJoueurCourant.add(grimoire);
main = new JPanel();
main.setBorder(new TitledBorder(null, "Main", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelCartesJoueurCourant.add(main);
afficherJoueurCourant();
JPanel panelDroite = new JPanel();
add(panelDroite, BorderLayout.EAST);
panelDroite.setLayout(new GridLayout(0, 1, 0, 0));
panelChaudron = new JPanel();
panelDroite.add(panelChaudron);
panelChaudron.setBorder(new TitledBorder(null, "Chaudron",
TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelChaudron.setLayout(new GridLayout(1, 1, 0, 0));
afficherPanelChaudron();
panelBibliotheque = new JPanel();
panelBibliotheque.setBorder(new TitledBorder(null, "Bibliotheque",
TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelDroite.add(panelBibliotheque);
panelBibliotheque.setLayout(new BoxLayout(panelBibliotheque, BoxLayout.Y_AXIS));
afficherPanelBibliotheque();
panelDefausse = new JPanel();
panelDefausse.setBorder(new TitledBorder(null, "Defausse", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelDroite.add(panelDefausse);
panelDefausse.setLayout(new BoxLayout(panelDefausse, BoxLayout.Y_AXIS));
afficherPanelDefausse();
panelActionJoueur = new JPanel();
panelDroite.add(panelActionJoueur);
panelActionJoueur.setBorder(new TitledBorder(null, "Action Joueur",
TitledBorder.LEADING, TitledBorder.TOP, null, null));
panelActionJoueur.setLayout(new MigLayout("", "[]", "[][][]"));
afficherPanelActionJoueur();
}
public void afficherPanelActionJoueur() {
this.joueurReagissant = plateau.getJoueurReagissant();
this.joueurCourant = plateau.getJoueurCourant();
btnJouerCarte = new JButton(" Jouer Carte ");
btnJouerCarte.setEnabled(false);
panelActionJoueur.add(btnJouerCarte, "cell 0 0");
btnJouerCarte.addActionListener(new ControllerInterfacePlateau(this));
btnEchangerCartes = new JButton("Echanger Cartes ");
panelActionJoueur.add(btnEchangerCartes, "cell 0 1");
btnEchangerCartes.addActionListener(new ControllerInterfacePlateau(this));
if( joueurReagissant == null || joueurCourant == joueurReagissant)
btnEchangerCartes.setEnabled(true);
else
btnEchangerCartes.setEnabled(false);
btnPasserTour = new JButton(" Terminer Tour ");
panelActionJoueur.add(btnPasserTour, "cell 0 2");
btnPasserTour.addActionListener(new ControllerInterfacePlateau(this));
if( joueurReagissant == null || joueurCourant == joueurReagissant)
btnPasserTour.setEnabled(true);
else
btnPasserTour.setEnabled(false);
}
public void rafraichirPanelActionJoueur() {
panelActionJoueur.removeAll();
panelActionJoueur.revalidate();
afficherPanelActionJoueur();
}
public void afficherPanelListeJoueurs() {
int cpt = 0;
for(int i = 0; i < plateau.getListeJoueurs().size(); i ++) { // Pour chaque joueur
JPanel jpJoueur = new JPanel();
jpJoueur.setBorder(new TitledBorder(null, plateau.listeJoueurs
.get(i).getNom(), TitledBorder.LEADING, TitledBorder.TOP,
null, null));
GridBagConstraints gbc_Joueur = new GridBagConstraints();
gbc_Joueur.insets = new Insets(0, 0, 5, 0);
gbc_Joueur.fill = GridBagConstraints.BOTH;
gbc_Joueur.gridx = 0;
gbc_Joueur.gridy = i;
panelListeJoueur.add(jpJoueur, gbc_Joueur);
jpJoueur.setLayout(new BoxLayout(jpJoueur, BoxLayout.LINE_AXIS));
JLabel lblGrimoire = new JLabel("" + plateau.listeJoueurs.get(i).getNbGemmes());
lblGrimoire.setIcon(new ImageIcon(InterfacePlateau.class.getResource("/images/G.png")));
jpJoueur.add(lblGrimoire);
JPanel CarteGrimoire = new JPanel();
CarteGrimoire.setBorder(new TitledBorder(null, "Grimoire",
TitledBorder.LEADING, TitledBorder.TOP, null, null));
jpJoueur.add(CarteGrimoire);
CarteGrimoire.setLayout(new BoxLayout(CarteGrimoire,
BoxLayout.X_AXIS));
// Affichage des cartes du grimoire
for(int j = 0; j < plateau.listeJoueurs.get(i).getGrimoire().size(); j++) {
JLabel lblCarteGrimoire = new JLabel("");
lblCarteGrimoire.setIcon(new ImageIcon(
imageCarte = resize(plateau.listeJoueurs.get(i)
.getGrimoire().get(j).getRecto(),
widthGrimoireJoueurAtt, heightGrimoireJoueurAtt)));
lblCarteGrimoire.setToolTipText(plateau.listeJoueurs.get(i)
.getGrimoire().get(j).getInfoBulle());
CarteGrimoire.add(lblCarteGrimoire);
}
cpt = plateau.listeJoueurs.get(i).getGrimoire().size();
if(plateau.listeJoueurs.get(i).getGrimoire().size() < 3) {
do {
JLabel lblCarteVide = new JLabel("");
lblCarteVide.setIcon(new ImageIcon(
imageCarte = resize("Vide.png",
widthGrimoireJoueurAtt, heightGrimoireJoueurAtt)));
CarteGrimoire.add(lblCarteVide);
cpt++;
}while (cpt < 3);
}
}
}
public void rafraichirPanelListeJoueurs() {
panelListeJoueur.removeAll();
panelListeJoueur.revalidate();
afficherPanelListeJoueurs();
}
public void afficherJoueurCourant() {
final ButtonGroup groupeBoutonsCartes = new ButtonGroup();
this.joueurCourant = plateau.getJoueurCourant();
panelPlateauDeJeu.add(panelCartesJoueurCourant);
tableCorrespondance.clear();
panelCartesJoueurCourant.setBorder(new TitledBorder(null,
"Joueur courant : " + joueurCourant.getNom() +" | Gemmes : "+joueurCourant.getNbGemmes(),
TitledBorder.LEADING, TitledBorder.TOP, null, null));
//Affichage du grimoire
for (int i = 0; i < joueurCourant.getGrimoire().size(); i++) {
JToggleButton jbutton = new JToggleButton("");
imageCarte = resize(joueurCourant.getGrimoire().get(i).getRecto(), 95,
160);
jbutton.setIcon(new ImageIcon(imageCarte));
jbutton.setToolTipText(joueurCourant.getGrimoire().get(i).getInfoBulle());
grimoire.add(jbutton);
groupeBoutonsCartes.add(jbutton);
tableCorrespondance.put(jbutton, joueurCourant.getGrimoire().get(i));
jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if((JToggleButton)arg0.getSource()!=null) {
carteSelectionnee = tableCorrespondance.get((JToggleButton)arg0.getSource());
btnJouerCarte.setEnabled(true);
}
}
});
}
//Affichage de la main
for (int i = 0; i < joueurCourant.getMain().size(); i++) {
JToggleButton jbutton = new JToggleButton("");
imageCarte = resize(joueurCourant.getMain().get(i).getRecto(),
95, 160);
jbutton.setIcon(new ImageIcon(imageCarte));
jbutton.setToolTipText(joueurCourant.getMain().get(i).getInfoBulle());
main.add(jbutton);
groupeBoutonsCartes.add(jbutton);
tableCorrespondance.put(jbutton, joueurCourant.getMain().get(i));
jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if((JToggleButton)arg0.getSource()!=null) {
carteSelectionnee = tableCorrespondance.get((JToggleButton)arg0.getSource());
btnJouerCarte.setEnabled(true);
}
}
});
}
}
public void rafraichirPanelJoueurCourant() {
//Rafraichissement du grimoire
grimoire.removeAll();
grimoire.revalidate();
//Rafraichissement de la main
main.removeAll();
main.revalidate();
afficherJoueurCourant();
}
public void afficherJoueurReagissant() {
this.joueurReagissant = plateau.getJoueurReagissant();
final ButtonGroup groupeBoutonsCartes = new ButtonGroup();
panelPlateauDeJeu.add(panelCartesJoueurCourant);
tableCorrespondance.clear();
panelCartesJoueurCourant.setBorder(new TitledBorder(null,
"Joueur reagissant : " + joueurReagissant.getNom(),
TitledBorder.LEADING, TitledBorder.TOP, null, null));
//Affichage du grimoire
for (int i = 0; i < joueurReagissant.getGrimoire().size(); i++) {
JToggleButton jbutton = new JToggleButton("");
imageCarte = resize(joueurReagissant.getGrimoire().get(i).getRecto(), 95,
160);
jbutton.setIcon(new ImageIcon(imageCarte));
jbutton.setToolTipText(joueurReagissant.getGrimoire().get(i).getInfoBulle());
grimoire.add(jbutton);
groupeBoutonsCartes.add(jbutton);
tableCorrespondance.put(jbutton, joueurReagissant.getGrimoire().get(i));
jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if((JToggleButton)arg0.getSource()!=null) {
carteSelectionnee = tableCorrespondance.get((JToggleButton)arg0.getSource());
btnJouerCarte.setEnabled(true);
}
}
});
}
//Affichage de la main
for (int i = 0; i < joueurReagissant.getMain().size(); i++) {
JToggleButton jbutton = new JToggleButton("");
imageCarte = resize(joueurReagissant.getMain().get(i).getRecto(),
95, 160);
jbutton.setIcon(new ImageIcon(imageCarte));
jbutton.setToolTipText(joueurReagissant.getMain().get(i).getInfoBulle());
main.add(jbutton);
groupeBoutonsCartes.add(jbutton);
tableCorrespondance.put(jbutton, joueurReagissant.getMain().get(i));
jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if((JToggleButton)arg0.getSource()!=null) {
carteSelectionnee = tableCorrespondance.get((JToggleButton)arg0.getSource());
btnJouerCarte.setEnabled(true);
}
}
});
}
}
public void rafraichirPanelJoueurReagissant() {
//Rafraichissement du grimoire
grimoire.removeAll();
grimoire.revalidate();
//Rafraichissement de la main
main.removeAll();
main.revalidate();
afficherJoueurReagissant();
}
public void afficherPanelChaudron() {
JLabel lblValeur = new JLabel("= "+ plateau.getChaudron().recupererNbGemmes());
lblValeur.setIcon(new ImageIcon(InterfacePlateau.class.getResource("/images/gemmes.png")));
panelChaudron.add(lblValeur);
}
public void rafraichirPanelChaudron() {
panelChaudron.removeAll();
panelChaudron.revalidate();
afficherPanelChaudron();
}
public void afficherPanelZoneDeJeu() {
JLabel lblZoneDeJeu = new JLabel("");
if(plateau.zoneDeJeu.isEmpty())
imageCarte = resize("Vide.png", 145, 225);
else {
imageCarte = resize(plateau.zoneDeJeu.get(plateau.zoneDeJeu.size() - 1).getRecto(), 145, 225);
lblZoneDeJeu.setToolTipText(plateau.zoneDeJeu.get(plateau.zoneDeJeu.size() - 1).getInfoBulle());
}
lblZoneDeJeu.setIcon(new ImageIcon(imageCarte));
panelZoneDeJeu.add(lblZoneDeJeu);
}
public void rafraichirPanelZoneDeJeu() {
System.out.println("Size ZDJ: " + plateau.getZoneDeJeu().size());
panelZoneDeJeu.removeAll();
panelZoneDeJeu.revalidate();
afficherPanelZoneDeJeu();
}
public void afficherPanelBibliotheque() {
JLabel lblNombreCarteRestantes = new JLabel("Cartes restantes: "
+ plateau.getBibliotheque().getPile().size());
panelBibliotheque.add(lblNombreCarteRestantes);
JLabel lblBibliotheque = new JLabel("");
lblBibliotheque.setAlignmentY(Component.BOTTOM_ALIGNMENT);
lblBibliotheque.setHorizontalAlignment(SwingConstants.CENTER);
lblBibliotheque.setIcon(new ImageIcon(InterfacePlateau.class
.getResource("/images/Recto_100x142.png")));
panelBibliotheque.add(lblBibliotheque);
}
public void rafraichirPanelBibliotheque() {
panelBibliotheque.removeAll();
panelBibliotheque.revalidate();
afficherPanelBibliotheque();
}
public void afficherPanelDefausse() {
lblCarteDefausse = new JLabel("Cartes defausse: "+ plateau.getDefausse().getPile().size());
lblCarteDefausse.setHorizontalAlignment(SwingConstants.CENTER);
lblCarteDefausse.setAlignmentY(3.0f);
panelDefausse.add(lblCarteDefausse);
imageCarteDefausse = new JLabel("");
imageCarteDefausse.setHorizontalAlignment(SwingConstants.CENTER);
if(plateau.getDefausse().getPile().isEmpty())
imageCarte = resize("Recto_100x142.png", 100, 142);
else {
imageCarte = resize(plateau.getDefausse().getPile().peek().getRecto(), 100, 142);
}
imageCarteDefausse.setIcon(new ImageIcon(imageCarte));
panelDefausse.add(imageCarteDefausse);
}
public void rafraichirPanelDefausse() {
panelDefausse.removeAll();
panelDefausse.revalidate();
afficherPanelDefausse();
}
public void rafraichirPlateauEntier() {
rafraichirPanelBibliotheque();
rafraichirPanelDefausse();
rafraichirPanelChaudron();
rafraichirPanelJoueurCourant();
rafraichirPanelListeJoueurs();
rafraichirPanelZoneDeJeu();
rafraichirPanelActionJoueur();
}
/**
* Fonction pour redimensionner les cartes
*
*/
public static BufferedImage resize(String nomImageCarte, int width,
int height) {
BufferedImage img = null;
ImprovedMultistepRescaleOp resampleOp = new ImprovedMultistepRescaleOp(
width, height);
try {
img = ImageIO.read(new File("./src/images/"
+ nomImageCarte.replace("hocusPocus.Cartes.", "")));
} catch (IOException e) {
e.printStackTrace();
}
return resampleOp.filter(img, null);
}
public Carte getCarteSelectionee() {
return carteSelectionnee;
}
public JPanel getGrimoire() {
return grimoire;
}
public void setGrimoire(JPanel grimoire) {
this.grimoire = grimoire;
}
public JPanel getMain() {
return main;
}
public void setMain(JPanel main) {
this.main = main;
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/IHM/InterfacePlateau.java | Java | mit | 16,674 |
package hocusPocus.IHM;
import hocusPocus.Cartes.Carte;
import hocusPocus.Partie.Joueur;
import hocusPocus.Partie.Plateau;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.WindowConstants;
import javax.swing.border.TitledBorder;
import com.mortennobel.imagescaling.experimental.ImprovedMultistepRescaleOp;
import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import java.awt.Component;
import java.awt.Toolkit;
public class EchangerMainGrimoire extends JFrame {
private Plateau plateau;
private Joueur joueurCourant;
private Hashtable<JToggleButton, Carte> tableCorrespondance;
private Carte carteSelectionneeMain;
private Carte carteSelectionneeGrimoire;
private InterfacePlateau interfacePlateau;
private JButton btnEchanger;
public EchangerMainGrimoire(final InterfacePlateau interfacePlateau) {
setIconImage(Toolkit.getDefaultToolkit().getImage(EchangerMainGrimoire.class.getResource("/images/icone.gif")));
setResizable(false);
final ButtonGroup groupeBoutonsCartesGrimoire = new ButtonGroup();
final ButtonGroup groupeBoutonsCartesMain = new ButtonGroup();
plateau = Plateau.getInstance();
joueurCourant = plateau.getJoueurCourant();
tableCorrespondance = new Hashtable<JToggleButton, Carte>();
this.interfacePlateau = interfacePlateau;
getContentPane().setLayout(new GridLayout(1, 1, 0, 0));
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setResizable(true);
this.setSize(766, 650);
this.setTitle("Echanger carte main grimoire");
BufferedImage imageCarte = null;
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(new GridLayout(3, 1, 0, 0));
JPanel panelMain = new JPanel();
panelMain.setBorder(new TitledBorder(null, "Main", TitledBorder.LEFT,
TitledBorder.TOP, null, null));
panel.add(panelMain);
JPanel panelGrimoire = new JPanel();
panelGrimoire.setBorder(new TitledBorder(null, "Grimoire",
TitledBorder.LEFT, TitledBorder.TOP, null, null));
panel.add(panelGrimoire);
JPanel Boutons = new JPanel();
panel.add(Boutons);
GridBagLayout gbl_Boutons = new GridBagLayout();
gbl_Boutons.columnWidths = new int[] { 399, 349, 25 };
gbl_Boutons.rowHeights = new int[] { 110, 23, 0 };
gbl_Boutons.columnWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
gbl_Boutons.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE };
Boutons.setLayout(gbl_Boutons);
btnEchanger = new JButton("Echanger");
btnEchanger.setAlignmentX(Component.CENTER_ALIGNMENT);
btnEchanger.setEnabled(false);
btnEchanger.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (carteSelectionneeGrimoire != null
&& carteSelectionneeMain != null) {
System.out.println("Echange des cartes selectionnees !");
joueurCourant.echangerMainGrimoire(carteSelectionneeMain,
carteSelectionneeGrimoire);
interfacePlateau.rafraichirPanelListeJoueurs();
interfacePlateau.rafraichirPanelJoueurCourant();
dispose();
}
}
});
GridBagConstraints gbc_btnEchanger = new GridBagConstraints();
gbc_btnEchanger.gridx = 0;
gbc_btnEchanger.gridy = 1;
Boutons.add(btnEchanger, gbc_btnEchanger);
JButton btnAnnuler = new JButton("Annuler");
btnAnnuler.setAlignmentX(Component.CENTER_ALIGNMENT);
btnAnnuler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
GridBagConstraints gbc_btnAnnuler = new GridBagConstraints();
gbc_btnAnnuler.gridx = 1;
gbc_btnAnnuler.gridy = 1;
Boutons.add(btnAnnuler, gbc_btnAnnuler);
for (int i = 0; i < joueurCourant.getGrimoire().size(); i++) { // Affichage
// grimoire
JToggleButton jbutton = new JToggleButton("");
imageCarte = resize(joueurCourant.getGrimoire().get(i).getRecto(),
95, 160);
jbutton.setIcon(new ImageIcon(imageCarte));
jbutton.setToolTipText(joueurCourant.getGrimoire().get(i)
.getInfoBulle());
panelGrimoire.add(jbutton);
groupeBoutonsCartesGrimoire.add(jbutton);
tableCorrespondance
.put(jbutton, joueurCourant.getGrimoire().get(i));
jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if ((JToggleButton) arg0.getSource() != null)
carteSelectionneeGrimoire = tableCorrespondance
.get((JToggleButton) arg0.getSource());
if (carteSelectionneeMain != null)
btnEchanger.setEnabled(true);
}
});
}
for (int i = 0; i < joueurCourant.getMain().size(); i++) { // Affichage
// main
JToggleButton jbutton = new JToggleButton("");
imageCarte = resize(joueurCourant.getMain().get(i).getRecto(), 95,
160);
jbutton.setIcon(new ImageIcon(imageCarte));
jbutton.setToolTipText(joueurCourant.getMain().get(i)
.getInfoBulle());
panelMain.add(jbutton);
groupeBoutonsCartesMain.add(jbutton);
tableCorrespondance.put(jbutton, joueurCourant.getMain().get(i));
jbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if ((JToggleButton) arg0.getSource() != null)
carteSelectionneeMain = tableCorrespondance
.get((JToggleButton) arg0.getSource());
if (carteSelectionneeGrimoire != null)
btnEchanger.setEnabled(true);
}
});
}
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static BufferedImage resize(String nomImageCarte, int width,
int height) {
BufferedImage img = null;
ImprovedMultistepRescaleOp resampleOp = new ImprovedMultistepRescaleOp(
width, height);
try {
img = ImageIO.read(new File("./src/images/"
+ nomImageCarte.replace("hocusPocus.Cartes.", "")));
} catch (IOException e) {
e.printStackTrace();
}
return resampleOp.filter(img, null);
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/IHM/EchangerMainGrimoire.java | Java | mit | 6,465 |
package hocusPocus.IHM;
import hocusPocus.Partie.Jeu;
import java.util.HashMap;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.swing.SwingConstants;
public class InformationJoueur extends JFrame implements Observer{
private static HashMap<String, Integer> infosJoueurs = new HashMap<String, Integer>();
private EcranAccueil interfaceGraphique = EcranAccueil.getInstance();
public InformationJoueur() {
}
/**
* Permet de recuperer le nom et l'age des joueurs
*/
public InformationJoueur(int getNbJoueurs){
int retour = -1;
infosJoueurs.clear(); // On vide la liste
for(int i = 0;i < getNbJoueurs; i++){
JTextField nom = new JTextField("Joueur" + (i + 1));
JComboBox age = new JComboBox(); // Pas besoin de <Integer> si JDK < 7
for(int j = 5; j <= 100; j++)
age.addItem(j);
retour = JOptionPane.showOptionDialog(null,
new Object[] {"Votre prenom :", nom, "Votre age :", age},"Hocus Pocus",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.QUESTION_MESSAGE, null,null,null);
if (retour == JOptionPane.CLOSED_OPTION)
return;
infosJoueurs.put(nom.getText(),age.getSelectedIndex()+5);
}
if (retour == JOptionPane.OK_OPTION)
Jeu.getInstance().initPlateau(infosJoueurs); // Lancement du plateau
System.out.println("Infos joueur : " + infosJoueurs.toString());
}
public static HashMap<String, Integer> getInfosJoueurs() {
return infosJoueurs;
}
@Override
public void update(Observable arg0, Object arg1) {
// TODO Auto-generated method stub
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/IHM/InformationJoueur.java | Java | mit | 1,881 |
package hocusPocus.Partie;
import java.util.ArrayList;
import java.util.Stack;
public class Chaudron {
private static Stack<Gemme> gemmes = new Stack<Gemme>();
Chaudron(int nbGemmes) {
for(int i = 0; i < nbGemmes; i++)
gemmes.push(new Gemme());
}
/**
* Retourne le nombre de gemmes
* @return
*/
public int recupererNbGemmes() {
if(gemmes.empty()) return 0;
return gemmes.size();
}
/**
* Ajoute un gemme dans le chaudron
* @param nbGemmes
*/
public void deposerGemmes(Gemme g) {
gemmes.push(g);
}
/**
* Surcharge: ajoute un nombre de gemmes defini dans le chaudron
* @param nbGemmes
*/
public static void deposerGemmes(ArrayList<Gemme> listeGemmes) {
for(Gemme gemme : listeGemmes)
gemmes.push(gemme);
}
/**
* Retourner le nombre de gemmes specifie
* @param nbGemmes
* @return un gemme ou une liste de gemmes
*/
public ArrayList<Gemme> piocherGemmes(int nbGemmes) {
ArrayList<Gemme> gemmesDemandes = new ArrayList<Gemme>();
if(nbGemmes == 1 && !gemmes.empty())
gemmesDemandes.add(gemmes.pop());
else{
for(int i = 0; i < nbGemmes; i++) {
if(!gemmes.isEmpty())
gemmesDemandes.add(gemmes.pop());
}
}
return gemmesDemandes;
}
public Gemme piocherUnGemme() {
return gemmes.pop();
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Partie/Chaudron.java | Java | mit | 1,341 |
package hocusPocus.Partie;
public class Main {
public static void main(String[] args) {
Jeu jeu = Jeu.getInstance();
jeu.initPartie();
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Partie/Main.java | Java | mit | 158 |
package hocusPocus.Partie;
import hocusPocus.IHM.GagnantPartie;
import java.util.ArrayList;
public class ThreadGagnant extends Thread{
private Plateau plateau;
private ArrayList<Joueur> listeJoueurs;
private Joueur joueurGagnant;
public ThreadGagnant(){
this.plateau = Plateau.getInstance();
this.listeJoueurs = plateau.getListeJoueurs();
this.joueurGagnant = listeJoueurs.get(0);
}
public void run() {
while(true) {
if(plateau.getChaudron().recupererNbGemmes() == 0){
for(int i = 1; i < listeJoueurs.size(); i++) {
if(joueurGagnant.getNbGemmes() < listeJoueurs.get(i).getNbGemmes()){
joueurGagnant = listeJoueurs.get(i);
}
}
break;
}
}
new GagnantPartie(joueurGagnant.getNom());
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Partie/ThreadGagnant.java | Java | mit | 784 |
package hocusPocus.Partie;
import hocusPocus.Cartes.Carte;
import hocusPocus.IHM.DesignerJoueur;
import hocusPocus.IHM.InteractionJoueur;
import java.util.ArrayList;
public class AnalyseZoneDeJeu {
private Plateau plateau;
private ArrayList<Carte> zoneDeJeu;
public AnalyseZoneDeJeu() {
this.plateau = Plateau.getInstance();
this.zoneDeJeu = this.plateau.getZoneDeJeu();
}
public void Analyse() {
String nomCarte = this.zoneDeJeu.get(0).getClass().getSimpleName();
if((this.zoneDeJeu.size() == 1) && (nomCarte.equals("HAbracadabra") || nomCarte.equals("HSacrifice") || nomCarte.equals("HVoleur") || nomCarte.equals("HHibou")))
new DesignerJoueur(); // Designer une cible pour la carte Hocus
else {
System.out.println("Pas de cible pour la carte " + this.zoneDeJeu.get((this.zoneDeJeu.size()) - 1).getClass().getSimpleName());
new InteractionJoueur();
}
}
public void Resolution(){
if(zoneDeJeu.size() == 1) {
new ResoudrePouvoirHocus(zoneDeJeu.get(0), plateau.getJoueurCourant()); // On resout la carte
}
if(zoneDeJeu.size() == 2) {
new ResoudrePouvoirPocus(zoneDeJeu.get(1), plateau.getJoueurCourant());
}
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Partie/AnalyseZoneDeJeu.java | Java | mit | 1,197 |
package hocusPocus.Partie;
import hocusPocus.IHM.EcranAccueil;
import hocusPocus.IHM.InterfacePlateau;
import java.awt.Color;
import java.util.ArrayList;
import java.util.HashMap;
public final class Jeu {
private static Plateau plateau;
private EcranAccueil ihm;
private InterfacePlateau interfacePlateau;
public static boolean partieRapide;
public static boolean partieNormale;
private static Jeu _instance = null; // singleton pattern
private ThreadVerificationGrimoire verificationTailleGrimoire;
private ThreadVerificationBibliotheque verificationTailleBibliotheque;
private ThreadGagnant threadGagnant;
private Jeu(){
}
public static Jeu getInstance(){
if(_instance == null)
_instance = new Jeu();
return _instance;
}
/**
* Methode permettant l'initialisation de la partie
* Initialisation de l'interface graphique
* Initialisation du plateau
*/
public void initPartie() {
ihm = EcranAccueil.getInstance();
}
/**
* Initialiser le plateau de jeu
* @param HashMap<String, Integer> informationsJoueurs
*/
public void initPlateau(HashMap<String, Integer> informationsJoueurs) {
plateau = Plateau.getInstance();
plateau.initJoueurs(informationsJoueurs);
plateau.classerJoueurs(); // Le plus jeune joueur doit commencer
plateau.initCartes(); // Instancier les cartes
plateau.getBibliotheque().melangerCartes();
plateau.distribuerCarte();
plateau.initChaudron();
System.out.println("Cartes instanciees et distribuees");
ihm.getContentPane().removeAll();
ihm.getContentPane().setBackground(Color.GRAY);
interfacePlateau = new InterfacePlateau();
ihm.getContentPane().add(interfacePlateau);
ihm.getContentPane().validate();
verificationTailleGrimoire = new ThreadVerificationGrimoire();
verificationTailleGrimoire.start();
verificationTailleBibliotheque = new ThreadVerificationBibliotheque();
verificationTailleBibliotheque.start();
threadGagnant = new ThreadGagnant();
threadGagnant.start();
}
public void resoudrePouvoirCarte() {
}
public static ArrayList<Joueur> getListeJoueurs() {
return plateau.getListeJoueurs();
}
public InterfacePlateau getInterfacePlateau() {
return this.interfacePlateau;
}
public ThreadVerificationGrimoire getVerificationTailleGrimoire() {
return verificationTailleGrimoire;
}
public ThreadVerificationBibliotheque getVerificationTailleBlibliotheque() {
return verificationTailleBibliotheque;
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Partie/Jeu.java | Java | mit | 2,530 |
package hocusPocus.Partie;
import hocusPocus.Cartes.Carte;
import java.util.ArrayList;
import java.util.Stack;
public class Defausse {
Stack<Carte> pile = new Stack<Carte>();
/**
* Empiler les carte sur la pile de defausse
* @param cartesDefaussees
*/
public void defausserCartes(ArrayList<Carte> cartesDefaussees) {
for(Carte carte : cartesDefaussees)
this.pile.push(carte);
}
public void defausserUneCarte(Carte carteDefaussee) {
this.pile.push(carteDefaussee);
}
/**
* Permet de vider la defausse et de retourner l'ensemble des cartes
* qu'elle contient
* @return
*/
public ArrayList<Carte> viderDefausse() {
ArrayList<Carte> cartesDefausse = new ArrayList<Carte>();
for(int i = 0; i < this.pile.size(); i++)
cartesDefausse.add(this.pile.pop());
return cartesDefausse;
}
public Stack<Carte> getPile() {
return pile;
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Partie/Defausse.java | Java | mit | 948 |
package hocusPocus.Partie;
public class Gemme {
String proprietaire;
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Partie/Gemme.java | Java | mit | 78 |
package hocusPocus.Partie;
import java.util.ArrayList;
/**
* Thread permettant de s'assurer qu'il y a toujours,
* dans la mesure du possible, 3 cartes dans le grimoire
* des joueurs
*
*/
public class ThreadVerificationGrimoire extends Thread{
private Plateau plateau;
private ArrayList<Joueur> listeJoueurs;
protected volatile boolean running = true;
public ThreadVerificationGrimoire() {
this.plateau = Plateau.getInstance();
this.listeJoueurs = plateau.getListeJoueurs();
}
public void stopMe() {
this.running = false;
}
public void restartMe() {
this.running = true;
}
public void run() {
while(true) {
while(running) {
for(int i = 0; i < listeJoueurs.size(); i++) {
while(listeJoueurs.get(i).getGrimoire().size() < 3) {
if(listeJoueurs.get(i).getMain().size() > 0 ) {
listeJoueurs.get(i).transfertMainVersGrimoire();
Jeu.getInstance().getInterfacePlateau().rafraichirPanelListeJoueurs();
}
else
break;
}
}
}
}
}
}
| 1215cpegestionprojet | trunk/src/hocusPocus/Partie/ThreadVerificationGrimoire.java | Java | mit | 1,061 |
<?php
/**
* Website: http://sourceforge.net/projects/simplehtmldom/
* Acknowledge: Jose Solorzano (https://sourceforge.net/projects/php-html/)
* Contributions by:
* Yousuke Kumakura (Attribute filters)
* Vadim Voituk (Negative indexes supports of "find" method)
* Antcs (Constructor with automatically load contents either text or file/url)
*
* all affected sections have comments starting with "PaperG"
*
* Paperg - Added case insensitive testing of the value of the selector.
* Paperg - Added tag_start for the starting index of tags - NOTE: This works but not accurately.
* This tag_start gets counted AFTER \r\n have been crushed out, and after the remove_noice calls so it will not reflect the REAL position of the tag in the source,
* it will almost always be smaller by some amount.
* We use this to determine how far into the file the tag in question is. This "percentage will never be accurate as the $dom->size is the "real" number of bytes the dom was created from.
* but for most purposes, it's a really good estimation.
* Paperg - Added the forceTagsClosed to the dom constructor. Forcing tags closed is great for malformed html, but it CAN lead to parsing errors.
* Allow the user to tell us how much they trust the html.
* Paperg add the text and plaintext to the selectors for the find syntax. plaintext implies text in the innertext of a node. text implies that the tag is a text node.
* This allows for us to find tags based on the text they contain.
* Create find_ancestor_tag to see if a tag is - at any level - inside of another specific tag.
* Paperg: added parse_charset so that we know about the character set of the source document.
* NOTE: If the user's system has a routine called get_last_retrieve_url_contents_content_type availalbe, we will assume it's returning the content-type header from the
* last transfer or curl_exec, and we will parse that and use it in preference to any other method of charset detection.
*
* Found infinite loop in the case of broken html in restore_noise. Rewrote to protect from that.
* PaperG (John Schlick) Added get_display_size for "IMG" tags.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @author S.C. Chen <me578022@gmail.com>
* @author John Schlick
* @author Rus Carroll
* @version 1.5 ($Rev: 196 $)
* @package PlaceLocalInclude
* @subpackage simple_html_dom
*/
/**
* All of the Defines for the classes below.
* @author S.C. Chen <me578022@gmail.com>
*/
define('HDOM_TYPE_ELEMENT', 1);
define('HDOM_TYPE_COMMENT', 2);
define('HDOM_TYPE_TEXT', 3);
define('HDOM_TYPE_ENDTAG', 4);
define('HDOM_TYPE_ROOT', 5);
define('HDOM_TYPE_UNKNOWN', 6);
define('HDOM_QUOTE_DOUBLE', 0);
define('HDOM_QUOTE_SINGLE', 1);
define('HDOM_QUOTE_NO', 3);
define('HDOM_INFO_BEGIN', 0);
define('HDOM_INFO_END', 1);
define('HDOM_INFO_QUOTE', 2);
define('HDOM_INFO_SPACE', 3);
define('HDOM_INFO_TEXT', 4);
define('HDOM_INFO_INNER', 5);
define('HDOM_INFO_OUTER', 6);
define('HDOM_INFO_ENDSPACE',7);
define('DEFAULT_TARGET_CHARSET', 'UTF-8');
define('DEFAULT_BR_TEXT', "\r\n");
define('DEFAULT_SPAN_TEXT', " ");
define('MAX_FILE_SIZE', 600000);
// helper functions
// -----------------------------------------------------------------------------
// get html dom from file
// $maxlen is defined in the code as PHP_STREAM_COPY_ALL which is defined as -1.
function file_get_html($url, $use_include_path = false, $context=null, $offset = -1, $maxLen=-1, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
{
// We DO force the tags to be terminated.
$dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $stripRN, $defaultBRText, $defaultSpanText);
// For sourceforge users: uncomment the next line and comment the retreive_url_contents line 2 lines down if it is not already done.
$contents = file_get_contents($url, $use_include_path, $context, $offset);
// Paperg - use our own mechanism for getting the contents as we want to control the timeout.
//$contents = retrieve_url_contents($url);
if (empty($contents) || strlen($contents) > MAX_FILE_SIZE)
{
return false;
}
// The second parameter can force the selectors to all be lowercase.
$dom->load($contents, $lowercase, $stripRN);
return $dom;
}
// get html dom from string
function str_get_html($str, $lowercase=true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
{
$dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $stripRN, $defaultBRText, $defaultSpanText);
if (empty($str) || strlen($str) > MAX_FILE_SIZE)
{
$dom->clear();
return false;
}
$dom->load($str, $lowercase, $stripRN);
return $dom;
}
// dump html dom tree
function dump_html_tree($node, $show_attr=true, $deep=0)
{
$node->dump($node);
}
/**
* simple html dom node
* PaperG - added ability for "find" routine to lowercase the value of the selector.
* PaperG - added $tag_start to track the start position of the tag in the total byte index
*
* @package PlaceLocalInclude
*/
class simple_html_dom_node
{
public $nodetype = HDOM_TYPE_TEXT;
public $tag = 'text';
public $attr = array();
public $children = array();
public $nodes = array();
public $parent = null;
// The "info" array - see HDOM_INFO_... for what each element contains.
public $_ = array();
public $tag_start = 0;
private $dom = null;
function __construct($dom)
{
$this->dom = $dom;
$dom->nodes[] = $this;
}
function __destruct()
{
$this->clear();
}
function __toString()
{
return $this->outertext();
}
// clean up memory due to php5 circular references memory leak...
function clear()
{
$this->dom = null;
$this->nodes = null;
$this->parent = null;
$this->children = null;
}
// dump node's tree
function dump($show_attr=true, $deep=0)
{
$lead = str_repeat(' ', $deep);
echo $lead.$this->tag;
if ($show_attr && count($this->attr)>0)
{
echo '(';
foreach ($this->attr as $k=>$v)
echo "[$k]=>\"".$this->$k.'", ';
echo ')';
}
echo "\n";
if ($this->nodes)
{
foreach ($this->nodes as $c)
{
$c->dump($show_attr, $deep+1);
}
}
}
// Debugging function to dump a single dom node with a bunch of information about it.
function dump_node($echo=true)
{
$string = $this->tag;
if (count($this->attr)>0)
{
$string .= '(';
foreach ($this->attr as $k=>$v)
{
$string .= "[$k]=>\"".$this->$k.'", ';
}
$string .= ')';
}
if (count($this->_)>0)
{
$string .= ' $_ (';
foreach ($this->_ as $k=>$v)
{
if (is_array($v))
{
$string .= "[$k]=>(";
foreach ($v as $k2=>$v2)
{
$string .= "[$k2]=>\"".$v2.'", ';
}
$string .= ")";
} else {
$string .= "[$k]=>\"".$v.'", ';
}
}
$string .= ")";
}
if (isset($this->text))
{
$string .= " text: (" . $this->text . ")";
}
$string .= " HDOM_INNER_INFO: '";
if (isset($node->_[HDOM_INFO_INNER]))
{
$string .= $node->_[HDOM_INFO_INNER] . "'";
}
else
{
$string .= ' NULL ';
}
$string .= " children: " . count($this->children);
$string .= " nodes: " . count($this->nodes);
$string .= " tag_start: " . $this->tag_start;
$string .= "\n";
if ($echo)
{
echo $string;
return;
}
else
{
return $string;
}
}
// returns the parent of node
// If a node is passed in, it will reset the parent of the current node to that one.
function parent($parent=null)
{
// I am SURE that this doesn't work properly.
// It fails to unset the current node from it's current parents nodes or children list first.
if ($parent !== null)
{
$this->parent = $parent;
$this->parent->nodes[] = $this;
$this->parent->children[] = $this;
}
return $this->parent;
}
// verify that node has children
function has_child()
{
return !empty($this->children);
}
// returns children of node
function children($idx=-1)
{
if ($idx===-1)
{
return $this->children;
}
if (isset($this->children[$idx])) return $this->children[$idx];
return null;
}
// returns the first child of node
function first_child()
{
if (count($this->children)>0)
{
return $this->children[0];
}
return null;
}
// returns the last child of node
function last_child()
{
if (($count=count($this->children))>0)
{
return $this->children[$count-1];
}
return null;
}
// returns the next sibling of node
function next_sibling()
{
if ($this->parent===null)
{
return null;
}
$idx = 0;
$count = count($this->parent->children);
while ($idx<$count && $this!==$this->parent->children[$idx])
{
++$idx;
}
if (++$idx>=$count)
{
return null;
}
return $this->parent->children[$idx];
}
// returns the previous sibling of node
function prev_sibling()
{
if ($this->parent===null) return null;
$idx = 0;
$count = count($this->parent->children);
while ($idx<$count && $this!==$this->parent->children[$idx])
++$idx;
if (--$idx<0) return null;
return $this->parent->children[$idx];
}
// function to locate a specific ancestor tag in the path to the root.
function find_ancestor_tag($tag)
{
global $debugObject;
if (is_object($debugObject)) { $debugObject->debugLogEntry(1); }
// Start by including ourselves in the comparison.
$returnDom = $this;
while (!is_null($returnDom))
{
if (is_object($debugObject)) { $debugObject->debugLog(2, "Current tag is: " . $returnDom->tag); }
if ($returnDom->tag == $tag)
{
break;
}
$returnDom = $returnDom->parent;
}
return $returnDom;
}
// get dom node's inner html
function innertext()
{
if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
$ret = '';
foreach ($this->nodes as $n)
$ret .= $n->outertext();
return $ret;
}
// get dom node's outer text (with tag)
function outertext()
{
global $debugObject;
if (is_object($debugObject))
{
$text = '';
if ($this->tag == 'text')
{
if (!empty($this->text))
{
$text = " with text: " . $this->text;
}
}
$debugObject->debugLog(1, 'Innertext of tag: ' . $this->tag . $text);
}
if ($this->tag==='root') return $this->innertext();
// trigger callback
if ($this->dom && $this->dom->callback!==null)
{
call_user_func_array($this->dom->callback, array($this));
}
if (isset($this->_[HDOM_INFO_OUTER])) return $this->_[HDOM_INFO_OUTER];
if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
// render begin tag
if ($this->dom && $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]])
{
$ret = $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]->makeup();
} else {
$ret = "";
}
// render inner text
if (isset($this->_[HDOM_INFO_INNER]))
{
// If it's a br tag... don't return the HDOM_INNER_INFO that we may or may not have added.
if ($this->tag != "br")
{
$ret .= $this->_[HDOM_INFO_INNER];
}
} else {
if ($this->nodes)
{
foreach ($this->nodes as $n)
{
$ret .= $this->convert_text($n->outertext());
}
}
}
// render end tag
if (isset($this->_[HDOM_INFO_END]) && $this->_[HDOM_INFO_END]!=0)
$ret .= '</'.$this->tag.'>';
return $ret;
}
// get dom node's plain text
function text()
{
if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
switch ($this->nodetype)
{
case HDOM_TYPE_TEXT: return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
case HDOM_TYPE_COMMENT: return '';
case HDOM_TYPE_UNKNOWN: return '';
}
if (strcasecmp($this->tag, 'script')===0) return '';
if (strcasecmp($this->tag, 'style')===0) return '';
$ret = '';
// In rare cases, (always node type 1 or HDOM_TYPE_ELEMENT - observed for some span tags, and some p tags) $this->nodes is set to NULL.
// NOTE: This indicates that there is a problem where it's set to NULL without a clear happening.
// WHY is this happening?
if (!is_null($this->nodes))
{
foreach ($this->nodes as $n)
{
$ret .= $this->convert_text($n->text());
}
// If this node is a span... add a space at the end of it so multiple spans don't run into each other. This is plaintext after all.
if ($this->tag == "span")
{
$ret .= $this->dom->default_span_text;
}
}
return $ret;
}
function xmltext()
{
$ret = $this->innertext();
$ret = str_ireplace('<![CDATA[', '', $ret);
$ret = str_replace(']]>', '', $ret);
return $ret;
}
// build node's text with tag
function makeup()
{
// text, comment, unknown
if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
$ret = '<'.$this->tag;
$i = -1;
foreach ($this->attr as $key=>$val)
{
++$i;
// skip removed attribute
if ($val===null || $val===false)
continue;
$ret .= $this->_[HDOM_INFO_SPACE][$i][0];
//no value attr: nowrap, checked selected...
if ($val===true)
$ret .= $key;
else {
switch ($this->_[HDOM_INFO_QUOTE][$i])
{
case HDOM_QUOTE_DOUBLE: $quote = '"'; break;
case HDOM_QUOTE_SINGLE: $quote = '\''; break;
default: $quote = '';
}
$ret .= $key.$this->_[HDOM_INFO_SPACE][$i][1].'='.$this->_[HDOM_INFO_SPACE][$i][2].$quote.$val.$quote;
}
}
$ret = $this->dom->restore_noise($ret);
return $ret . $this->_[HDOM_INFO_ENDSPACE] . '>';
}
// find elements by css selector
//PaperG - added ability for find to lowercase the value of the selector.
function find($selector, $idx=null, $lowercase=false)
{
$selectors = $this->parse_selector($selector);
if (($count=count($selectors))===0) return array();
$found_keys = array();
// find each selector
for ($c=0; $c<$count; ++$c)
{
// The change on the below line was documented on the sourceforge code tracker id 2788009
// used to be: if (($levle=count($selectors[0]))===0) return array();
if (($levle=count($selectors[$c]))===0) return array();
if (!isset($this->_[HDOM_INFO_BEGIN])) return array();
$head = array($this->_[HDOM_INFO_BEGIN]=>1);
// handle descendant selectors, no recursive!
for ($l=0; $l<$levle; ++$l)
{
$ret = array();
foreach ($head as $k=>$v)
{
$n = ($k===-1) ? $this->dom->root : $this->dom->nodes[$k];
//PaperG - Pass this optional parameter on to the seek function.
$n->seek($selectors[$c][$l], $ret, $lowercase);
}
$head = $ret;
}
foreach ($head as $k=>$v)
{
if (!isset($found_keys[$k]))
$found_keys[$k] = 1;
}
}
// sort keys
ksort($found_keys);
$found = array();
foreach ($found_keys as $k=>$v)
$found[] = $this->dom->nodes[$k];
// return nth-element or array
if (is_null($idx)) return $found;
else if ($idx<0) $idx = count($found) + $idx;
return (isset($found[$idx])) ? $found[$idx] : null;
}
// seek for given conditions
// PaperG - added parameter to allow for case insensitive testing of the value of a selector.
protected function seek($selector, &$ret, $lowercase=false)
{
global $debugObject;
if (is_object($debugObject)) { $debugObject->debugLogEntry(1); }
list($tag, $key, $val, $exp, $no_key) = $selector;
// xpath index
if ($tag && $key && is_numeric($key))
{
$count = 0;
foreach ($this->children as $c)
{
if ($tag==='*' || $tag===$c->tag) {
if (++$count==$key) {
$ret[$c->_[HDOM_INFO_BEGIN]] = 1;
return;
}
}
}
return;
}
$end = (!empty($this->_[HDOM_INFO_END])) ? $this->_[HDOM_INFO_END] : 0;
if ($end==0) {
$parent = $this->parent;
while (!isset($parent->_[HDOM_INFO_END]) && $parent!==null) {
$end -= 1;
$parent = $parent->parent;
}
$end += $parent->_[HDOM_INFO_END];
}
for ($i=$this->_[HDOM_INFO_BEGIN]+1; $i<$end; ++$i) {
$node = $this->dom->nodes[$i];
$pass = true;
if ($tag==='*' && !$key) {
if (in_array($node, $this->children, true))
$ret[$i] = 1;
continue;
}
// compare tag
if ($tag && $tag!=$node->tag && $tag!=='*') {$pass=false;}
// compare key
if ($pass && $key) {
if ($no_key) {
if (isset($node->attr[$key])) $pass=false;
} else {
if (($key != "plaintext") && !isset($node->attr[$key])) $pass=false;
}
}
// compare value
if ($pass && $key && $val && $val!=='*') {
// If they have told us that this is a "plaintext" search then we want the plaintext of the node - right?
if ($key == "plaintext") {
// $node->plaintext actually returns $node->text();
$nodeKeyValue = $node->text();
} else {
// this is a normal search, we want the value of that attribute of the tag.
$nodeKeyValue = $node->attr[$key];
}
if (is_object($debugObject)) {$debugObject->debugLog(2, "testing node: " . $node->tag . " for attribute: " . $key . $exp . $val . " where nodes value is: " . $nodeKeyValue);}
//PaperG - If lowercase is set, do a case insensitive test of the value of the selector.
if ($lowercase) {
$check = $this->match($exp, strtolower($val), strtolower($nodeKeyValue));
} else {
$check = $this->match($exp, $val, $nodeKeyValue);
}
if (is_object($debugObject)) {$debugObject->debugLog(2, "after match: " . ($check ? "true" : "false"));}
// handle multiple class
if (!$check && strcasecmp($key, 'class')===0) {
foreach (explode(' ',$node->attr[$key]) as $k) {
// Without this, there were cases where leading, trailing, or double spaces lead to our comparing blanks - bad form.
if (!empty($k)) {
if ($lowercase) {
$check = $this->match($exp, strtolower($val), strtolower($k));
} else {
$check = $this->match($exp, $val, $k);
}
if ($check) break;
}
}
}
if (!$check) $pass = false;
}
if ($pass) $ret[$i] = 1;
unset($node);
}
// It's passed by reference so this is actually what this function returns.
if (is_object($debugObject)) {$debugObject->debugLog(1, "EXIT - ret: ", $ret);}
}
protected function match($exp, $pattern, $value) {
global $debugObject;
if (is_object($debugObject)) {$debugObject->debugLogEntry(1);}
switch ($exp) {
case '=':
return ($value===$pattern);
case '!=':
return ($value!==$pattern);
case '^=':
return preg_match("/^".preg_quote($pattern,'/')."/", $value);
case '$=':
return preg_match("/".preg_quote($pattern,'/')."$/", $value);
case '*=':
if ($pattern[0]=='/') {
return preg_match($pattern, $value);
}
return preg_match("/".$pattern."/i", $value);
}
return false;
}
protected function parse_selector($selector_string) {
global $debugObject;
if (is_object($debugObject)) {$debugObject->debugLogEntry(1);}
// pattern of CSS selectors, modified from mootools
// Paperg: Add the colon to the attrbute, so that it properly finds <tag attr:ibute="something" > like google does.
// Note: if you try to look at this attribute, yo MUST use getAttribute since $dom->x:y will fail the php syntax check.
// Notice the \[ starting the attbute? and the @? following? This implies that an attribute can begin with an @ sign that is not captured.
// This implies that an html attribute specifier may start with an @ sign that is NOT captured by the expression.
// farther study is required to determine of this should be documented or removed.
// $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is";
$pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-:]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is";
preg_match_all($pattern, trim($selector_string).' ', $matches, PREG_SET_ORDER);
if (is_object($debugObject)) {$debugObject->debugLog(2, "Matches Array: ", $matches);}
$selectors = array();
$result = array();
//print_r($matches);
foreach ($matches as $m) {
$m[0] = trim($m[0]);
if ($m[0]==='' || $m[0]==='/' || $m[0]==='//') continue;
// for browser generated xpath
if ($m[1]==='tbody') continue;
list($tag, $key, $val, $exp, $no_key) = array($m[1], null, null, '=', false);
if (!empty($m[2])) {$key='id'; $val=$m[2];}
if (!empty($m[3])) {$key='class'; $val=$m[3];}
if (!empty($m[4])) {$key=$m[4];}
if (!empty($m[5])) {$exp=$m[5];}
if (!empty($m[6])) {$val=$m[6];}
// convert to lowercase
if ($this->dom->lowercase) {$tag=strtolower($tag); $key=strtolower($key);}
//elements that do NOT have the specified attribute
if (isset($key[0]) && $key[0]==='!') {$key=substr($key, 1); $no_key=true;}
$result[] = array($tag, $key, $val, $exp, $no_key);
if (trim($m[7])===',') {
$selectors[] = $result;
$result = array();
}
}
if (count($result)>0)
$selectors[] = $result;
return $selectors;
}
function __get($name) {
if (isset($this->attr[$name]))
{
return $this->convert_text($this->attr[$name]);
}
switch ($name) {
case 'outertext': return $this->outertext();
case 'innertext': return $this->innertext();
case 'plaintext': return $this->text();
case 'xmltext': return $this->xmltext();
default: return array_key_exists($name, $this->attr);
}
}
function __set($name, $value) {
switch ($name) {
case 'outertext': return $this->_[HDOM_INFO_OUTER] = $value;
case 'innertext':
if (isset($this->_[HDOM_INFO_TEXT])) return $this->_[HDOM_INFO_TEXT] = $value;
return $this->_[HDOM_INFO_INNER] = $value;
}
if (!isset($this->attr[$name])) {
$this->_[HDOM_INFO_SPACE][] = array(' ', '', '');
$this->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;
}
$this->attr[$name] = $value;
}
function __isset($name) {
switch ($name) {
case 'outertext': return true;
case 'innertext': return true;
case 'plaintext': return true;
}
//no value attr: nowrap, checked selected...
return (array_key_exists($name, $this->attr)) ? true : isset($this->attr[$name]);
}
function __unset($name) {
if (isset($this->attr[$name]))
unset($this->attr[$name]);
}
// PaperG - Function to convert the text from one character set to another if the two sets are not the same.
function convert_text($text)
{
global $debugObject;
if (is_object($debugObject)) {$debugObject->debugLogEntry(1);}
$converted_text = $text;
$sourceCharset = "";
$targetCharset = "";
if ($this->dom)
{
$sourceCharset = strtoupper($this->dom->_charset);
$targetCharset = strtoupper($this->dom->_target_charset);
}
if (is_object($debugObject)) {$debugObject->debugLog(3, "source charset: " . $sourceCharset . " target charaset: " . $targetCharset);}
if (!empty($sourceCharset) && !empty($targetCharset) && (strcasecmp($sourceCharset, $targetCharset) != 0))
{
// Check if the reported encoding could have been incorrect and the text is actually already UTF-8
if ((strcasecmp($targetCharset, 'UTF-8') == 0) && ($this->is_utf8($text)))
{
$converted_text = $text;
}
else
{
$converted_text = iconv($sourceCharset, $targetCharset, $text);
}
}
// Lets make sure that we don't have that silly BOM issue with any of the utf-8 text we output.
if ($targetCharset == 'UTF-8')
{
if (substr($converted_text, 0, 3) == "\xef\xbb\xbf")
{
$converted_text = substr($converted_text, 3);
}
if (substr($converted_text, -3) == "\xef\xbb\xbf")
{
$converted_text = substr($converted_text, 0, -3);
}
}
return $converted_text;
}
/**
* Returns true if $string is valid UTF-8 and false otherwise.
*
* @param mixed $str String to be tested
* @return boolean
*/
static function is_utf8($str)
{
$c=0; $b=0;
$bits=0;
$len=strlen($str);
for($i=0; $i<$len; $i++)
{
$c=ord($str[$i]);
if($c > 128)
{
if(($c >= 254)) return false;
elseif($c >= 252) $bits=6;
elseif($c >= 248) $bits=5;
elseif($c >= 240) $bits=4;
elseif($c >= 224) $bits=3;
elseif($c >= 192) $bits=2;
else return false;
if(($i+$bits) > $len) return false;
while($bits > 1)
{
$i++;
$b=ord($str[$i]);
if($b < 128 || $b > 191) return false;
$bits--;
}
}
}
return true;
}
/*
function is_utf8($string)
{
//this is buggy
return (utf8_encode(utf8_decode($string)) == $string);
}
*/
/**
* Function to try a few tricks to determine the displayed size of an img on the page.
* NOTE: This will ONLY work on an IMG tag. Returns FALSE on all other tag types.
*
* @author John Schlick
* @version April 19 2012
* @return array an array containing the 'height' and 'width' of the image on the page or -1 if we can't figure it out.
*/
function get_display_size()
{
global $debugObject;
$width = -1;
$height = -1;
if ($this->tag !== 'img')
{
return false;
}
// See if there is aheight or width attribute in the tag itself.
if (isset($this->attr['width']))
{
$width = $this->attr['width'];
}
if (isset($this->attr['height']))
{
$height = $this->attr['height'];
}
// Now look for an inline style.
if (isset($this->attr['style']))
{
// Thanks to user gnarf from stackoverflow for this regular expression.
$attributes = array();
preg_match_all("/([\w-]+)\s*:\s*([^;]+)\s*;?/", $this->attr['style'], $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
$attributes[$match[1]] = $match[2];
}
// If there is a width in the style attributes:
if (isset($attributes['width']) && $width == -1)
{
// check that the last two characters are px (pixels)
if (strtolower(substr($attributes['width'], -2)) == 'px')
{
$proposed_width = substr($attributes['width'], 0, -2);
// Now make sure that it's an integer and not something stupid.
if (filter_var($proposed_width, FILTER_VALIDATE_INT))
{
$width = $proposed_width;
}
}
}
// If there is a width in the style attributes:
if (isset($attributes['height']) && $height == -1)
{
// check that the last two characters are px (pixels)
if (strtolower(substr($attributes['height'], -2)) == 'px')
{
$proposed_height = substr($attributes['height'], 0, -2);
// Now make sure that it's an integer and not something stupid.
if (filter_var($proposed_height, FILTER_VALIDATE_INT))
{
$height = $proposed_height;
}
}
}
}
// Future enhancement:
// Look in the tag to see if there is a class or id specified that has a height or width attribute to it.
// Far future enhancement
// Look at all the parent tags of this image to see if they specify a class or id that has an img selector that specifies a height or width
// Note that in this case, the class or id will have the img subselector for it to apply to the image.
// ridiculously far future development
// If the class or id is specified in a SEPARATE css file thats not on the page, go get it and do what we were just doing for the ones on the page.
$result = array('height' => $height,
'width' => $width);
return $result;
}
// camel naming conventions
function getAllAttributes() {return $this->attr;}
function getAttribute($name) {return $this->__get($name);}
function setAttribute($name, $value) {$this->__set($name, $value);}
function hasAttribute($name) {return $this->__isset($name);}
function removeAttribute($name) {$this->__set($name, null);}
function getElementById($id) {return $this->find("#$id", 0);}
function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);}
function getElementByTagName($name) {return $this->find($name, 0);}
function getElementsByTagName($name, $idx=null) {return $this->find($name, $idx);}
function parentNode() {return $this->parent();}
function childNodes($idx=-1) {return $this->children($idx);}
function firstChild() {return $this->first_child();}
function lastChild() {return $this->last_child();}
function nextSibling() {return $this->next_sibling();}
function previousSibling() {return $this->prev_sibling();}
function hasChildNodes() {return $this->has_child();}
function nodeName() {return $this->tag;}
function appendChild($node) {$node->parent($this); return $node;}
}
/**
* simple html dom parser
* Paperg - in the find routine: allow us to specify that we want case insensitive testing of the value of the selector.
* Paperg - change $size from protected to public so we can easily access it
* Paperg - added ForceTagsClosed in the constructor which tells us whether we trust the html or not. Default is to NOT trust it.
*
* @package PlaceLocalInclude
*/
class simple_html_dom
{
public $root = null;
public $nodes = array();
public $callback = null;
public $lowercase = false;
// Used to keep track of how large the text was when we started.
public $original_size;
public $size;
protected $pos;
protected $doc;
protected $char;
protected $cursor;
protected $parent;
protected $noise = array();
protected $token_blank = " \t\r\n";
protected $token_equal = ' =/>';
protected $token_slash = " />\r\n\t";
protected $token_attr = ' >';
// Note that this is referenced by a child node, and so it needs to be public for that node to see this information.
public $_charset = '';
public $_target_charset = '';
protected $default_br_text = "";
public $default_span_text = "";
// use isset instead of in_array, performance boost about 30%...
protected $self_closing_tags = array('img'=>1, 'br'=>1, 'input'=>1, 'meta'=>1, 'link'=>1, 'hr'=>1, 'base'=>1, 'embed'=>1, 'spacer'=>1);
protected $block_tags = array('root'=>1, 'body'=>1, 'form'=>1, 'div'=>1, 'span'=>1, 'table'=>1);
// Known sourceforge issue #2977341
// B tags that are not closed cause us to return everything to the end of the document.
protected $optional_closing_tags = array(
'tr'=>array('tr'=>1, 'td'=>1, 'th'=>1),
'th'=>array('th'=>1),
'td'=>array('td'=>1),
'li'=>array('li'=>1),
'dt'=>array('dt'=>1, 'dd'=>1),
'dd'=>array('dd'=>1, 'dt'=>1),
'dl'=>array('dd'=>1, 'dt'=>1),
'p'=>array('p'=>1),
'nobr'=>array('nobr'=>1),
'b'=>array('b'=>1),
'option'=>array('option'=>1),
);
function __construct($str=null, $lowercase=true, $forceTagsClosed=true, $target_charset=DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
{
if ($str)
{
if (preg_match("/^http:\/\//i",$str) || is_file($str))
{
$this->load_file($str);
}
else
{
$this->load($str, $lowercase, $stripRN, $defaultBRText, $defaultSpanText);
}
}
// Forcing tags to be closed implies that we don't trust the html, but it can lead to parsing errors if we SHOULD trust the html.
if (!$forceTagsClosed) {
$this->optional_closing_array=array();
}
$this->_target_charset = $target_charset;
}
function __destruct()
{
$this->clear();
}
// load html from string
function load($str, $lowercase=true, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
{
global $debugObject;
// prepare
$this->prepare($str, $lowercase, $stripRN, $defaultBRText, $defaultSpanText);
// strip out comments
$this->remove_noise("'<!--(.*?)-->'is");
// strip out cdata
$this->remove_noise("'<!\[CDATA\[(.*?)\]\]>'is", true);
// Per sourceforge http://sourceforge.net/tracker/?func=detail&aid=2949097&group_id=218559&atid=1044037
// Script tags removal now preceeds style tag removal.
// strip out <script> tags
$this->remove_noise("'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'is");
$this->remove_noise("'<\s*script\s*>(.*?)<\s*/\s*script\s*>'is");
// strip out <style> tags
$this->remove_noise("'<\s*style[^>]*[^/]>(.*?)<\s*/\s*style\s*>'is");
$this->remove_noise("'<\s*style\s*>(.*?)<\s*/\s*style\s*>'is");
// strip out preformatted tags
$this->remove_noise("'<\s*(?:code)[^>]*>(.*?)<\s*/\s*(?:code)\s*>'is");
// strip out server side scripts
$this->remove_noise("'(<\?)(.*?)(\?>)'s", true);
// strip smarty scripts
$this->remove_noise("'(\{\w)(.*?)(\})'s", true);
// parsing
while ($this->parse());
// end
$this->root->_[HDOM_INFO_END] = $this->cursor;
$this->parse_charset();
// make load function chainable
return $this;
}
// load html from file
function load_file()
{
$args = func_get_args();
$this->load(call_user_func_array('file_get_contents', $args), true);
// Throw an error if we can't properly load the dom.
if (($error=error_get_last())!==null) {
$this->clear();
return false;
}
}
// set callback function
function set_callback($function_name)
{
$this->callback = $function_name;
}
// remove callback function
function remove_callback()
{
$this->callback = null;
}
// save dom as string
function save($filepath='')
{
$ret = $this->root->innertext();
if ($filepath!=='') file_put_contents($filepath, $ret, LOCK_EX);
return $ret;
}
// find dom node by css selector
// Paperg - allow us to specify that we want case insensitive testing of the value of the selector.
function find($selector, $idx=null, $lowercase=false)
{
return $this->root->find($selector, $idx, $lowercase);
}
// clean up memory due to php5 circular references memory leak...
function clear()
{
foreach ($this->nodes as $n) {$n->clear(); $n = null;}
// This add next line is documented in the sourceforge repository. 2977248 as a fix for ongoing memory leaks that occur even with the use of clear.
if (isset($this->children)) foreach ($this->children as $n) {$n->clear(); $n = null;}
if (isset($this->parent)) {$this->parent->clear(); unset($this->parent);}
if (isset($this->root)) {$this->root->clear(); unset($this->root);}
unset($this->doc);
unset($this->noise);
}
function dump($show_attr=true)
{
$this->root->dump($show_attr);
}
// prepare HTML data and init everything
protected function prepare($str, $lowercase=true, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT)
{
$this->clear();
// set the length of content before we do anything to it.
$this->size = strlen($str);
// Save the original size of the html that we got in. It might be useful to someone.
$this->original_size = $this->size;
//before we save the string as the doc... strip out the \r \n's if we are told to.
if ($stripRN) {
$str = str_replace("\r", " ", $str);
$str = str_replace("\n", " ", $str);
// set the length of content since we have changed it.
$this->size = strlen($str);
}
$this->doc = $str;
$this->pos = 0;
$this->cursor = 1;
$this->noise = array();
$this->nodes = array();
$this->lowercase = $lowercase;
$this->default_br_text = $defaultBRText;
$this->default_span_text = $defaultSpanText;
$this->root = new simple_html_dom_node($this);
$this->root->tag = 'root';
$this->root->_[HDOM_INFO_BEGIN] = -1;
$this->root->nodetype = HDOM_TYPE_ROOT;
$this->parent = $this->root;
if ($this->size>0) $this->char = $this->doc[0];
}
// parse html content
protected function parse()
{
if (($s = $this->copy_until_char('<'))==='')
{
return $this->read_tag();
}
// text
$node = new simple_html_dom_node($this);
++$this->cursor;
$node->_[HDOM_INFO_TEXT] = $s;
$this->link_nodes($node, false);
return true;
}
// PAPERG - dkchou - added this to try to identify the character set of the page we have just parsed so we know better how to spit it out later.
// NOTE: IF you provide a routine called get_last_retrieve_url_contents_content_type which returns the CURLINFO_CONTENT_TYPE from the last curl_exec
// (or the content_type header from the last transfer), we will parse THAT, and if a charset is specified, we will use it over any other mechanism.
protected function parse_charset()
{
global $debugObject;
$charset = null;
if (function_exists('get_last_retrieve_url_contents_content_type'))
{
$contentTypeHeader = get_last_retrieve_url_contents_content_type();
$success = preg_match('/charset=(.+)/', $contentTypeHeader, $matches);
if ($success)
{
$charset = $matches[1];
if (is_object($debugObject)) {$debugObject->debugLog(2, 'header content-type found charset of: ' . $charset);}
}
}
if (empty($charset))
{
$el = $this->root->find('meta[http-equiv=Content-Type]',0);
if (!empty($el))
{
$fullvalue = $el->content;
if (is_object($debugObject)) {$debugObject->debugLog(2, 'meta content-type tag found' . $fullvalue);}
if (!empty($fullvalue))
{
$success = preg_match('/charset=(.+)/', $fullvalue, $matches);
if ($success)
{
$charset = $matches[1];
}
else
{
// If there is a meta tag, and they don't specify the character set, research says that it's typically ISO-8859-1
if (is_object($debugObject)) {$debugObject->debugLog(2, 'meta content-type tag couldn\'t be parsed. using iso-8859 default.');}
$charset = 'ISO-8859-1';
}
}
}
}
// If we couldn't find a charset above, then lets try to detect one based on the text we got...
if (empty($charset))
{
// Have php try to detect the encoding from the text given to us.
$charset = mb_detect_encoding($this->root->plaintext . "ascii", $encoding_list = array( "UTF-8", "CP1252" ) );
if (is_object($debugObject)) {$debugObject->debugLog(2, 'mb_detect found: ' . $charset);}
// and if this doesn't work... then we need to just wrongheadedly assume it's UTF-8 so that we can move on - cause this will usually give us most of what we need...
if ($charset === false)
{
if (is_object($debugObject)) {$debugObject->debugLog(2, 'since mb_detect failed - using default of utf-8');}
$charset = 'UTF-8';
}
}
// Since CP1252 is a superset, if we get one of it's subsets, we want it instead.
if ((strtolower($charset) == strtolower('ISO-8859-1')) || (strtolower($charset) == strtolower('Latin1')) || (strtolower($charset) == strtolower('Latin-1')))
{
if (is_object($debugObject)) {$debugObject->debugLog(2, 'replacing ' . $charset . ' with CP1252 as its a superset');}
$charset = 'CP1252';
}
if (is_object($debugObject)) {$debugObject->debugLog(1, 'EXIT - ' . $charset);}
return $this->_charset = $charset;
}
// read tag info
protected function read_tag()
{
if ($this->char!=='<')
{
$this->root->_[HDOM_INFO_END] = $this->cursor;
return false;
}
$begin_tag_pos = $this->pos;
$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
// end tag
if ($this->char==='/')
{
$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
// This represents the change in the simple_html_dom trunk from revision 180 to 181.
// $this->skip($this->token_blank_t);
$this->skip($this->token_blank);
$tag = $this->copy_until_char('>');
// skip attributes in end tag
if (($pos = strpos($tag, ' '))!==false)
$tag = substr($tag, 0, $pos);
$parent_lower = strtolower($this->parent->tag);
$tag_lower = strtolower($tag);
if ($parent_lower!==$tag_lower)
{
if (isset($this->optional_closing_tags[$parent_lower]) && isset($this->block_tags[$tag_lower]))
{
$this->parent->_[HDOM_INFO_END] = 0;
$org_parent = $this->parent;
while (($this->parent->parent) && strtolower($this->parent->tag)!==$tag_lower)
$this->parent = $this->parent->parent;
if (strtolower($this->parent->tag)!==$tag_lower) {
$this->parent = $org_parent; // restore origonal parent
if ($this->parent->parent) $this->parent = $this->parent->parent;
$this->parent->_[HDOM_INFO_END] = $this->cursor;
return $this->as_text_node($tag);
}
}
else if (($this->parent->parent) && isset($this->block_tags[$tag_lower]))
{
$this->parent->_[HDOM_INFO_END] = 0;
$org_parent = $this->parent;
while (($this->parent->parent) && strtolower($this->parent->tag)!==$tag_lower)
$this->parent = $this->parent->parent;
if (strtolower($this->parent->tag)!==$tag_lower)
{
$this->parent = $org_parent; // restore origonal parent
$this->parent->_[HDOM_INFO_END] = $this->cursor;
return $this->as_text_node($tag);
}
}
else if (($this->parent->parent) && strtolower($this->parent->parent->tag)===$tag_lower)
{
$this->parent->_[HDOM_INFO_END] = 0;
$this->parent = $this->parent->parent;
}
else
return $this->as_text_node($tag);
}
$this->parent->_[HDOM_INFO_END] = $this->cursor;
if ($this->parent->parent) $this->parent = $this->parent->parent;
$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
return true;
}
$node = new simple_html_dom_node($this);
$node->_[HDOM_INFO_BEGIN] = $this->cursor;
++$this->cursor;
$tag = $this->copy_until($this->token_slash);
$node->tag_start = $begin_tag_pos;
// doctype, cdata & comments...
if (isset($tag[0]) && $tag[0]==='!') {
$node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until_char('>');
if (isset($tag[2]) && $tag[1]==='-' && $tag[2]==='-') {
$node->nodetype = HDOM_TYPE_COMMENT;
$node->tag = 'comment';
} else {
$node->nodetype = HDOM_TYPE_UNKNOWN;
$node->tag = 'unknown';
}
if ($this->char==='>') $node->_[HDOM_INFO_TEXT].='>';
$this->link_nodes($node, true);
$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
return true;
}
// text
if ($pos=strpos($tag, '<')!==false) {
$tag = '<' . substr($tag, 0, -1);
$node->_[HDOM_INFO_TEXT] = $tag;
$this->link_nodes($node, false);
$this->char = $this->doc[--$this->pos]; // prev
return true;
}
if (!preg_match("/^[\w-:]+$/", $tag)) {
$node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until('<>');
if ($this->char==='<') {
$this->link_nodes($node, false);
return true;
}
if ($this->char==='>') $node->_[HDOM_INFO_TEXT].='>';
$this->link_nodes($node, false);
$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
return true;
}
// begin tag
$node->nodetype = HDOM_TYPE_ELEMENT;
$tag_lower = strtolower($tag);
$node->tag = ($this->lowercase) ? $tag_lower : $tag;
// handle optional closing tags
if (isset($this->optional_closing_tags[$tag_lower]) )
{
while (isset($this->optional_closing_tags[$tag_lower][strtolower($this->parent->tag)]))
{
$this->parent->_[HDOM_INFO_END] = 0;
$this->parent = $this->parent->parent;
}
$node->parent = $this->parent;
}
$guard = 0; // prevent infinity loop
$space = array($this->copy_skip($this->token_blank), '', '');
// attributes
do
{
if ($this->char!==null && $space[0]==='')
{
break;
}
$name = $this->copy_until($this->token_equal);
if ($guard===$this->pos)
{
$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
continue;
}
$guard = $this->pos;
// handle endless '<'
if ($this->pos>=$this->size-1 && $this->char!=='>') {
$node->nodetype = HDOM_TYPE_TEXT;
$node->_[HDOM_INFO_END] = 0;
$node->_[HDOM_INFO_TEXT] = '<'.$tag . $space[0] . $name;
$node->tag = 'text';
$this->link_nodes($node, false);
return true;
}
// handle mismatch '<'
if ($this->doc[$this->pos-1]=='<') {
$node->nodetype = HDOM_TYPE_TEXT;
$node->tag = 'text';
$node->attr = array();
$node->_[HDOM_INFO_END] = 0;
$node->_[HDOM_INFO_TEXT] = substr($this->doc, $begin_tag_pos, $this->pos-$begin_tag_pos-1);
$this->pos -= 2;
$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
$this->link_nodes($node, false);
return true;
}
if ($name!=='/' && $name!=='') {
$space[1] = $this->copy_skip($this->token_blank);
$name = $this->restore_noise($name);
if ($this->lowercase) $name = strtolower($name);
if ($this->char==='=') {
$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
$this->parse_attr($node, $name, $space);
}
else {
//no value attr: nowrap, checked selected...
$node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_NO;
$node->attr[$name] = true;
if ($this->char!='>') $this->char = $this->doc[--$this->pos]; // prev
}
$node->_[HDOM_INFO_SPACE][] = $space;
$space = array($this->copy_skip($this->token_blank), '', '');
}
else
break;
} while ($this->char!=='>' && $this->char!=='/');
$this->link_nodes($node, true);
$node->_[HDOM_INFO_ENDSPACE] = $space[0];
// check self closing
if ($this->copy_until_char_escape('>')==='/')
{
$node->_[HDOM_INFO_ENDSPACE] .= '/';
$node->_[HDOM_INFO_END] = 0;
}
else
{
// reset parent
if (!isset($this->self_closing_tags[strtolower($node->tag)])) $this->parent = $node;
}
$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
// If it's a BR tag, we need to set it's text to the default text.
// This way when we see it in plaintext, we can generate formatting that the user wants.
// since a br tag never has sub nodes, this works well.
if ($node->tag == "br")
{
$node->_[HDOM_INFO_INNER] = $this->default_br_text;
}
return true;
}
// parse attributes
protected function parse_attr($node, $name, &$space)
{
// Per sourceforge: http://sourceforge.net/tracker/?func=detail&aid=3061408&group_id=218559&atid=1044037
// If the attribute is already defined inside a tag, only pay atetntion to the first one as opposed to the last one.
if (isset($node->attr[$name]))
{
return;
}
$space[2] = $this->copy_skip($this->token_blank);
switch ($this->char) {
case '"':
$node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;
$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
$node->attr[$name] = $this->restore_noise($this->copy_until_char_escape('"'));
$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
break;
case '\'':
$node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_SINGLE;
$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
$node->attr[$name] = $this->restore_noise($this->copy_until_char_escape('\''));
$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
break;
default:
$node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_NO;
$node->attr[$name] = $this->restore_noise($this->copy_until($this->token_attr));
}
// PaperG: Attributes should not have \r or \n in them, that counts as html whitespace.
$node->attr[$name] = str_replace("\r", "", $node->attr[$name]);
$node->attr[$name] = str_replace("\n", "", $node->attr[$name]);
// PaperG: If this is a "class" selector, lets get rid of the preceeding and trailing space since some people leave it in the multi class case.
if ($name == "class") {
$node->attr[$name] = trim($node->attr[$name]);
}
}
// link node's parent
protected function link_nodes(&$node, $is_child)
{
$node->parent = $this->parent;
$this->parent->nodes[] = $node;
if ($is_child)
{
$this->parent->children[] = $node;
}
}
// as a text node
protected function as_text_node($tag)
{
$node = new simple_html_dom_node($this);
++$this->cursor;
$node->_[HDOM_INFO_TEXT] = '</' . $tag . '>';
$this->link_nodes($node, false);
$this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
return true;
}
protected function skip($chars)
{
$this->pos += strspn($this->doc, $chars, $this->pos);
$this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
}
protected function copy_skip($chars)
{
$pos = $this->pos;
$len = strspn($this->doc, $chars, $pos);
$this->pos += $len;
$this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
if ($len===0) return '';
return substr($this->doc, $pos, $len);
}
protected function copy_until($chars)
{
$pos = $this->pos;
$len = strcspn($this->doc, $chars, $pos);
$this->pos += $len;
$this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
return substr($this->doc, $pos, $len);
}
protected function copy_until_char($char)
{
if ($this->char===null) return '';
if (($pos = strpos($this->doc, $char, $this->pos))===false) {
$ret = substr($this->doc, $this->pos, $this->size-$this->pos);
$this->char = null;
$this->pos = $this->size;
return $ret;
}
if ($pos===$this->pos) return '';
$pos_old = $this->pos;
$this->char = $this->doc[$pos];
$this->pos = $pos;
return substr($this->doc, $pos_old, $pos-$pos_old);
}
protected function copy_until_char_escape($char)
{
if ($this->char===null) return '';
$start = $this->pos;
while (1)
{
if (($pos = strpos($this->doc, $char, $start))===false)
{
$ret = substr($this->doc, $this->pos, $this->size-$this->pos);
$this->char = null;
$this->pos = $this->size;
return $ret;
}
if ($pos===$this->pos) return '';
if ($this->doc[$pos-1]==='\\') {
$start = $pos+1;
continue;
}
$pos_old = $this->pos;
$this->char = $this->doc[$pos];
$this->pos = $pos;
return substr($this->doc, $pos_old, $pos-$pos_old);
}
}
// remove noise from html content
// save the noise in the $this->noise array.
protected function remove_noise($pattern, $remove_tag=false)
{
global $debugObject;
if (is_object($debugObject)) { $debugObject->debugLogEntry(1); }
$count = preg_match_all($pattern, $this->doc, $matches, PREG_SET_ORDER|PREG_OFFSET_CAPTURE);
for ($i=$count-1; $i>-1; --$i)
{
$key = '___noise___'.sprintf('% 5d', count($this->noise)+1000);
if (is_object($debugObject)) { $debugObject->debugLog(2, 'key is: ' . $key); }
$idx = ($remove_tag) ? 0 : 1;
$this->noise[$key] = $matches[$i][$idx][0];
$this->doc = substr_replace($this->doc, $key, $matches[$i][$idx][1], strlen($matches[$i][$idx][0]));
}
// reset the length of content
$this->size = strlen($this->doc);
if ($this->size>0)
{
$this->char = $this->doc[0];
}
}
// restore noise to html content
function restore_noise($text)
{
global $debugObject;
if (is_object($debugObject)) { $debugObject->debugLogEntry(1); }
while (($pos=strpos($text, '___noise___'))!==false)
{
// Sometimes there is a broken piece of markup, and we don't GET the pos+11 etc... token which indicates a problem outside of us...
if (strlen($text) > $pos+15)
{
$key = '___noise___'.$text[$pos+11].$text[$pos+12].$text[$pos+13].$text[$pos+14].$text[$pos+15];
if (is_object($debugObject)) { $debugObject->debugLog(2, 'located key of: ' . $key); }
if (isset($this->noise[$key]))
{
$text = substr($text, 0, $pos).$this->noise[$key].substr($text, $pos+16);
}
else
{
// do this to prevent an infinite loop.
$text = substr($text, 0, $pos).'UNDEFINED NOISE FOR KEY: '.$key . substr($text, $pos+16);
}
}
else
{
// There is no valid key being given back to us... We must get rid of the ___noise___ or we will have a problem.
$text = substr($text, 0, $pos).'NO NUMERIC NOISE KEY' . substr($text, $pos+11);
}
}
return $text;
}
// Sometimes we NEED one of the noise elements.
function search_noise($text)
{
global $debugObject;
if (is_object($debugObject)) { $debugObject->debugLogEntry(1); }
foreach($this->noise as $noiseElement)
{
if (strpos($noiseElement, $text)!==false)
{
return $noiseElement;
}
}
}
function __toString()
{
return $this->root->innertext();
}
function __get($name)
{
switch ($name)
{
case 'outertext':
return $this->root->innertext();
case 'innertext':
return $this->root->innertext();
case 'plaintext':
return $this->root->text();
case 'charset':
return $this->_charset;
case 'target_charset':
return $this->_target_charset;
}
}
// camel naming conventions
function childNodes($idx=-1) {return $this->root->childNodes($idx);}
function firstChild() {return $this->root->first_child();}
function lastChild() {return $this->root->last_child();}
function createElement($name, $value=null) {return @str_get_html("<$name>$value</$name>")->first_child();}
function createTextNode($value) {return @end(str_get_html($value)->nodes);}
function getElementById($id) {return $this->find("#$id", 0);}
function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);}
function getElementByTagName($name) {return $this->find($name, 0);}
function getElementsByTagName($name, $idx=-1) {return $this->find($name, $idx);}
function loadFile() {$args = func_get_args();$this->load_file($args);}
}
?> | 0321hy | trunk/simple_html_dom.php | PHP | asf20 | 65,037 |
<?php
return array(
'appname'=>'飞飞CMS',
'ppvod_welcome'=>'欢迎使用飞飞CMS 2.7.130201版',
'ppvod_version'=>'2.7.130201',
'ppvod_homeurl'=>'http://www.feifeicms.com',
'ppvod_version_js'=>'http://union.feifeicms.com/feifei/version2.js',
'install_error'=>'已经安装过飞飞影视系统,重新安装请先删除Conf/install.lock 文件!',
'install_success'=>'恭喜您!飞飞影视系统安装完成,1秒后自动进入后台管理!',
'install_db_connect'=>'数据库连接失败!请检查数据库连接参数!',
'install_db_select'=>'数据库建立失败,请手动创建或者填写系统管理员分配的数据库名!',
'login_username_check'=>'管理员帐号必须填写!',
'login_password_check'=>'管理员密码必须填写!',
'login_username_not'=>'用户不存在,请重新输入!',
'login_password_not'=>'用户密码错误,请重新输入!',
'login_out'=>'已经安全关闭管理后台!',
);
?> | 0321hy | trunk/Lib/Lang/zh-cn/common.php | PHP | asf20 | 975 |
<?php
$config = require './Runtime/Conf/config.php';
$array = array(
'USER_AUTH_KEY'=>'ffvod',// 用户认证SESSION标记
'NOT_AUTH_ACTION'=>'index,show,add,top,left,main',// 默认无需认证操作
// 'REQUIRE_AUTH_MODULE'=>'Admin,List,Vod,News,User,Collect,Data,Upload,Link,Ads,Cache,Create,Tpl,Cm,Gb,Tag,Special,Nav,Side,Pic',// 默认需要认证模型
'REQUIRE_AUTH_MODULE'=>'Admin,List,Vod,News,User,Collect,Data,Upload,Link,Ads,Cache,Tpl,Cm,Gb,Tag,Special,Nav,Side,Pic',// 默认需要认证模型
'URL_PATHINFO_DEPR'=>'-',
'APP_GROUP_LIST'=>'Admin,Home,Plus,User',//项目分组
'TMPL_FILE_DEPR'=>'_',//模板文件MODULE_NAME与ACTION_NAME之间的分割符,只对项目分组部署有效
'LANG_SWITCH_ON'=>true,// 多语言包功能
'LANG_AUTO_DETECT'=>false,//是否自动侦测浏览器语言
'URL_CASE_INSENSITIVE'=>true,//URL是否不区分大小写 默认区分大小写
'DB_FIELDTYPE_CHECK'=>true, //是否进行字段类型检查
'DATA_CACHE_SUBDIR'=>true,//哈希子目录动态缓存的方式
'TMPL_ACTION_ERROR' => './Public/jump/jumpurl.html', // 默认错误跳转对应的模板文件
'TMPL_ACTION_SUCCESS' => './Public/jump/jumpurl.html', // 默认成功跳转对应的模板文件
'DATA_PATH_LEVEL'=>2,
'url_model' => '3',
'play_player' =>array (
'baiduhd'=> array('01','百度影音'),
'bdhd'=> array('01','百度影音 '),
'youku'=> array('02','在线高清'),
'youku_new'=> array('02','在线视频'),
'yuku'=> array('02','优酷视频'),
'qvod'=> array('03','快播高清'),
'tudou'=> array('03','土豆视频'),
'qiyi'=> array('04','奇艺高清'),
'pvod'=> array('05','皮皮高清'),
'baofeng'=> array('06','暴风影音'),
'sinahd'=> array('07','新浪视频'),
'sohu'=> array('08','搜狐视频'),
'ku6'=> array('09','酷六视频'),
'qq'=> array('10','腾讯视频'),
'web9'=> array('11','久久影音'),
'gvod'=> array('12','迅播高清'),
'down'=> array('13','影片下载'),
'swf'=> array('14','Swf动画'),
'flv'=> array('15','Flv视频'),
'pptv'=> array('16','PPTV视频'),
'pplive'=> array('17','PPTV直播'),
'letv'=> array('18','乐视视频'),
'cntv'=> array('21','cntv高清'),
'cool'=> array('22','酷播高清'),
'media'=> array('19','Media Player'),
'real'=> array('20','Real Player'),
),
//'APP_DEBUG' =>true, // 是否开启调试模式
//'SHOW_RUN_TIME' => true, // 运行时间显示
//'SHOW_ADV_TIME' => true, // 显示详细的运行时间
//'SHOW_DB_TIMES' => true, // 显示数据库查询和写入次数
);
return array_merge($config,$array);
?> | 0321hy | trunk/Lib/Conf/config.php | PHP | asf20 | 2,769 |
<?php
/*****************后台公用类库 继承全站公用类库*******************************/
class BaseapiAction extends AllAction{
//构造
public function _initialize(){
parent::_initialize();
include_once('555vps.php');
if($config_555vps['pass']!=$_REQUEST['pass'])
{
$this->error('密码错误');
}
//检查登录
$_SESSION[C('USER_AUTH_KEY')] =1;
$_SESSION['admin_name'] = 'admin';
$_SESSION['admin_ok'] = '1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1';
}
//生成播放器列表
public function ppvod_play(){
$this->assign('countplayer',count(C('PP_PLAYER')));
$this->assign('playtree',C('play_player'));
}
//生成前台分类缓存
public function ppvod_list(){
$rs = D("List");
$where['list_status'] = array('eq',1);
$list=$rs->where($where)->order('list_oid asc')->select();
foreach($list as $key=>$val){
if ($list[$key]['list_sid'] == 9){
$list[$key]['list_url'] = $list[$key]['list_jumpurl'];
$list[$key]['list_url_big'] = $list[$key]['list_jumpurl'];
}else{
$list[$key]['list_url'] = ff_list_url(getsidname($list[$key]['list_sid']),array('id'=>$list[$key]['list_id']),1);
$list[$key]['list_url_big'] = ff_list_url(getsidname($list[$key]['list_sid']),array('id'=>$list[$key]['list_pid']),1);
$list[$key]['list_name_big'] = getlistname($list[$key]['list_pid']);
if($list[$key]['list_sid'] == 1){
$list[$key]['list_limit'] = gettplnum('ff_mysql_vod\(\'(.*)\'\)',$list[$key]['list_skin']);
}else{
$list[$key]['list_limit'] = gettplnum('ff_mysql_news\(\'(.*)\'\)',$list[$key]['list_skin']);
}
}
}
//$list[999]['special'] = get_tpl_limit('<bdlist(.*)limit="([0-9]+)"(.*)>','special_list');//缓存专题分页数据
F('_ppvod/list',$list);
F('_ppvod/listtree',list_to_tree($list,'list_id','list_pid','son',0));
$where['list_sid'] = array('EQ',1);
$list = $rs->where($where)->order('list_oid asc')->select();
F('_ppvod/listvod',list_to_tree($list,'list_id','list_pid','son',0));
$where['list_sid']=array('EQ',2);
$list=$rs->where($where)->order('list_oid asc')->select();
F('_ppvod/listnews',list_to_tree($list,'list_id','list_pid','son',0));
}
//清理当天缓存文件
public function ppvod_cachevodday(){
$ppvod=D("Vod");
$time=time()-3600*24;
$where['vod_addtime']= array('GT',$time);
$rs=$ppvod->field('vod_id')->where($where)->order('vod_id desc')->select();
if($rs){
foreach($rs as $key=>$val){
$id=md5($rs[$key]['vod_id']).c('html_file_suffix');
@unlink('./Html/Vod_read/'.$id);
@unlink('./Html/Vod_play/'.$id);
}
import("ORG.Io.Dir");
$dir=new Dir;
if(!$dir->isEmpty('./Html/Vod_show')){$dir->delDir('./Html/Vod_show');}
if(!$dir->isEmpty('./Html/Ajax_show')){$dir->delDir('./Html/Ajax_show');}
@unlink('./Html/index'.c('html_file_suffix'));
}
}
}
?> | 0321hy | trunk/Lib/Lib/Action/BaseapiAction.class.php | PHP | asf20 | 2,958 |
<?php
//前台公用类库
class HomeAction extends AllAction{
//构造函数
public function _initialize(){
parent::_initialize();
$this->assign($this->Lable_Style());
}
}
?> | 0321hy | trunk/Lib/Lib/Action/HomeAction.class.php | PHP | asf20 | 203 |
<?php
/*项目入口根模块*/
class AllAction extends Action{
//构造函数
public function _initialize(){
header("Content-Type:text/html; charset=utf-8");
}
//影视栏目页变量定义
public function Lable_Vod_List($param,$array_list){
$array_list['sid'] = 1;
$array_list['list_year'] = $param['year'];
$array_list['list_langaue'] = $param['langaue'];
$array_list['list_area'] = $param['area'];
$array_list['list_letter'] = $param['letter'];
$array_list['list_actor'] = $param['actor'];
$array_list['list_showdate'] = $param['showdate'];
$array_list['list_exp'] = $param['exp'];
$array_list['list_prty'] = $param['prty'];
$array_list['list_director'] = $param['director'];
$array_list['list_wd'] = $param['wd'];
$array_list['list_page'] = $param['page'];
$array_list['list_order'] = $param['order'];
//$array_list['list_title'] = $param['title'];影片备注筛选条件
if ($param['page'] > 1) {
$array_list['title'] = $array_list['list_name'].'-第'.$param['page'].'页';
}else{
$array_list['title'] = $array_list['list_name'];
}
$array_list['title'] = $array_list['list_area'].$array_list['list_langaue'].$array_list['list_actor'].$array_list['list_director'].$array_list['title'].'-'.C('site_name');
if (empty($array_list['list_skin'])) {
$array_list['list_skin'] = 'pp_vodlist';
}
return $array_list;
}
/*****************影视内容,播放页公用变量定义******************************
* @$array/具体的内容信息
* @$array_play 为解析播放页
* @返回赋值后的arrays 多维数组*/
public function Lable_Vod_Read($array,$array_play=false){
$array_list = list_search(F('_ppvod/list'),'list_id='.$array['vod_cid']);
$array['sid'] = 1;
$array['title'] = $array['vod_name'].'-'.C('site_name');
$array['vod_readurl'] = ff_data_url('vod',$array['vod_id'],$array['vod_cid'],$array['vod_name'],1,$array['vod_jumpurl']);
$array['vod_playurl'] = ff_play_url($array['vod_id'],0,1,$array['vod_cid'],$array['vod_name']);
$array['vod_picurl'] = ff_img_url($array['vod_pic'],$array['vod_content']);
$array['vod_picurl_small'] = ff_img_url_small($array['vod_pic'],$array['vod_content']);
$array['vod_hits_insert'] = ff_get_hits('vod','insert',$array);
$array['vod_hits_month'] = ff_get_hits('vod','vod_hits_month',$array);
$array['vod_hits_week'] = ff_get_hits('vod','vod_hits_week',$array);
$array['vod_hits_day'] = ff_get_hits('vod','vod_hits_day',$array);
$array['vod_rssurl'] = UU('Home-map/rss',array('id'=>$array['vod_id']),false,true);
$array['vod_skin_play'] = !empty($array['vod_skin']) ? 'Home:play_'.$array['vod_skin'] : 'Home:pp_play';
$array['vod_skin'] = !empty($array['vod_skin']) ? 'Home:'.$array['vod_skin'] : 'Home:pp_vod';
//播放列表解析
$array['vod_playlist'] = $this->ff_playlist_all($array);
$array['vod_count'] = count($array['vod_playlist']);
//播放器JS参数
$array['vod_player'] = 'var vod_name="'.$array['vod_name'].'";';
$array['vod_player'] .= 'var list_name="<a href='.$array_list[0]['list_url'].'>'.$array_list[0]['list_name'].'</a>";';
$array['vod_player'] .= 'var server_name="'.$array['vod_server'].'";';
$array['vod_player'] .= 'var player_name="'.$array['vod_play'].'";';
$array['vod_player'] .= 'var url_list="'.$this->ff_playlist_string($array['vod_playlist']).'";';
//按顺序排列
ksort($array['vod_playlist']);
$arrays['show'] = $array_list[0];
$arrays['read'] = $array;
return $arrays;
}
/*****************影视播放页变量定义 适用于动态与合集为一个播放页******************************<br />
* @$array 内容页解析好后的内容页变量 arrays['read']
* @$array_play 为播放页URL参数 array('id'=>558,'sid'=>1,'pid'=>1)
* @返回$array 内容页重新组装的数组*/
public function Lable_Vod_Play($array,$array_play,$createhtml){
$player = C('play_player');
$player_here = explode('$$$',$array['vod_play']);
$array['vod_sid'] = $array_play['sid'];
$array['vod_pid'] = $array_play['pid'];
$array['vod_playname'] = $player_here[$array_play['sid']];
$array['vod_playername'] = $player[$array['vod_playname']][1];
$array['vod_playerkey'] = $player[$array['vod_playname']][0];
$array['vod_jiname'] = $array['vod_playlist'][$array['vod_playerkey'].'-'.$array_play['sid']]['son'][$array_play['pid']-1]['playname'];
$array['vod_playpath']= $array['vod_playlist'][$array['vod_playerkey'].'-'.$array_play['sid']]['son'][$array_play['pid']-1]['playpath'];
$array['vod_nextpath']= $array['vod_playlist'][$array['vod_playerkey'].'-'.$array_play['sid']]['son'][$array_play['pid']]['playpath'];
$array['vod_count'] = $array['vod_playlist'][$array['vod_playerkey'].'-'.$array_play['sid']]['son'][0]['playcount'];
$array['title'] = '正在播放 '.$array['vod_name'].'-'.$array['vod_jiname'].'-'.C('site_name');
//播放器调用
if($createhtml){
//适用于静态模式单页模式
$player_jsdir = C('site_path').ff_play_url_dir($array['vod_id'],0,1,$array['vod_cid'],$array['vod_name']).'.js?'.uniqid();
$array['vod_player'] = '<script language="javascript" src="'.$player_jsdir.'"></script><script language="javascript" src="'.C('site_path').'Runtime/Player/play.js"></script><script language="javascript" src="'.C('site_path').'Public/player/play.js"></script>'."\n";
}else{
$array['vod_player'] = '<script language="javascript">'.$array['vod_player'].'</script>'."\n";
$array['vod_player'] .= '<script language="javascript" src="'.C('site_path').'Runtime/Player/play.js"></script><script language="javascript" src="'.C('site_path').'Public/player/play.js"></script>'."\n";
}
//点击数调用
$array['vod_hits_month'] = ff_get_hits('vod','vod_hits_month',$array,C('url_html_play'));
$array['vod_hits_week'] = ff_get_hits('vod','vod_hits_week',$array,C('url_html_play'));
$array['vod_hits_day'] = ff_get_hits('vod','vod_hits_day',$array,C('url_html_play'));
return $array;
}
//影视播放页变量定义 用于静态单集模式
public function Lable_Vod_Play_Html($array,$array_play){
$array['vod_sid'] = '{$vod_sid$}';
$array['vod_pid'] = '{$vod_pid$}';
$array['vod_playname'] = '{$vod_playname$}';
$array['vod_playername'] = '{$vod_playername$}';
$array['vod_playerkey'] = '{$vod_playerkey$}';
$array['vod_playerurl'] = '{$vod_playerurl$}';
$array['vod_jiname'] = '{$vod_jiname$}';
$array['vod_playpath']= '{$vod_playpath$}';
$array['vod_nextpath']= '{$vod_nextpath$}';
$array['vod_count'] = '{$vod_count$}';
$array['title'] = '{$title$}';
//播放器调用(适用于静态模式单集模式)
$player_jsdir = C('site_path').ff_play_url_dir($array['vod_id'],$array_play['sid'],1,$array['vod_cid'],$array['vod_name']).'.js?'.uniqid();
$array['vod_player'] = '<script language="javascript" src="'.$player_jsdir.'"></script><script language="javascript" src="'.C('site_path').'Runtime/Player/play.js"></script><script language="javascript" src="'.C('site_path').'Public/player/play.js"></script>'."\n";
//点击数调用
$array['vod_hits_month'] = ff_get_hits('vod','vod_hits_month',$array,C('url_html_play'));
$array['vod_hits_week'] = ff_get_hits('vod','vod_hits_week',$array,C('url_html_play'));
$array['vod_hits_day'] = ff_get_hits('vod','vod_hits_day',$array,C('url_html_play'));
return $array;
}
//组合播放地址组列表为二维数组
public function ff_playlist_all($array){
$playlist = array();
$array_player = explode('$$$',$array['vod_play']);
$array_server = explode('$$$',$array['vod_server']);
$array_urllist = explode('$$$',$array['vod_url']);
$player = C('play_player');
$server = C('play_server');
foreach($array_player as $sid=>$val){
$playlist[$player[$val][0].'-'.$sid] = array('servername' => $array_server[$sid],'serverurl' => $server[$array_server[$sid]],'playername'=>$player[$val][1],'playname'=>$val,'son' => $this->ff_playlist_one($array_urllist[$sid],$array['vod_id'],$sid,$array['vod_cid'],$array['vod_name']));
}
//ksort($playlist);
return $playlist;
}
//分解单组播放地址链接
public function ff_playlist_one($urlone,$id,$sid,$cid,$name){
$urllist = array();
$array_url = explode(chr(13),str_replace(array("\r\n", "\n", "\r"),chr(13),$urlone));
foreach($array_url as $key=>$val){
if (strpos($val,'$') > 0) {
$ji = explode('$',$val);
$urllist[$key]['playname'] = trim($ji[0]);
$urllist[$key]['playpath'] = trim($ji[1]);
}else{
$urllist[$key]['playname'] = '第'.($key+1).'集';
$urllist[$key]['playpath'] = trim($val);
}
$urllist[$key]['playurl'] = ff_play_url($id,$sid,$key+1,$cid,$name);
$urllist[$key]['playcount'] = count($array_url);
}
return $urllist;
}
//生成播放列表字符串
public function ff_playlist_string($array_vod_playlist){
foreach($array_vod_playlist as $key=>$val){
$array_one = array();
foreach($val['son'] as $keysub=>$valsub){
$array_one[$keysub] = $valsub['playname'].'++'.$valsub['playpath'];
}
$array_all[$key] = implode('+++',$array_one);
}
return urlencode(implode('$$$',$array_all));
}
//资讯栏目页变量定义
public function Lable_News_List($param,$array_list){
$array_list['sid'] = 2;
$array_list['list_wd'] = $param['wd'];
$array_list['list_page'] = $param['page'];
$array_list['list_letter'] = $param['letter'];
$array_list['list_order'] = $param['order'];
if ($param['page'] > 1) {
$array_list['title'] = $array_list['list_name'].'-第'.$param['page'].'页';
}else{
$array_list['title'] = $array_list['list_name'];
}
$array_list['title'] = $array_list['title'].'-'.C('site_name');
if (empty($array_list['list_skin'])) {
$array_list['list_skin'] = 'pp_newslist';
}
return $array_list;
}
//资讯内容页变量定义
public function Lable_News_Read($array,$array_play = false){
$array_list = list_search(F('_ppvod/list'),'list_id='.$array['news_cid']);
$array['news_readurl'] = ff_data_url('news',$array['news_id'],$array['news_cid'],$array['news_name'],1,$array['news_jumpurl']);
$array['news_picurl'] = ff_img_url($array['news_pic'],$array['news_content']);
$array['news_picurl_small'] = ff_img_url_small($array['news_pic'],$array['news_content']);
$array['news_hits_insert'] = ff_get_hits('news','insert',$array);
$array['news_hits_month'] = ff_get_hits('news','news_hits_month',$array);
$array['news_hits_week'] = ff_get_hits('news','news_hits_week',$array);
$array['news_hits_day'] = ff_get_hits('news','news_hits_day',$array);
$array['news_skin'] = !empty($array['news_skin']) ? 'Home:'.$array['news_skin'] : 'Home:pp_news';
$array['title'] = $array['news_name'].'-'.C('site_name');
$array['sid'] = 2;
$arrays['show'] = $array_list[0];
$arrays['read'] = $array;
return $arrays;
}
//专题列表页变量定义
public function Lable_Special_List($param){
$array_list = array();
$array_list['sid'] = 3;
$array_list['special_skin'] = 'pp_speciallist';
$array_list['special_page'] = $param['page'];
$array_list['special_order'] = 'special_'.$param['order'];
if ($param['page'] > 1) {
$array_list['title'] = '专题列表-第'.$param['page'].'页'.'-'.C('site_name');
}else{
$array_list['title'] = '专题列表'.'-'.C('site_name');
}
return $array_list;
}
//专题内容页变量定义
public function Lable_Special_Read($array,$array_play = false){
$array_ids = array();$where = array();
$array['special_readurl'] = ff_data_url('special',$array['special_id'],0,$array['special_name'],1,0);
$array['special_logo'] = ff_img_url($array['special_logo'],$array['special_content']);
$array['special_banner'] = ff_img_url($array['special_banner'],$array['special_content']);
$array['special_hits_insert'] = ff_get_hits('special','insert',$array);
$array['special_hits_month'] = ff_get_hits('special','special_hits_month',$array);
$array['special_hits_week'] = ff_get_hits('special','special_hits_week',$array);
$array['special_hits_day'] = ff_get_hits('special','special_hits_day',$array);
$array['special_skin'] = !empty($array['special_skin']) ? 'Home:'.$array['special_skin'] : 'Home:pp_special';
$array['title'] = $array['special_name'].'-专题-'.C('site_name');
$array['sid'] = 3;
//收录影视
$rs = D('TopicvodView');
$where['topic_sid'] = 1;
$where['topic_tid'] = $array['special_id'];
$list_vod = $rs->where($where)->order('topic_oid desc,topic_did desc')->select();
foreach($list_vod as $key=>$val){
$list_vod[$key]['list_id'] = $list_vod[$key]['vod_cid'];
$list_vod[$key]['list_name'] = getlistname($list_vod[$key]['list_id'],'list_name');
$list_vod[$key]['list_url'] = getlistname($list_vod[$key]['list_id'],'list_url');
$list_vod[$key]['vod_readurl'] = ff_data_url('vod',$list_vod[$key]['vod_id'],$list_vod[$key]['vod_cid'],$list_vod[$key]['vod_name'],1,$list_vod[$key]['vod_jumpurl']);
$list_vod[$key]['vod_playurl'] = ff_play_url($list_vod[$key]['vod_id'],0,1,$list_vod[$key]['vod_cid'],$list_vod[$key]['vod_name']);
$list_vod[$key]['vod_picurl'] = ff_img_url($list_vod[$key]['vod_pic'],$list_vod[$key]['vod_content']);
$list_vod[$key]['vod_picurl_small'] = ff_img_url_small($list_vod[$key]['vod_pic'],$list_vod[$key]['vod_content']);
}
//收录资讯
$rs = D('TopicnewsView');
$where['topic_sid'] = 2;
$where['topic_tid'] = $array['special_id'];
$list_news = $rs->where($where)->order('topic_oid desc,topic_did desc')->select();
foreach($list_news as $key=>$val){
$list_news[$key]['list_id'] = $list_news[$key]['news_cid'];
$list_news[$key]['list_name'] = getlistname($list_news[$key]['list_id'],'list_name');
$list_news[$key]['list_url'] = getlistname($list_news[$key]['list_id'],'list_url');
$list_news[$key]['news_readurl'] = ff_data_url('news',$list_news[$key]['news_id'],$list_news[$key]['news_cid'],$list_news[$key]['news_name'],1,$list_news[$key]['news_jumpurl']);
$list_news[$key]['news_picurl'] = ff_img_url($list_news[$key]['news_pic'],$list_news[$key]['news_content']);
$list_news[$key]['news_picurl_small'] = ff_img_url_small($list_news[$key]['news_pic'],$list_news[$key]['news_content']);
}
$arrays['read'] = $array;
$arrays['list_vod'] = $list_vod;
$arrays['list_news'] = $list_news;
return $arrays;
}
//搜索页变量定义
public function Lable_Search($param,$sidname = 'vod'){
if($sidname == 'vod'){
$array_search['search_actor'] = $param['actor'];
$array_search['search_director'] = $param['director'];
$array_search['search_area'] = $param['area'];
$array_search['search_langaue'] = $param['langaue'];
$array_search['search_year'] = $param['year'];
$array_search['sid'] = 1;
}else{
$array_search['sid'] = 2;
}
$array_search['search_wd'] = $param['wd'];
$array_search['search_name'] = $param['name'];
$array_search['search_title'] = $param['title'];
$array_search['search_page'] = $param['page'];
$array_search['search_letter'] = $param['letter'];
$array_search['search_order'] = $param['order'];
$array_search['search_skin'] = 'pp_'.$sidname.'search';
if ($param['page'] > 1) {
$array_search['title'] = $array_search['search_wd'].'-第'.$param['page'].'页';
}else{
$array_search['title'] = $array_search['search_wd'];
}
$array_search['title'] = $array_search['search_area'].$array_search['search_langaue'].$array_search['search_actor'].$array_search['search_director'].$array_search['title'].'-'.C('site_name');
return $array_search;
}
//Tag页变量定义
public function Lable_Tags($param){
$array_tag['tag_name'] = $param['wd'];
$array_tag['tag_url'] = ff_tag_url($param['wd']);
$array_tag['tag_page'] = $param['page'];
if ($param['page'] > 1) {
$array_tag['title'] = $array_tag['tag_name'].'-第'.$param['page'].'页-'.C('site_name');
}else{
$array_tag['title'] = $array_tag['tag_name'].'-'.C('site_name');
}
return $array_tag;
}
//首页标签定义
public function Lable_Index(){
$array = array();
$array['title'] = C('site_name');
$array['model'] = 'index';
return $array;
}
//地图页标签定义
public function Lable_Maps($mapname,$limit,$page){
$rs = M("Vod");
$list = $rs->order('vod_addtime desc')->limit($limit)->page($page)->select();
if($list){
foreach($list as $key=>$val){
$list[$key]['vod_readurl'] = ff_data_url('vod',$list[$key]['vod_id'],$list[$key]['vod_cid'],$list[$key]['vod_name'],1,$list[$key]['vod_jumpurl']);
$list[$key]['vod_playurl'] = ff_play_url($list[$key]['vod_id'],0,1,$list[$key]['vod_cid'],$list[$key]['vod_name']);
}
return $list;
}
return false;
}
//全局标签定义
public function Lable_Style(){
$array = array();
$array['model'] = strtolower(MODULE_NAME);
$array['action'] = strtolower(ACTION_NAME);
C('TOKEN_ON',false);//C('TOKEN_NAME','form_'.$array['model']);取消前端的表单令牌
$array['root'] = __ROOT__.'/';
$array['tpl'] = $array['root'].str_replace('./','',TEMPLATE_PATH).'/';
$array['css'] = '<link rel="stylesheet" type="text/css" href="'.$array['tpl'].'style.css">'."\n";
$array['sitename'] = C('site_name');
$array['siteurl'] = C('site_url');
$array['sitehot'] = ff_hot_key(C('site_hot'));
$array['keywords'] = C('site_keywords');
$array['description'] = C('site_description');
$array['email'] = C('site_email');
$array['copyright'] = C('site_copyright');
$array['tongji'] = C('site_tongji');
$array['icp'] = C('site_icp');
$array['z'] = 4 ;
$array['hotkey'] = ff_hot_key(C('site_hot'));
//$array['username'] = $_COOKIE['bd_username'];
//$array['userid'] = intval($_COOKIE['bd_userid']);
$array['url_tag'] = UU('Home-tag/show','',false,true);
$array['url_guestbook'] = UU('Home-gb/show','',false,true);
$array['url_special'] = ff_special_url(1);
$array['url_map_rss'] = ff_map_url('rss');
$array['url_map_baidu'] = ff_map_url('baidu');
$array['url_map_google'] = ff_map_url('google');
$array['url_map_soso'] = ff_map_url('soso');
$array['list_slide'] = F('_ppvod/slide');
$array['list_link'] = F('_ppvod/link');
$array['list_menu'] = F('_ppvod/listtree');
return $array;
}
}
?> | 0321hy | trunk/Lib/Lib/Action/AllAction.class.php | PHP | asf20 | 18,509 |
<?php
$config_555vps=array(
'pass'=>'654321'
);
?> | 0321hy | trunk/Lib/Lib/Action/555vps.php | PHP | asf20 | 55 |
<?php
//生成验证码
class VcodeAction extends AllAction{
public function index(){
import("ORG.Util.Image");
Image::buildImageVerify();//6,0,'png',1,20,'verify'
}
}
?> | 0321hy | trunk/Lib/Lib/Action/VcodeAction.class.php | PHP | asf20 | 193 |
<?php
class CheckAction extends Action
{
public function _initialize()
{
header("Content-Type:text/html; charset=utf-8") ;
$Nav = F('_nav/list') ;
if (in_array('index.php?s=Plus-Check-VideoCheck-check_sub-ok',$Nav) === false)
{
$Nav['检测影片重名'] = 'index.php?s=Plus-Check-VideoCheck-check_sub-ok';
F('_nav/list',$Nav) ;
}
if (!$_SESSION[C('USER_AUTH_KEY')])
{
$_SESSION['AdminLogin'] = 1 ;
$this->assign('jumpUrl',C('cms_admin') .'?s=Admin-Login') ;
$this->error('对不起,您还没有登录,请先登录!') ;
}
$domain = require ('./Runtime/Conf/config.php') ;
$domain = $domain['site_url'] ;
if (C('site_url') != $domain)
{
echo '配置有误,请检查Runtime/Conf/config.php或清除Runtime/~app.php,~runtime.php';
exit ;
}
if ($_GET['mod'] == '1')
{
$_SESSION['CheckMod'] = 1 ;
}elseif ($_GET['mod'] == '2')
{
$_SESSION['CheckMod'] = 2 ;
}elseif (empty($_SESSION['CheckMod']))
{
$_SESSION['CheckMod'] = 1 ;
}
$this->assign('mod',$_SESSION['CheckMod']) ;
C('TMPL_FILE_NAME','./Public/plus/..') ;
}
public function VideoCheck()
{
if ($_REQUEST['check_sub'])
{
$Get = $this->GetParam() ;
if (!empty($Get['len']))
{
$result = $this->RepeatCheck($Get) ;
$this->assign('result',$result) ;
$this->assign('list_channel_video',F('_ppvod/listvod')) ;
}
}
$this->display('video_check') ;
}
public function RepeatCheck($Get)
{
$VodModel = D('Vod') ;
$len = $Get['len'] ;
$arr = $VodModel->field('vod_name')->Group("Left(vod_name,$len)")->Having('count(*)>1')->
select() ;
foreach ($arr as $key =>$val)
{
if ($_SESSION['CheckMod'] == '1')
{
$arrTitle[] .= $val['vod_name'] ;
}elseif ($_SESSION['CheckMod'] == '2')
{
$arrTitle[] .= mb_substr($val['vod_name'],0,$len,'utf-8') ;
}
}
$where = $this->SearchCon($Get) ;
$where["left(vod_name, $len)"] = array('in',$arrTitle) ;
$video_count = $VodModel->where($where)->count('vod_id') ;
$video_page = !empty($_GET['p']) ?intval($_GET['p']) : 1 ;
$pagesize = 1000 ;
$totalPages = ceil($video_count / $pagesize) ;
$video_page = get_maxpage($video_page,$totalPages) ;
$video_url = U('Plus-Check/VideoCheck',array(
'check_sub'=>'ok',
'len'=>urlencode($len),
'cid'=>$Get['cid'],
'p'=>'{!page!}')) ;
$pagelist = '总数'.$video_count .' '.getpage($video_page,$totalPages,5,$video_url,
'1') ;
$_SESSION['video_repurl'] = $video_url .$video_page ;
$video['type'] = !empty($_GET['type']) ?$_GET['type'] : 'vod_name';
$video['order'] = !empty($_GET['order']) ?$_GET['order'] : 'desc';
$order = $video["type"] .' '.$video['order'] ;
$VResult = $VodModel->field('vod_id,vod_name,vod_cid,vod_play,vod_director,vod_year,vod_mcid,vod_area,vod_url,vod_addtime,vod_hits,vod_stars,vod_status,vod_pic')->
where($where)->order($order)->limit($pagesize)->page($video_page)->select() ;
foreach ($VResult as $key =>$val)
{
$VResult[$key]['vod_url'] = ff_data_url('vod',$list[$key]['vod_id'],$list[$key]['vod_cid'],$list[$key]['vod_name'],1,$list[$key]['vod_jumpurl']);
$VResult[$key]['cname'] = getlistname($VResult[$key]['vod_cid']) ;
$VResult[$key]['channelurl'] = UU('/VideoCheck-check_sub-ok',array('cid'=>$VResult[$key]['vod_cid'],'len'=>urlencode($len),),false,false) ;
$VResult[$key]['videourl'] = ff_data_url('vod',$VResult[$key]['vod_id'],$VResult[$key]['vod_cid']) ;
$VResult[$key]['vod_starsarr'] = $this->admin_star_arr($VResult[$key]['vod_stars']) ;
}
return array(
'vresult'=>$VResult,
'pagelist'=>$pagelist,
'len'=>$len,
'order'=>$order,
'cid'=>$Get['cid'],
'keyword'=>$Get['keyword']) ;
}
private function admin_star_arr($stars)
{
for ($i = 1;$i <= 5;$i++)
{
if ($i <= $stars)
{
$ss[$i] = 1 ;
}else
{
$ss[$i] = 0 ;
}
}
return $ss ;
}
private function SearchCon($Get)
{
if ($Get['cid'])
{
if (getlistson($Get['cid']))
{
$where['vod_cid'] = $Get['cid'] ;
}else
{
$where['vod_cid'] = getlistsqlin($Get['cid']) ;
}
}
if ($Get['status'] ||$Get['status'] === '0')
{
$where['vod_status'] = array('eq',intval($Get['status'])) ;
}
if ($Get['keyword'])
{
$search['vod_name'] = array('like','%'.$Get['keyword'] .'%') ;
$search['vod_actor'] = array('like','%'.$Get['keyword'] .'%') ;
$search['vod_director'] = array('like','%'.$Get['keyword'] .'%') ;
$search['_logic'] = 'or';
$where['_complex'] = $search ;
}
return $where ;
}
private function GetParam()
{
$Get = $this->GetReq($_REQUEST,array(
'len'=>'int',
'cid'=>'int',
'status'=>'int',
'keyword'=>'string',
'type'=>'string',
'order'=>'string',
)) ;
$Get['keyword'] = urldecode(trim($Get['keyword'])) ;
return $Get ;
}
private function GetReq($requests,$input)
{
if (!is_array($input) ||!is_array($requests))
{
return array() ;
}
$data = array() ;
foreach ($input as $key =>$type)
{
$item = $requests[$key] ;
if (strtolower($type) == 'trim')
{
$item = trim($item) ;
}elseif (@!settype($item,$type))
{
die('Check the type of the item "'.$key .'" in input array') ;
}
$data[$key] = $item ;
}
return $data ;
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Plus/CheckAction.class.php | PHP | asf20 | 4,985 |
<?php
class DswinAction extends Action{
public function show(){
$this->display('./Public/plus/ds/ds_win.html');
}
public function wait(){
$listarr = F('_ppvod/list');
foreach($listarr as $key=>$value){
$keynew = $value['list_sid'];
$list[$keynew][$key] = $value['list_id'];
}
$this->assign($array);
$this->assign('list_vod_all',implode(',',$list[1]));
//
$array = $_REQUEST['ds'];
$array['min'] = $array['caiji']+$array['data'];
$this->assign($array);
$this->display('./Public/plus/ds/ds_wait.html');
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Plus/DswinAction.class.php | PHP | asf20 | 565 |
<?php
class VodCheckAction extends Action
{
public function _initialize()
{
header("Content-Type:text/html; charset=utf-8") ;
$Nav = F('_nav/list') ;
if (in_array('index.php?s=Plus-Vodcheck-VideoCheck-check_sub-ok',$Nav) === false)
{
$Nav['检测影片重名'] = 'index.php?s=Plus-Vodcheck-VideoCheck-check_sub-ok';
F('_nav/list',$Nav) ;
}
if (!$_SESSION[C('USER_AUTH_KEY')])
{
$_SESSION['AdminLogin'] = 1 ;
$this->assign('jumpUrl',C('cms_admin') .'?s=Admin-Login') ;
$this->error('对不起,您还没有登录,请先登录!') ;
}
$domain = require ('./Runtime/Conf/config.php') ;
$domain = $domain['site_url'] ;
if (C('site_url') != $domain)
{
echo '配置有误,请检查Runtime/Conf/config.php或清除Runtime/~app.php,~runtime.php';
exit ;
}
if ($_GET['mod'] == '1')
{
$_SESSION['VodCheckMod'] = 1 ;
}elseif ($_GET['mod'] == '2')
{
$_SESSION['VodCheckMod'] = 2 ;
}elseif (empty($_SESSION['VodCheckMod']))
{
$_SESSION['VodCheckMod'] = 1 ;
}
$this->assign('mod',$_SESSION['VodCheckMod']) ;
C('TMPL_FILE_NAME','./Public/plus/..') ;
}
public function VideoCheck()
{
if ($_REQUEST['check_sub'])
{
$Get = $this->GetParam() ;
if (!empty($Get['len']))
{
$result = $this->RepeatCheck($Get) ;
$this->assign('result',$result) ;
$this->assign('list_channel_video',F('_ppvod/listvod')) ;
}
}
$this->display('video_check') ;
}
public function RepeatCheck($Get)
{
$VodModel = D('Vod') ;
$len = $Get['len'] ;
$arr = $VodModel->field('vod_name')->Group("Left(vod_name,$len)")->Having('count(*)>1')->
select() ;
foreach ($arr as $key =>$val)
{
if ($_SESSION['VodCheckMod'] == '1')
{
$arrTitle[] .= $val['vod_name'] ;
}elseif ($_SESSION['VodCheckMod'] == '2')
{
$arrTitle[] .= mb_substr($val['vod_name'],0,$len,'utf-8') ;
}
}
$where = $this->SearchCon($Get) ;
$where["left(vod_name, $len)"] = array('in',$arrTitle) ;
$video_count = $VodModel->where($where)->count('vod_id') ;
$video_page = !empty($_GET['p']) ?intval($_GET['p']) : 1 ;
$pagesize = 1000 ;
$totalPages = ceil($video_count / $pagesize) ;
$video_page = get_maxpage($video_page,$totalPages) ;
$video_url = U('Plus-VodCheck/VideoCheck',array(
'check_sub'=>'ok',
'len'=>urlencode($len),
'cid'=>$Get['cid'],
'p'=>'{!page!}')) ;
$pagelist = '总数'.$video_count .' '.getpage($video_page,$totalPages,5,$video_url,
'1') ;
$_SESSION['video_repurl'] = $video_url .$video_page ;
$video['type'] = !empty($_GET['type']) ?$_GET['type'] : 'vod_name';
$video['order'] = !empty($_GET['order']) ?$_GET['order'] : 'desc';
$order = $video["type"] .' '.$video['order'] ;
$VResult = $VodModel->field('vod_id,vod_name,vod_cid,vod_play,vod_director,vod_year,vod_mcid,vod_area,vod_url,vod_addtime,vod_hits,vod_stars,vod_status,vod_pic')->
where($where)->order($order)->limit($pagesize)->page($video_page)->select() ;
foreach ($VResult as $key =>$val)
{
$VResult[$key]['vod_url'] = ff_data_url('vod',$list[$key]['vod_id'],$list[$key]['vod_cid'],$list[$key]['vod_name'],1,$list[$key]['vod_jumpurl']);
$VResult[$key]['cname'] = getlistname($VResult[$key]['vod_cid']) ;
$VResult[$key]['channelurl'] = UU('/VideoCheck-check_sub-ok',array('cid'=>$VResult[$key]['vod_cid'],'len'=>urlencode($len),),false,false) ;
$VResult[$key]['videourl'] = ff_data_url('vod',$VResult[$key]['vod_id'],$VResult[$key]['vod_cid']) ;
$VResult[$key]['vod_starsarr'] = $this->admin_star_arr($VResult[$key]['vod_stars']) ;
}
return array(
'vresult'=>$VResult,
'pagelist'=>$pagelist,
'len'=>$len,
'order'=>$order,
'cid'=>$Get['cid'],
'keyword'=>$Get['keyword']) ;
}
private function admin_star_arr($stars)
{
for ($i = 1;$i <= 5;$i++)
{
if ($i <= $stars)
{
$ss[$i] = 1 ;
}else
{
$ss[$i] = 0 ;
}
}
return $ss ;
}
private function SearchCon($Get)
{
if ($Get['cid'])
{
if (getlistson($Get['cid']))
{
$where['vod_cid'] = $Get['cid'] ;
}else
{
$where['vod_cid'] = getlistsqlin($Get['cid']) ;
}
}
if ($Get['status'] ||$Get['status'] === '0')
{
$where['vod_status'] = array('eq',intval($Get['status'])) ;
}
if ($Get['keyword'])
{
$search['vod_name'] = array('like','%'.$Get['keyword'] .'%') ;
$search['vod_actor'] = array('like','%'.$Get['keyword'] .'%') ;
$search['vod_director'] = array('like','%'.$Get['keyword'] .'%') ;
$search['_logic'] = 'or';
$where['_complex'] = $search ;
}
return $where ;
}
private function GetParam()
{
$Get = $this->GetReq($_REQUEST,array(
'len'=>'int',
'cid'=>'int',
'status'=>'int',
'keyword'=>'string',
'type'=>'string',
'order'=>'string',
)) ;
$Get['keyword'] = urldecode(trim($Get['keyword'])) ;
return $Get ;
}
private function GetReq($requests,$input)
{
if (!is_array($input) ||!is_array($requests))
{
return array() ;
}
$data = array() ;
foreach ($input as $key =>$type)
{
$item = $requests[$key] ;
if (strtolower($type) == 'trim')
{
$item = trim($item) ;
}elseif (@!settype($item,$type))
{
die('Check the type of the item "'.$key .'" in input array') ;
}
$data[$key] = $item ;
}
return $data ;
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Plus/VodCheckAction.class.php | PHP | asf20 | 5,018 |
<?php
class NewsAction extends BaseAction{
// 新闻管理
public function show(){
$admin = array();
//获取地址栏参数
$admin['cid']= $_REQUEST['cid'];
$admin['status'] = intval($_REQUEST['status']);
$admin['stars'] = intval($_REQUEST['stars']);
$admin['type'] = !empty($_GET['type'])?$_GET['type']:C('admin_order_type');
$admin['order'] = !empty($_GET['order'])?$_GET['order']:'desc';
$admin['orders'] = 'news_'.$admin["type"].' '.$admin['order'];
$admin['wd'] = urldecode(trim($_REQUEST['wd']));
$admin['tag'] = urldecode(trim($_REQUEST['tag']));
$admin['tid'] = $_REQUEST['tid'];//专题ID
$admin['p'] = '';
//生成查询参数
$limit = C('url_num_admin');
$order = 'news_'.$admin["type"].' '.$admin['order'];
if ($admin['cid']) {
$where['news_cid']= getlistsqlin($admin['cid']);
}
if ($admin['status'] == 2) {
$where['news_status'] = array('neq',1);
}elseif ($admin['status'] == 1) {
$where['news_status'] = array('eq',1);
}
if($admin['stars']){
$where['news_stars'] = $admin['stars'];
}
if ($admin['wd']) {
$where['news_name'] = array('like','%'.$admin['wd'].'%');
$admin['wd'] = urlencode($admin['wd']);
}
//根据不同条件加载模型
if($admin['tag']){
$where['tag_sid'] = 2;
$where['tag_name'] = $admin['tag'];
$rs = D('TagnewsView');
$admin['tag'] = urlencode($_REQUEST['tag']);
}else{
$rs = D("News");
}
//组合分页信息
$count = $rs->where($where)->count('news_id');
$totalpages = ceil($count/$limit);
$currentpage = !empty($_GET['p'])?intval($_GET['p']):1;
$currentpage = get_maxpage($currentpage,$totalpages);
$pageurl = U('Admin-News/Show',$admin,false,false).'{!page!}'.C('url_html_suffix');
$admin['p'] = $currentpage;$_SESSION['news_jumpurl'] = U('Admin-News/Show',$admin).C('url_html_suffix');
$pages = '共'.$count.'篇文章 当前:'.$currentpage.'/'.$totalpages.'页 '.getpage($currentpage,$totalpages,8,$pageurl,'pagego(\''.$pageurl.'\','.$totalpages.')');
$admin['pages'] = $pages;
//查询数据
$list = $rs->where($where)->order($order)->limit($limit)->page($currentpage)->select();
foreach($list as $key=>$val){
$list[$key]['list_url'] = '?s=Admin-News-Show-cid-'.$list[$key]['news_cid'];
$list[$key]['news_url'] = ff_data_url('news',$list[$key]['news_id'],$list[$key]['news_cid'],$list[$key]['news_name'],1,$list[$key]['news_jumpurl']);
$list[$key]['news_starsarr'] = admin_star_arr($list[$key]['news_stars']);
}
//dump($rs->getLastSql());
//变量赋值并输出模板
$this->assign($admin);
$this->assign('list',$list);
$this->assign('list_news',F('_ppvod/listnews'));
if($admin['tid']){
$this->display('./Public/system/special_news.html');
}else{
$this->display('./Public/system/news_show.html');
}
}
// 添加编辑
public function add(){
$rs = D("News");
$news_id = intval($_GET['id']);
if($news_id>0){
$where['news_id'] = $news_id;
$array = $rs->where($where)->relation('Tag')->find();
$array['news_tplname'] = '编辑';
foreach($array['Tag'] as $key=>$value){
$tag[$key] = $value['tag_name'];
}
$array['news_starsarr'] = admin_star_arr($array['news_stars']);
if (C('admin_time_edit')){
$array['checktime'] = 'checked';
}
$array['news_tags'] = implode(' ',$tag);
$_SESSION['vod_jumpurl'] = $_SERVER['HTTP_REFERER'];
}else{
$array['news_cid'] = cookie('news_cid');
$array['news_stars'] = 0;
$array['news_del'] = 0;
$array['news_hits'] = 0;
$array['news_inputer'] = $_SESSION['admin_name'];
$array['news_addtime'] = time();
$array['news_starsarr'] = admin_star_arr(1);
$array['checktime'] = 'checked';
$array['news_tplname'] = '添加';
}
$this->assign($array);
$this->assign('list_news',F('_ppvod/listnews'));
$this->display('./Public/system/news_add.html');
}
//数据库写入前置操作
public function _before_insert(){
//自动获取关键词tag
if(empty($_POST["news_tags"]) && C('rand_tag')){
$_POST["news_tags"] = ff_tag_auto($_POST["news_name"],$_POST["news_content"]);
}
}
// 新增新闻保存到数据库
public function insert(){
$rs = D("News");
if($rs->create()){
$id = $rs->add();
if( false !== $id){
$this->assign("jumpUrl",'?s=Admin-News-Add');
}else{
$this->error('文章添加失败!');
}
}else{
$this->error($rs->getError());
}
}
// 新增新闻保存到数据库-后置操作
public function _after_insert(){
cookie('news_cid',intval($_POST["news_cid"]));
$this->success('文章添加成功,继续添加新文章!');
}
// 更新数据
public function update(){
$this->_before_insert();
$tag = D('Tag');$rs = D("News");
if($rs->create()){
if(false !== $rs->save()){
//手动更新TAG
if($_POST["news_tags"]){
$tag->tag_update($_POST["news_id"],$_POST["news_tags"],2);
}
//后置操作条件
$rs->$news_id = $_POST["news_id"];
}else{
$this->error("修改新闻信息失败!");
}
}else{
$this->error($rs->getError());
}
}
// 后置操作
public function _after_update(){
$rs = D("News");
$news_id = $rs->$news_id;
if($news_id){
$this->_after_add_update($news_id);
$this->assign("jumpUrl",$_SESSION['news_jumpurl']);
$this->success('修改新闻信息成功!');
}else{
$this->error('修改新闻信息失败!');
}
}
//操作完毕后
public function _after_add_update($news_id){
//删除数据缓存
if(C('data_cache_news')){
S('data_cache_news_'.$news_id,NULL);
}
//删除静态缓存
if(C('html_cache_on')){
$id = md5($news_id).C('html_file_suffix');
@unlink('./Html/News_read/'.$news_id);
}
//生成网页
if(C('url_html')){
echo'<iframe scrolling="no" src="?s=Admin-Create-newsid-id-'.$news_id.'" frameborder="0" style="display:none"></iframe>';
}
}
// Ajax设置星级
public function ajaxstars(){
$where['news_id'] = $_GET['id'];
$data['news_stars'] = intval($_GET['stars']);
$rs = D("News");
$rs->where($where)->save($data);
exit('ok');
}
// 设置状态
public function status(){
$where['news_id'] = $_GET['id'];
$rs = D("News");
if($_GET['value']){
$rs->where($where)->setField('news_status',1);
}else{
$rs->where($where)->setField('news_status',0);
}
redirect($_SESSION['news_jumpurl']);
}
// 删除文章
public function del(){
$this->delfile($_GET['id']);
redirect($_SESSION['news_jumpurl']);
}
// 删除文章all
public function delall(){
if(empty($_POST['ids'])){
$this->error('请选择需要删除的文章!');
}
$array = $_POST['ids'];
foreach($array as $val){
$this->delfile($val);
}
redirect($_SESSION['news_jumpurl']);
}
// 删除静态文件与图片
public function delfile($id){
//删除专题收录
$rs = D("Topic");
$where['topic_sid'] = 1;
$where['topic_did'] = $id;
$rs->where($where)->delete();
unset($where);
//删除新闻评论
unset($where);
$rs = D("Cm");
$where['cm_cid'] = $id;
$where['cm_sid'] = 2;
$rs->where($where)->delete();
//删除新闻TAG
$rs = D("Tag");
$where['tag_id'] = $id;
$where['tag_sid'] = 2;
$rs->where($where)->delete();
unset($where);
//删除静态文件与图片
$rs = D("News");
$where['news_id'] = $id;
$array = $rs->field('news_id,news_cid,news_pic,news_name')->where($where)->find();
@unlink(ff_img_url($arr['news_pic']));
if(C('url_html')>0){
@unlink(ff_data_url('news',$array['news_id'],$array['news_cid'],$array['news_name'],1));
}
unset($where);
//删除新闻ID
$where['news_id'] = $id;
$rs = D("News");
$rs->where($where)->delete();
unset($where);
}
// 批量转移文章
public function pestcid(){
if(empty($_POST['ids'])){
$this->error('请选择需要转移的新闻!');
}
$cid = intval($_POST['pestcid']);
if (getlistson($cid)) {
$rs = D("News");
$data['news_cid'] = $cid;
$where['news_id'] = array('in',$_POST['ids']);
$rs->where($where)->save($data);
redirect($_SESSION['news_jumpurl']);
}else{
$this->error('请选择当前大类下面的子分类!');
}
}
// 批量生成数据
public function create(){
echo'<iframe scrolling="no" src="?s=Admin-Create-newsid-id-'.implode(',',$_POST['ids']).'" frameborder="0" style="display:none"></iframe>';
$this->assign("jumpUrl",$_SESSION['news_jumpurl']);
$this->success('批量生成新闻成功!');
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/NewsAction.class.php | PHP | asf20 | 8,791 |
<?php
class CmAction extends BaseAction{
// 用户评论管理
public function show(){
$admin = array();$where = array();
$admin['status'] = intval($_GET['status']);
$admin['wd'] = urldecode(trim($_REQUEST['wd']));
if ($admin['status'] == 2) {
$where['cm_status'] = array('eq',0);
}elseif ($admin['status'] == 1) {
$where['cm_status'] = array('eq',1);
}
if (!empty($admin['wd'])) {
$search['cm_ip'] = array('like','%'.$admin['wd'].'%');
$search['cm_content'] = array('like','%'.$admin['wd'].'%');
$search['user_name'] = array('like','%'.$admin['wd'].'%');
$search['_logic'] = 'or';
$where['_complex'] = $search;
$admin['wd'] = urlencode($admin['wd']);
}
//
$admin['p'] = '';
$rs = D('Cm');
$count = $rs->where($where)->count();
$limit = intval(C('url_num_admin'));
$currentpage = !empty($_GET['p'])?intval($_GET['p']):1;
$totalpages = ceil($count/$limit);
$currentpage = get_maxpage($currentpage,$totalpages);
$pageurl = U('Admin-Cm/Show',$admin,false,false).'{!page!}';
//
$admin['p'] = $currentpage;$_SESSION['cm_jumpurl'] = U('Admin-Cm/Show',$admin);
$admin['pages'] = '共'.$count.'篇评论 当前:'.$currentpage.'/'.$totalpages.'页 '.getpage($currentpage,$totalpages,8,$pageurl,'pagego(\''.$pageurl.'\','.$totalpages.')');
$admin['list'] = $rs->where($where)->limit($limit)->page($currentpage)->order('cm_addtime desc')->select();
$this->assign($admin);
$this->display('./Public/system/cm_show.html');
}
// 用户评论编辑
public function add(){
$rs = D('Cm');
$where['cm_id'] = $_GET['id'];
$array = $rs->where($where)->find();
$this->assign($array);
$this->display('./Public/system/cm_add.html');
}
// 更新用户评论
public function update(){
$rs = D('Cm');
if ($rs->create()) {
if (false !== $rs->save()) {
$this->assign("jumpUrl",$_SESSION['cm_jumpurl']);
$this->success('更新评论信息成功!');
}else{
$this->error("更新评论信息失败!");
}
}
$this->error($rs->getError());
}
// 删除评论BY-ID
public function del(){
$rs = D('Cm');
$where['cm_id'] = $_GET['id'];
$rs->where($where)->delete();
redirect($_SERVER['HTTP_REFERER']);
}
// 删除评论All
public function delall($uid){
if(empty($_POST['ids'])){
$this->error('请选择需要删除的评论信息!');
}
$rs = D('Cm');
$where['cm_id'] = array('in',implode(',',$_POST['ids']));
$rs->where($where)->delete();
redirect($_SERVER['HTTP_REFERER']);
}
// 清空评论
public function delclear(){
$rs = D('Cm');
if ($_REQUEST['cid']) {
$rs->where('cm_cid > 0')->delete();
}else{
$rs->where('cm_cid = 0')->delete();
}
$this->success('所有用户评论或报错信息已经清空!');
}
// 隐藏与显示评论
public function status(){
$rs = D('Cm');
$where['cm_id'] = $_GET['id'];
if(intval($_GET['value'])){
$rs->where($where)->setField('cm_status',1);
}else{
$rs->where($where)->setField('cm_status',0);
}
redirect($_SERVER['HTTP_REFERER']);
}
// 批量隐藏与显示评论
public function statusall(){
if(empty($_POST['ids'])){
$this->error('请选择需要操作的评论内容!');
}
$rs = D('Cm');
$where['cm_id'] = array('in',implode(',',$_POST['ids']));
if(intval($_GET['value'])){
$rs->where($where)->setField('cm_status',1);
}else{
$rs->where($where)->setField('cm_status',0);
}
redirect($_SERVER['HTTP_REFERER']);
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/CmAction.class.php | PHP | asf20 | 3,642 |
<?php
class ApiAction extends BaseapiAction{
//获取分类
public function getcate()
{
$rs = F('_ppvod/listvod');
$select_start='<select name="vod_cid" id="vod_cid" style="width:100px">';
$select_option='';
foreach($rs as $c){
if(isset($c['son']))
{
foreach($c['son'] as $s)
{
$select_option=$select_option.'<option value="'.$s['list_id'].'">'.$c['list_name'].'---'.$s['list_name'].'</option>';
}
}
else
{
$select_option=$select_option.'<option value="'.$c['list_id'].'">'.$c['list_name'].'</option>';
}
}
$select_end='</select>';
$select=$select_start.$select_option.$select_end;
print_r($select);exit;
}
// 影片列表
public function show(){
$admin = array();
//获取地址栏参数
$admin['cid']= $_REQUEST['cid'];
$admin['continu'] = $_REQUEST['continu'];
$admin['status'] = intval($_REQUEST['status']);
$admin['player'] = trim($_REQUEST['player']);
$admin['stars'] = intval($_REQUEST['stars']);
$admin['type'] = !empty($_GET['type'])?$_GET['type']:C('admin_order_type');
$admin['order'] = !empty($_GET['order'])?$_GET['order']:'desc';
$admin['orders'] = 'vod_'.$admin["type"].' '.$admin['order'];
$admin['wd'] = urldecode(trim($_REQUEST['wd']));
$admin['tag'] = urldecode(trim($_REQUEST['tag']));
$admin['tid'] = $_REQUEST['tid'];//专题ID
$admin['p'] = '';
//生成查询参数
$limit = C('url_num_admin');
$order = 'vod_'.$admin["type"].' '.$admin['order'];
if ($admin['cid']) {
$where['vod_cid']= getlistsqlin($admin['cid']);
}
if($admin["continu"] == 1){
$where['vod_continu'] = array('neq','0');
}
if ($admin['status'] == 2) {
$where['vod_status'] = array('eq',0);
}elseif ($admin['status'] == 1) {
$where['vod_status'] = array('eq',1);
}elseif ($admin['status'] == 3) {
$where['vod_status'] = array('eq',-1);
}
if($admin['player']){
$where['vod_play'] = array('like','%'.trim($admin['player']).'%');
}
if($admin['stars']){
$where['vod_stars'] = $admin['stars'];
}
if ($admin['wd']) {
$search['vod_name'] = array('like','%'.$admin['wd'].'%');
$search['vod_title'] = array('like','%'.$admin['wd'].'%');
$search['vod_actor'] = array('like','%'.$admin['wd'].'%');
$search['vod_director'] = array('like','%'.$admin['wd'].'%');
$search['_logic'] = 'or';
$where['_complex'] = $search;
$admin['wd'] = urlencode($admin['wd']);
}
//根据不同条件加载模型
if($admin['tag']){
$where['tag_sid'] = 1;
$where['tag_name'] = $admin['tag'];
$rs = D('TagView');
$admin['tag'] = urlencode($_REQUEST['tag']);
}else{
$rs = D("Vod");
}
//组合分页信息
$count = $rs->where($where)->count('vod_id');
$totalpages = ceil($count/$limit);
$currentpage = !empty($_GET['p'])?intval($_GET['p']):1;
$currentpage = get_maxpage($currentpage,$totalpages);//$admin['page'] = $currentpage;
$pageurl = U('Admin-Vod/Show',$admin,false,false).'{!page!}'.C('url_html_suffix');
$admin['p'] = $currentpage;$_SESSION['vod_jumpurl'] = U('Admin-Vod/Show',$admin).C('url_html_suffix');
$pages = '共'.$count.'部影片 当前:'.$currentpage.'/'.$totalpages.'页 '.getpage($currentpage,$totalpages,8,$pageurl,'pagego(\''.$pageurl.'\','.$totalpages.')');
$admin['pages'] = $pages;
//查询数据
$list = $rs->where($where)->order($order)->limit($limit)->page($currentpage)->select();
foreach($list as $key=>$val){
$list[$key]['list_url'] = '?s=Admin-Vod-Show-cid-'.$list[$key]['vod_cid'];
$list[$key]['vod_url'] = ff_data_url('vod',$list[$key]['vod_id'],$list[$key]['vod_cid'],$list[$key]['vod_name'],1,$list[$key]['vod_jumpurl']);
$list[$key]['vod_starsarr'] = admin_star_arr($list[$key]['vod_stars']);
}
//dump($rs->getLastSql());
//变量赋值并输出模板
$this->ppvod_play();
$this->assign($admin);
$this->assign('list',$list);
$this->assign('list_vod',F('_ppvod/listvod'));
if($admin['tid']){
$this->display('./Public/system/special_vod.html');
}else{
$this->display('./Public/system/vod_show.html');
}
}
// 添加编辑影片
public function add(){
$rs = D("Vod");
$vod_id = intval($_GET['id']);
if($vod_id){
$where['vod_id'] = $vod_id;
$array = $rs->where($where)->relation('Tag')->find();
foreach($array['Tag'] as $key=>$value){
$tag[$key] = $value['tag_name'];
}
foreach(explode('$$$',$array['vod_play']) as $key=>$val){
$play[array_search($val,C('play_player'))] = $val;
}
$array['vod_play_list'] = C('play_player');
$array['vod_server_list'] = C('play_server');
$array['vod_play'] = explode('$$$',$array['vod_play']);
$array['vod_server'] = explode('$$$',$array['vod_server']);
$array['vod_url'] = explode('$$$',$array['vod_url']);
$array['vod_starsarr'] = admin_star_arr($array['vod_stars']);
$array['vod_tags'] = implode(' ',$tag);
if (C('admin_time_edit')){
$array['checktime'] = 'checked';
}
$array['vod_tplname'] = '编辑';
$_SESSION['vod_jumpurl'] = $_SERVER['HTTP_REFERER'];
}else{
$array['vod_cid'] = cookie('vod_cid');
$array['vod_stars'] = 1;
$array['vod_status'] = 1;
$array['vod_hits'] = 0;
$array['vod_addtime'] = time();
$array['vod_continu'] = 0;
$array['vod_inputer'] = $_SESSION['admin_name'];
$array['vod_play_list'] = C('play_player');
$array['vod_server_list'] = C('play_server');
$array['vod_url']=array(0=>'');
$array['vod_starsarr'] = admin_star_arr(1);
$array['checktime'] = 'checked';
$array['vod_tplname'] = '添加';
}
$array['vod_language_list']=explode(',',C('play_language'));
$array['vod_zimu_list']=explode(',',C('play_zimu'));
$array['vod_area_list']=explode(',',C('play_area'));
$array['vod_year_list']=explode(',',C('play_year'));
$this->ppvod_play();
$this->assign($array);
$this->assign("jumpUrl",$_SESSION['vod_jumpurl']);
$this->assign('listvod',F('_ppvod/listvod'));
$this->display('./Public/system/vod_add.html');
}
// 数据库写入前置操作
public function _before_insert(){
//自动获取关键词tag
if(empty($_POST["vod_tags"]) && C('rand_tag')){
$_POST["vod_tags"] = ff_tag_auto($_POST["vod_name"],$_POST["vod_content"]);
}
//播放器组与地址组
$vod_jishu_arr=explode("{ff}",$_POST["jishu"]);
$vod_url=array();
$vod_play_arr=array("bdhd","qvod","tudou","yuku","qiyi","pvod","baofeng","sinahd","sinaz","sohu","souhu","ku6","qq","web9","gvod","swf","flv","pptv","pplive","letv","cntv","wasu","fengxing","ifeng","cool","xunlei","tudou2","xunlei2","media","real","pps","joy","m1905","yinyuetai","v163","ifeng","imgo","down1","down2","down3","down4","down5","down6","down7");
foreach($vod_play_arr as $v_p_a)
{
if(isset($_POST['vod_'.$v_p_a]))
{
$v_tmp=explode("{ff}",$_POST['vod_'.$v_p_a]);
foreach($v_tmp as $vt)
{
if(trim($vt)!="")
{
$vod_url[$v_p_a][]=$vt;
$vod_new_url[$v_p_a][]=$vt;
}
}
}
}
if(isset($_POST['old_url']) && isset($_POST['old_play']))
{
foreach($_POST['old_url'] as $kkk=>$old_url)
{
$ttt=array_unique(explode("\r\n",$old_url));
foreach($ttt as $tttttt)
{
$vod_url[$_POST['old_play'][$kkk]][]=$tttttt;
$vod_old_url[$_POST['old_play'][$kkk]][]=$tttttt;
}
}
//if($vod_url == $vod_old_url) {
// $this->error('集数相同 不需要更新');
//}
$eqCount = 0;
foreach($vod_new_url as $k => $v) {
if(count($v) <= count($vod_old_url[$k])) {
$eqCount++;
}
}
if($eqCount == count(array_keys($vod_new_url))) {
$this->error('集数相同 不需要更新');
}
}
$new_vod_url=array();
$new_vod_play=array();
foreach($vod_url as $k=>$v)
{
//去掉重复的
$real_v=array_unique($v);
$new_vod_url[]=implode("\r\n",$real_v);
$new_vod_play[]=$k;
}
$_POST["vod_url"] =implode("$$$",$new_vod_url);
$_POST["vod_play"] = implode("$$$",$new_vod_play);
if($_POST['vod_hits']==""){$_POST['vod_hits']=rand(100,600);}
if($_POST['vod_continu']==""){$_POST['vod_continu']=count($vod_url);}
}
// 新增数据
public function insert(){
$tag = D('Tag');
$rs = D("Vod");
$condition['vod_name'] = $_POST['vod_name'];
// 把查询条件传入查询方法
$ex=$rs->where($condition)->select();
if($ex){$_POST['vod_id']=$ex[0]['vod_id'];$_POST['old_url']=explode("$$$",$ex[0]['vod_url']);$_POST['old_play']=explode("$$$",$ex[0]['vod_play']);$this->update();exit;}
if($rs->create()){
//关联操作>>写入tag
if($_POST["vod_tags"]){
$rs->Tag = $tag->tag_array($_POST["vod_tags"],1);
$id = $rs->relation('Tag')->add();
}else{
$id = $rs->add();
}
$rs->$vod_id = $id;
}else{
$this->error($rs->getError());
}
}
// 数据库写入-后置操作
public function _after_insert(){
$rs = D("Vod");
$vod_id = $rs->$vod_id;
if($vod_id){
cookie('vod_cid',$vod_id);
$this->_after_add_update($vod_id);
$this->assign("jumpUrl",'?s=Admin-Vod-Add');
$this->success('视频添加成功,继续添加新视频!');
}else{
$this->error('视频添加失败。');
}
}
// 更新数据
public function update(){
$this->_before_insert();
$tag = D('Tag');$rs = D("Vod");
if($rs->create()){
/*只更新部分字段*/
$updateFields = array(
'vod_name' => $_POST['vod_name'],
'vod_title' => $_POST['vod_title'],
'vod_continu' => $_POST['vod_continu'],
'vod_url' => $_POST['vod_url'],
'vod_play' => $_POST['vod_play'],
'vod_addtime' => time()
);
if(false !== $rs->where(array('vod_id' => $_POST['vod_id']))->save($updateFields)){
//手动更新TAG
if($_POST["vod_tags"]){
$tag->tag_update($_POST["vod_id"],$_POST["vod_tags"],1);
}
//后置操作条件
$rs->$vod_id = $_POST["vod_id"];
$this->_after_update();
}else{
$this->error("修改影片信息失败!");
}
}else{
$this->error($rs->getError());
}
}
// 后置操作
public function _after_update(){
$rs = D("Vod");
$vod_id = $rs->$vod_id;
if($vod_id){
$this->_after_add_update($vod_id);
$this->assign("jumpUrl",$_SESSION['vod_jumpurl']);
$this->success('视频更新成功!');
}else{
$this->error('视频更新失败。');
}
}
//操作完毕后
public function _after_add_update($vod_id){
//删除静态缓存
if(C('html_cache_on')){
$id = md5($vod_id).C('html_file_suffix');
@unlink('./Html/Vod_read/'.$vod_id);
@unlink('./Html/Vod_play/'.$vod_id);
}
//生成网页
if(C('url_html')){
echo'<iframe scrolling="no" src="?s=Admin-Create-vodid-id-'.$vod_id.'" frameborder="0" style="display:none"></iframe>';
}
}
// 删除影片
public function del(){
$this->delfile($_GET['id']);
redirect($_SESSION['vod_jumpurl']);
}
// 删除影片all
public function delall(){
if(empty($_POST['ids'])){
$this->error('请选择需要删除的影片!');
}
$array = $_POST['ids'];
foreach($array as $val){
$this->delfile($val);
}
redirect($_SESSION['vod_jumpurl']);
}
// 删除静态文件与图片
public function delfile($id){
$where = array();
//删除影片观看记录
//$rs = D("View");
//$where['did'] = $id;
//$rs->where($where)->delete();
//删除专题收录
$rs = D("Topic");
$where['topic_sid'] = 1;
$where['topic_did'] = $id;
$rs->where($where)->delete();
unset($where);
//删除影片评论
$rs = D("Cm");
$where['cm_cid'] = $id;
$where['cm_sid'] = 1;
$rs->where($where)->delete();
unset($where);
//删除影片TAG
$rs = D("Tag");
$where['tag_id'] = $id;
$where['tag_sid'] = 1;
$rs->where($where)->delete();
unset($where);
//删除静态文件与图片
$rs = D("Vod");
$where['vod_id'] = $id;
$array = $rs->field('vod_id,vod_cid,vod_pic,vod_name')->where($where)->find();
@unlink(ff_img_url($arr['vod_pic']));
if(C('url_html')>0){
@unlink(ff_data_url('vod',$array['vod_id'],$array['vod_cid'],$array['vod_name'],1));
@unlink(ff_play_url($array['vod_id'],0,1,$array['vod_cid'],$array['vod_name']));
}
unset($where);
//删除影片ID
$where['vod_id'] = $id;
$rs->where($where)->delete();
unset($where);
}
// 批量生成数据
public function create(){
echo'<iframe scrolling="no" src="?s=Admin-Create-vodid-id-'.implode(',',$_POST['ids']).'" frameborder="0" style="display:none"></iframe>';
$this->assign("jumpUrl",$_SESSION['vod_jumpurl']);
$this->success('批量生成数据成功!');
}
// 批量转移影片
public function pestcid(){
if(empty($_POST['ids'])){
$this->error('请选择需要转移的影片!');
}
$cid = intval($_POST['pestcid']);
if (getlistson($cid)) {
$rs = D("Vod");
$data['vod_cid'] = $cid;
$where['vod_id'] = array('in',$_POST['ids']);
$rs->where($where)->save($data);
redirect($_SESSION['vod_jumpurl']);
}else{
$this->error('请选择当前大类下面的子分类!');
}
}
// 设置状态
public function status(){
$where['vod_id'] = $_GET['id'];
$rs = D("Vod");
if($_GET['value']){
$rs->where($where)->setField('vod_status',1);
}else{
$rs->where($where)->setField('vod_status',0);
}
redirect($_SESSION['vod_jumpurl']);
}
// Ajax设置星级
public function ajaxstars(){
$where['vod_id'] = $_GET['id'];
$data['vod_stars'] = intval($_GET['stars']);
$rs = D("Vod");
$rs->where($where)->save($data);
echo('ok');
}
// Ajax设置连载
public function ajaxcontinu(){
$where['vod_id'] = $_GET['id'];
$data['vod_continu'] = trim($_GET['continu']);
$rs = D("Vod");
$rs->where($where)->save($data);
echo('ok');
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/ApiAction.class.php | PHP | asf20 | 14,145 |
<?php
/**
* Cat类库
* 用于类型分类的独立类库
* created by QQ:182377860
*/
class CatAction extends BaseAction
{
/*
* 添加分类
*/
public function add()
{
$mcid = intval($_GET['mcid']);
$rs = M('Mcat');
$list = array();
if($mcid)
{
$where = array();
$where['m_cid'] = $mcid;
$list = $rs->where($where)->find();
$list['tpltitle'] = '编辑';
}
else
{
$list['m_cid'] = 0;
$list['m_list_id'] = isset($_GET['id']) ? intval($_GET['id']) : 0;
$list['m_order'] = $rs->max('m_order')+1;
$list['m_name'] = '';
$list['tpltitle'] = '添加';
}
$this->assign($list);
$this->assign('list_tree',F('_ppvod/listtree'));
$this->display('./Public/system/cat_add.html');
}
/*
* 管理类型
*/
public function show()
{
$condition = array(
'list_pid' => 0,
'list_sid' => 1
);
$tree = M('List')->where($condition)->field("list_id,list_name,list_oid")->findAll();
foreach ($tree as $k=>$v){
$tree[$k]['son'] = D('Mcat')->list_cat($v['list_id']);
$tree[$k]['total'] = $tree[$k]['son'] == null ? 0 : count($tree[$k]['son']);
}
$this->assign('tree', $tree);
$this->display('./Public/system/cat_show.html');
}
public function _before_insert()
{
if($_POST['m_list_id'] == 0)
{
$this->error('请选择分类');
}
}
public function insert()
{
$rs = D('Mcat');
if($rs->create())
{
//表单验证通过
if($rs->add()) {
$this->assign("jumpUrl",'?s=Admin-Cat-Show');
$this->success('添加类型分类成功!');
}else {
$this->error('添加类型分类错误');
}
}
else
{
$this->error($rs->getError());
}
}
// 删除数据
public function del()
{
$mcid = intval($_GET['mcid']);
if(M('Mcat')->where("m_cid = {$mcid}")->delete()){
$this->success('删除成功');
}else{
$this->error('删除失败');
}
}
public function _before_update()
{
$where = array(
'm_name' => trim($_POST['m_name'])
);
$result = M('Mcat')->where($where)->find();
if($result){
if($result['m_cid'] != intval($_POST['m_cid'])){
$this->error('名称已经存在,请重新填写!');
}
}
}
/*
* 更新
*/
public function update()
{
$rs = D('Mcat');
if($rs->create()){
$rs->save();
$this->success('修改成功');
}else{
$this->error($rs->getError());
}
}
/*
* 批量更新
*/
public function Updateall()
{
if(empty($_POST['ids'])){
$this->error('请选择需要编辑的项目!');
}
$_data = $_POST;
foreach ($_data['ids'] as $val) {
$data['m_order'] = $_data['m_order'][$val];
$data['m_name'] = $_data['m_name'][$val];
M('Mcat')->where("m_cid = {$val}")->save($data);
}
$this->success('批量修改成功!');
}
/*
* 批量删除
*/
public function Delall()
{
if(empty($_POST['ids'])){
$this->error('请选择需要删除的栏目!');
}
$ids = implode(',', $_POST['ids']);
$condition = array(
'm_cid' => array('in', $ids)
);
M('Mcat')->where($condition)->delete();
$this->success('批量删除类型成功!');
}
}
/* End of File CatAction.class.php */
/* Create by 182377860@qq.com */
| 0321hy | trunk/Lib/Lib/Action/Admin/CatAction.class.php | PHP | asf20 | 3,311 |
<?php
class LinkAction extends BaseAction{
// 显示友情链接
public function show(){
$rs = D("Link");
$link = $rs->order('link_type asc,link_order asc')->select();
F('_ppvod/link',$link);
$list = $rs->order('link_order asc')->select();
$this->assign('list_link',$list);
$this->display('./Public/system/link_show.html');
}
// 添加友情链接
public function add(){
$id = intval($_GET['id']);
$rs = D("Link");
if ($id) {
$where['link_id'] = $id;
$list = $rs->where($where)->find();
$list['tpltitle'] = '编辑';
}else{
$list['link_order'] = $rs->max('link_order')+1;
$list['tpltitle'] = '添加';
}
$this->assign($list);
$this->display('./Public/system/link_add.html');
}
// 添加友情链接并写入数据库
public function insert(){
$rs = D("Link");
if ($rs->create()) {
if ( false !== $rs->add() ) {
redirect('?s=Admin-Link-Show');
}else{
$this->error('添加友情链接失败!');
}
}else{
$this->error($rs->getError());
}
}
// 更新友情链接
public function update(){
$rs = D("Link");
if ($rs->create()) {
$list = $rs->save();
if ($list !== false) {
redirect('?s=Admin-Link-Show');
}else{
$this->error("更新友情链接失败!");
}
}else{
$this->error($rs->getError());
}
}
// 批量更新
public function updateall(){
$array = $_POST;
$rs = D("Link");
foreach($array['link_id'] as $value){
$data['link_id'] = $array['link_id'][$value];
$data['link_name'] = trim($array['link_name'][$value]);
$data['link_url'] = trim($array['link_url'][$value]);
$data['link_logo'] = trim($array['link_logo'][$value]);
$data['link_order'] = $array['link_order'][$value];
$data['link_type'] = $array['link_type'][$value];
if(empty($data['link_name'])){
$rs->where('link_id = '.intval($data['link_id']))->delete();
}else{
$rs->save($data);
}
}
$this->success('友情链接数据更新成功!');
}
// 删除友情链接
public function del(){
$rs = D("Link");
$where['link_id'] = $_GET['id'];
$rs->where($where)->delete();
redirect('?s=Admin-Link-Show');
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/LinkAction.class.php | PHP | asf20 | 2,291 |
<?php
class NavAction extends BaseAction{
public function show(){
$array = F('_nav/list');
$this->assign('array_nav',$array);
$this->display('./Public/system/nav.html');
}
public function update(){
$content = trim($_POST["content"]);
if(empty($content)){
$this->error('自定义菜单不能为空!');
}
foreach(explode(chr(13),$content) as $value){
list($key,$val) = explode('|',trim($value));
if(!empty($val)){
$arrlist[trim($key)] = trim($val);
}
}
F('_nav/list',$arrlist);
$this->assign("jumpUrl",C('cms_admin').'?s=Admin-Nav-Show-reload-1');
$this->success('自定义菜单编辑成功!');
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/NavAction.class.php | PHP | asf20 | 687 |
<?php
class AdminAction extends BaseAction{
// 用户管理
public function show(){
$rs = D("Admin");
$list = $rs->order('admin_logintime desc')->select();
$this->assign('url_html_suffix',C('url_html_suffix'));
$this->assign('html_file_suffix',C('html_file_suffix'));
$this->assign('list',$list);
$this->display('./Public/system/admin_show.html');
}
// 用户添加
public function add(){
$array = array();
$where['admin_id'] = $_GET['id'];
$rs = D("Admin");
$array = $rs->where($where)->find();
$type = explode(',',$array['admin_ok']);
$this->assign('admin',$type);
$this->assign($array);
$this->display('./Public/system/admin_add.html');
}
//处理权限入库
public function _before_insert(){
$ok = $_POST['ids'];
for($i=0;$i<20;$i++){
if($ok[$i]){
$rs[$i]=$ok[$i];
}else{
$rs[$i]=0;
}
}
$_POST['admin_ok'] = implode(',',$rs);
}
// 写入数据
public function insert(){
$rs = D("Admin");
if($rs->create()){
if(false !== $rs->add()){
$this->assign("jumpUrl",'?s=Admin-Admin-Show');
$this->success('添加后台管理员成功!');
}else{
$this->error('添加后台管理员失败');
}
}else{
$this->error($rs->getError());
}
}
// 更新数据
public function update(){
$this->_before_insert();
$rs = D("Admin");
if ($rs->create()) {
if(false !== $rs->save()){
$this->assign("jumpUrl",'?s=Admin-Admin-Show');
$this->success('更新管理员信息成功!');
}else{
$this->error("更新管理员信息失败!");
}
}else{
$this->error($rs->getError());
}
}
// 删除用户
public function del(){
$rs = D("Admin");
$rs->where('admin_id='.$_GET['id'])->delete();
$this->success('删除后台管理员成功!');
}
// 批量删除
public function delall(){
$where['admin_id'] = array('in',implode(',',$_POST['ids']));
$rs = D("Admin");
$rs->where($where)->delete();
$this->success('批量删除后台管理员成功!');
}
// 配置信息
public function config(){
$tpl = TMPL_PATH.'*';
$list = glob($tpl);
foreach ($list as $i=>$file){
$dir[$i]['filename'] = basename($file);
}
$this->assign('dir',$dir);
$config = require './Runtime/Conf/config.php';
$this->assign($config);
$this->ppvod_list();//更新导航菜单
$this->display('./Public/system/admin_conf.html');
}
// 配置信息保存
public function configsave(){
$config = $_POST["config"];
$config['site_tongji'] = stripslashes($config['site_tongji']);
$config['play_collect_content'] = stripslashes($config['play_collect_content']);
$config['admin_time_edit'] = (bool) $config['admin_time_edit'];
$config['url_voddata'] = trim($config['url_voddata']);
$config['url_newsdata'] = trim($config['url_newsdata']);
$config['upload_thumb'] = (bool) $config['upload_thumb'];
$config['upload_water'] = (bool) $config['upload_water'];
$config['upload_http'] = (bool) $config['upload_http'];
$config['upload_ftp'] = (bool) $config['upload_ftp'];
$config['play_collect'] = (bool) $config['play_collect'];
$config['play_second'] = intval($config['play_second']);
$config['tmpl_cache_on'] = (bool) $config['tmpl_cache_on'];
$config['html_cache_on'] = (bool) $config['html_cache_on'];
$config['user_gbcm'] = (bool) $config['user_gbcm'];
//播放地址前缀
foreach(explode(chr(13),trim($config["play_server"])) as $v){
list($key,$val) = explode('$$$',trim($v));
$arrserver[trim($key)] = trim($val);
}
$config["play_server"] = $arrserver;
//采集伪原创内容
foreach(explode(chr(13),trim($config["play_collect_content"])) as $v){
$arrcollect[] = trim($v);
}
$config["play_collect_content"] = $arrcollect;
//静态缓存
$config['html_cache_time'] = $config['html_cache_time']*3600;//其它页缓存
if($config['html_cache_index']>0){
$config['_htmls_']['home:index:index'] = array('{:action}',$config['html_cache_index']*3600);
}else{
$config['_htmls_']['home:index:index'] = NULL;
}
if($config['html_cache_list']>0){
$config['_htmls_']['home:vod:show'] = array('{:module}_{:action}/{$_SERVER.REQUEST_URI|md5}',$config['html_cache_list']*3600);
$config['_htmls_']['home:news:show'] = array('{:module}_{:action}/{$_SERVER.REQUEST_URI|md5}',$config['html_cache_list']*3600);
}else{
$config['_htmls_']['home:vod:show'] = NULL;
$config['_htmls_']['home:news:show'] = NULL;
}
if($config['html_cache_content']>0){
$config['_htmls_']['home:vod:read'] = array('{:module}_{:action}/{id|md5}',$config['html_cache_content']*3600);
$config['_htmls_']['home:news:read'] = array('{:module}_{:action}/{$_SERVER.REQUEST_URI|md5}',$config['html_cache_content']*3600);
}else{
$config['_htmls_']['home:vod:read'] = NULL;
$config['_htmls_']['home:news:read'] = NULL;
}
if($config['html_cache_play']>0){
$config['_htmls_']['home:vod:play'] = array('{:module}_{:action}/{$_SERVER.REQUEST_URI|md5}',$config['html_cache_play']*3600);
}else{
$config['_htmls_']['home:vod:play'] = NULL;
}
if($config['html_cache_ajax']>0){
$config['_htmls_']['home:my:show'] = array('{:module}_{:action}/{$_SERVER.REQUEST_URI|md5}',$config['html_cache_ajax']*3600);
}else{
$config['_htmls_']['home:my:show'] = NULL;
}
if(0==$config['url_html']){
@unlink('./index'.C('html_file_suffix'));//动态模式则删除首页静态文件
}else{
$config['html_home_suffix'] = $config['html_file_suffix'];//将静态后缀写入配置供前台生成的路径的时候调用
}
$config_old = require './Runtime/Conf/config.php';
$config_new = array_merge($config_old,$config);
arr2file('./Runtime/Conf/config.php',$config_new);
@unlink('./Runtime/~app.php');
//
$pp_play.= 'var ff_root="'.$config['site_path'].'";';
$pp_play.= 'var ff_width='.$config['play_width'].';';
$pp_play.= 'var ff_height='.$config['play_height'].';';
$pp_play.= 'var ff_showlist='.$config['play_show'].';';
$pp_play.= 'var ff_second='.intval($config['play_second']).';';
$pp_play.= 'var ff_qvod="'.$config['play_qvod'].'";';
$pp_play.= 'var ff_gvod="'.$config['play_gvod'].'";';
$pp_play.= 'var ff_pvod="'.$config['play_pvod'].'";';
$pp_play.= 'var ff_web9="'.$config['play_web9'].'";';
$pp_play.= 'var ff_bdhd="'.$config['play_bdhd'].'";';
$pp_play.= 'var ff_baiduhd="'.$config['play_bdhd'].'";';
$pp_play.= 'var ff_pplive="";';
$pp_play.= 'var ff_buffer="'.$config['play_playad'].'";';
foreach(C('play_server') as $key=>$value){
$pp_play.= 'var ff_'.$key.'="'.$value.'";';
}
foreach(C('play_player') as $key=>$value){
$pp_play.= 'var play_'.$key.'="'.$value[1].'";';
}
write_file('./Runtime/Player/play.js',$pp_play);
admin_ff_hot_key(C('site_hot'));
$this->success('恭喜您,配置信息更新成功!');
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/AdminAction.class.php | PHP | asf20 | 7,077 |
<?php
class CreateHtmliuhuhg2123hu1ws12Action extends Based1923d0j1i29szsakhodsaAction{
//构造函数
public function _initialize(){
parent::_initialize();
$this->assign($this->Lable_Style());
$this->assign("waitSecond",C('url_time'));
}
//组合需要生成的资讯列表并缓存
public function newslist(){
$this->list_cache_array(2);
}
//生成资讯列表从缓存任务列表
public function newslist_create(){
$this->list_create_array(2);
}
//组合需要生成的视频列表并缓存
public function vodlist(){
$this->list_cache_array(1);
}
//生成视频列表从缓存任务列表
public function vodlist_create(){
$this->list_create_array(1);
}
//缓存视频/资讯列表列表路径为数组
public function list_cache_array($sid=1){
$jump = intval($_REQUEST['jump']);
$this->check(C('url_html_list'),getsidname($sid).'列表页','?s=Admin-Create-Index-jump-'.$jump);
$array_list = F('_ppvod/list');
$array_listids = explode(',',$_REQUEST['ids_list_'.$sid]);
$k = 0;
foreach($array_listids as $key=>$value){
$list = list_search($array_list,'list_id='.$value);
if($list[0]["list_limit"]){
$totalpages = ceil(getcount($value)/$list[0]["list_limit"]);
}else{
$totalpages = 1;
}
for($page = 1; $page <= $totalpages; $page++){
$array[$k]['id'] = $value;
$array[$k]['page'] = $page;
$k++;
}
}
F('_create/list',$array);
if($sid == 1){
$this->vodlist_create();
}else{
$this->newslist_create();
}
}
//生成视频/资讯列表列表从缓存数组(分页生成)
public function list_create_array($sid){
$List = F('_ppvod/list');
$Url = F('_create/list');
$key = intval($_REQUEST['key']);
$jump = intval($_REQUEST['jump']);
if($sid==1){
$nextcreate = '?s=Admin-Create-Vodlist_create-jump-'.$jump.'-key-'.$key;
$sidname = '视频';
}else{
$nextcreate = '?s=Admin-Create-Newslist_create-jump-'.$jump.'-key-'.$key;
$sidname = '资讯';
}
//断点生成(写入缓存)
F('_create/nextcreate',$nextcreate);
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体">';
echo'<li>总共需要生成<font color=blue>'.count($Url).'</font>个'.$sidname.'列表页,每页生成'.C('url_number').'个。</li>';
for($i=1;$i<=C('url_number');$i++){
if(!$Url[$key]){
break;
}
//变量赋值
C('jumpurl',ff_list_url(getsidname($sid),array('id'=>$Url[$key]['id'],'p'=>'{!page!}'),9999));
C('currentpage',$Url[$key]['page']);
$channel = list_search($List,'list_id='.$Url[$key]['id']);
if($sid == 1){
$channel = $this->Lable_Vod_List(array('id'=>$Url[$key]['id'],'page'=>$Url[$key]['page'],'order'=>'addtime'),$channel[0]);
}else{
$channel = $this->Lable_News_List(array('id'=>$Url[$key]['id'],'page'=>$Url[$key]['page'],'order'=>'addtime'),$channel[0]);
}
$this->assign($channel);
//目录路径并生成
$listdir = str_replace('{!page!}',$Url[$key]['page'],ff_list_url_dir(getsidname($sid),$Url[$key]['id'],$Url[$key]['page']));
$this->buildHtml($listdir,'./','Home:'.$channel['list_skin']);
//预览路径
$showurl = C('sitepath').$listdir.C('html_file_suffix');
echo'<li>第<font color=red>'.($key+1).'</font>个生成完毕 <a href="'.$showurl.'" target="_blank">'.$showurl.'</a></li>';
ob_flush();flush();
$key++;
}
echo'</ul>';
if($key < count($Url)){
if($sid==1){
$nextcreate = '?s=Admin-Create-Vodlist_create-jump-'.$jump.'-key-'.$key;
}else{
$nextcreate = '?s=Admin-Create-Newslist_create-jump-'.$jump.'-key-'.$key;
}
$this->jump($nextcreate,'让服务器休息一会,生成任务等待中...');
}
F('_create/list',NULL);
if($jump){
$this->jump('?s=Admin-Create-Index-jump-'.$jump,'列表页已经全部生成,下次将生成网站首页。');
}
F('_create/nextcreate',NULL);
$this->jump('?s=Admin-Create-Show','恭喜您,列表页已经全部生成!');
}
//读取资讯内容按分类
public function newsclass(){
$jump = intval($_REQUEST['jump']);
$ids = trim($_REQUEST['ids_2']);
$page = !empty($_GET['page']) ? intval($_GET['page']) : 1;
//检测是否需要生成
$this->check(C('url_html'),'资讯内容页','?s=Admin-Create-Newslist-ids_2-'.$ids.'-jump-'.$jump);
//断点生成(写入缓存)
F('_create/nextcreate','?s=Admin-Create-Vodclass-ids_2-'.$ids.'-jump-'.$jump.'-page-'.$page);
//查询数据开始
$rs = D("News");
$where['news_status'] = array('eq',1);
$where['news_cid'] = array('in',$ids);
$count = $rs->where($where)->count('news_id');
$totalpages = ceil($count/C('url_number'));
$array = $rs->where($where)->order('news_addtime desc')->limit(C('url_number'))->page($page)->relation('Tag')->select();
if (empty($array)) {
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->error('当前分类没有数据,暂不需要生成!');
}
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体">';
echo'<li>总共需要生成<font color=blue>'.$count.'</font>个资讯内容页,需要分<font color=blue>'.$totalpages.'</font>次来执行,正在执行第<font color=red>'.$page.'</font>次</li>';
foreach($array as $key=>$value){
$this->news_read_create($value);
}
echo'</ul>';
//组合回跳URL路径与执行跳转
$jumpurl = '?s=Admin-Create-Show';
if($page < $totalpages){
$jumpurl = '?s=Admin-Create-Newsclass-ids_2-'.$ids.'-jump-'.$jump.'-page-'.($page+1);
}else{
if($jump){
$jumpurl = '?s=Admin-Create-Newslist-ids_list_2-'.$ids.'-jump-'.$jump;
}
}
if($page < $totalpages){
$this->jump($jumpurl,'稍等一会,准备生成下一次资讯内容页...');
}
F('_create/nextcreate',NULL);
$this->jump($jumpurl,'恭喜您,资讯内容页全部生成完毕。');
}
//读取资讯内容按时间
public function newsday(){
$jump = intval($_REQUEST['jump']);
$this->check(C('url_html'),'资讯内容页');
//查询数据开始
$rs = D("News");
$mday = intval($_REQUEST['mday_2']);
$min = intval($_REQUEST['min']);
$where['news_status'] = array('eq',1);
$where['news_cid'] = array('gt',0);
if($min){//生成多少分钟内的影片
$where['news_addtime'] = array('gt',time()-$min*60);
}else{
$where['news_addtime'] = array('gt',getxtime($mday));
}
//
$count = $rs->where($where)->count('news_id');
$totalpages = ceil($count/C('url_number'));
$page = !empty($_GET['page'])?intval($_GET['page']):1;
$array = $rs->where($where)->order('news_addtime desc')->limit(C('url_number'))->page($page)->relation('Tag')->select();
if (empty($array )) {
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->error('今日没有数据更新,暂不需要生成!');
}
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体">';
echo'<li>总共需要生成<font color=blue>'.$count.'</font>个资讯内容页,需要分<font color=blue>'.$totalpages.'</font>次来执行,正在执行第<font color=red>'.$page.'</font>次</li>';
foreach($array as $key=>$value){
$this->news_read_create($value);
}
echo'</ul>';
//组合回跳URL路径与执行跳转
$jumpurl = '?s=Admin-Create-Show';
if ($page < $totalpages) {
$jumpurl = '?s=Admin-Create-Newsday-jump-'.$jump.'-mday_2-'.$mday.'-min-'.$mid.'-page-'.($page+1);
}else{
if($jump){
$listarr = F('_ppvod/list');
foreach($listarr as $key=>$value){
$keynew = $value['list_sid'];
$list[$keynew][$key] = $value['list_id'];
}
$ids = implode(',',$list[1]);
$jumpurl = '?s=Admin-Create-Newslist-jump-1-ids_list_2-'.$ids;
}
}
if ($page < $totalpages) {
$this->jump($jumpurl,'第('.$page.')页已经生成完毕,正在准备下一个。');
}
F('_create/nextcreate',NULL);
$this->jump($jumpurl,'恭喜您,生成完毕。');
}
//读取资讯内容按ID
public function newsid(){
$where = array();
$rs = D("News");
$where['news_id'] = array('in',$_REQUEST["id"]);
$where['news_status'] = 1;
$where['news_cid'] = array('gt',0);
$array = $rs->where($where)->relation('Tag')->select();
foreach($array as $value){
$this->news_read_create($value);
}
}
//生成资讯内容页
public function news_read_create($array){
$arrays = $this->Lable_News_Read($array);
$this->assign($arrays['show']);
$this->assign($arrays['read']);
$newsdir = ff_data_url_dir('news',$arrays['read']['news_id'],$arrays['read']['news_cid'],$arrays['read']['news_name'],1);
$this->buildHtml($newsdir,'./',$arrays['read']['news_skin']);
$newsurl = C('site_path').$newsdir.C('html_file_suffix');
echo '<li>'.$arrays['read']['news_id'].' <a href="'.$newsurl.'" target="_blank">'.$newsurl.'</a> 生成完毕</li>';
ob_flush();flush();
}
//读取视频内容按分类
public function vodclass(){
$jump = intval($_REQUEST['jump']);
$ids = trim($_REQUEST['ids_1']);
$page = !empty($_GET['page']) ? intval($_GET['page']) : 1;
$this->check(C('url_html'),'视频内容页','?s=Admin-Create-Vodlist-ids_1-'.$ids.'-jump-'.$jump);
//断点生成(写入缓存)
F('_create/nextcreate','?s=Admin-Create-Vodclass-ids_1-'.$ids.'-jump-'.$jump.'-page-'.$page);
$rs = D("Vod");
$where['vod_status'] = array('eq',1);
$where['vod_cid'] = array('in',$ids);
$count = $rs->where($where)->count('vod_id');
$totalpages = ceil($count/C('url_number'));
$array = $rs->where($where)->order('vod_addtime desc')->limit(C('url_number'))->page($page)->relation('Tag')->select();
if (empty($array)) {
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->error('当前分类没有数据,暂不需要生成!');
}
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体"><li>总共需要生成<font color=blue>'.$count.'</font>个视频内容页,需要分<font color=blue>'.$totalpages.'</font>次来执行,正在执行第<font color=blue>'.$page.'</font>次</li>';
foreach($array as $key=>$value){
$this->vod_read_create($value);
}
echo'</ul>';
//组合回跳URL路径与执行跳转
$jumpurl = '?s=Admin-Create-Show';
if($page < $totalpages){
$jumpurl = '?s=Admin-Create-Vodclass-ids_1-'.$ids.'-jump-'.$jump.'-page-'.($page+1);
}else{
if($jump){
$jumpurl = '?s=Admin-Create-Vodlist-ids_list_1-'.$ids.'-jump-'.$jump;
}
}
if($page < $totalpages){
$this->jump($jumpurl,'稍等一会,准备生成下一次视频内容页...');
}
F('_create/nextcreate',NULL);
$this->jump($jumpurl,'恭喜您,视频内容页全部生成完毕。');
}
//读取视频内容按时间
public function vodday(){
$jump = intval($_REQUEST['jump']);
$this->check(C('url_html'),'视频内容页');
$rs = D("Vod");
$mday = intval($_REQUEST['mday_1']);
$min = intval($_REQUEST['min']);
$where['vod_status'] = array('eq',1);
$where['vod_cid'] = array('gt',0);
//
if($min){//生成多少分钟内的影片
$where['vod_addtime'] = array('gt',time()-$min*60);
}else{
$where['vod_addtime'] = array('gt',getxtime($mday));
}
//
$count = $rs->where($where)->count('vod_id');
$totalpages = ceil($count/C('url_number'));
$page = !empty($_GET['page'])?intval($_GET['page']):1;
$array = $rs->where($where)->order('vod_addtime desc')->limit(C('url_number'))->page($page)->relation('Tag')->select();
if (empty($array )) {
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->error('今日没有数据更新,暂不需要生成!');
}
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体"><li>总共需要生成<font color=blue>'.$count.'</font>个视频内容页,需要分<font color=blue>'.$totalpages.'</font>次来执行,正在执行第<font color=blue>'.$page.'</font>次</li>';
foreach($array as $key=>$value){
$this->vod_read_create($value);
}
echo'</ul>';
if ($page < $totalpages) {
$jumpurl = '?s=Admin-Create-Vodday-jump-'.$jump.'-mday_1-'.$mday.'-min-'.$mid.'-page-'.($page+1);
}else{
if($jump){
$listarr = F('_ppvod/list');
foreach($listarr as $key=>$value){
$keynew = $value['list_sid'];
$list[$keynew][$key] = $value['list_id'];
}
$ids = implode(',',$list[1]);
$jumpurl = '?s=Admin-Create-Vodlist-jump-1-ids_list_1-'.$ids;
}else{
$jumpurl = '?s=Admin-Create-Show';
}
}
if ($page < $totalpages) {
$this->jump($jumpurl,'第('.$page.')页已经生成完毕,正在准备下一个。');
}
F('_create/nextcreate',NULL);
$this->jump($jumpurl,'恭喜您,生成完毕。');
}
//读取影片内容按ID
public function vodid(){
$where = array();
$rs = D("Vod");
$where['vod_id'] = array('in',$_REQUEST["id"]);
$where['vod_cid'] = array('gt',0);
$where['vod_status'] = 1;
$array = $rs->where($where)->relation('Tag')->select();
foreach($array as $value){
$this->vod_read_create($value);
}
}
//生成影视内容页
public function vod_read_create($array){
$arrays = $this->Lable_Vod_Read($array);
$this->assign($arrays['show']);
$this->assign($arrays['read']);
//生成内容页
$videodir = ff_data_url_dir('vod',$arrays['read']['vod_id'],$arrays['read']['vod_cid'],$arrays['read']['vod_name'],1);
$this->buildHtml($videodir,'./',$arrays['read']['vod_skin']);
echo('<li><a href="'.C('site_path').$videodir.C('html_file_suffix').'" target="_blank">'.$arrays['read']['vod_id'].'</a> detail ok</li>');
//生成播放页
if(C('url_html')){
$this->vod_play_create($arrays);
}
ob_flush();
flush();
}
//生成播放页
public function vod_play_create($arrays){
//合集在一个页面
if(C('url_html_play')==1){
$this->assign($arrays['show']);
$arrays['read'] = $this->Lable_Vod_Play($arrays['read'],array('id'=>$arrays['read']['vod_id'],'sid'=>0,'pid'=>1));
$this->assign($arrays['read']);
$playdir = ff_play_url_dir($arrays['read']['vod_id'],0,1,$arrays['read']['vod_cid'],$arrays['read']['vod_name']);
$this->buildHtml($playdir,'./',$arrays['read']['vod_skin_play']);
echo('<li>'.$arrays['read']['vod_id'].' play ok</li>');
}elseif(C('url_html_play')==2){
echo('<li>'.$arrays['read']['vod_id'].' play ');
//生成播放地址js(只需要一次)
$player_dir = ff_play_url_dir($arrays['read']['vod_id'],0,1,$arrays['read']['vod_cid'],$arrays['read']['vod_name']);
write_file('./'.$player_dir.'.js',$arrays['read']['vod_player']);
//播放页模板通用变量解析
$this->assign($arrays['show']);
//第一个分集生成完后
foreach($arrays['read']['vod_playlist'] as $sid=>$son){
$arr_sid = explode('-',$sid);
$arr_play = array();
foreach($son["son"] as $pid=>$value){
//路径替换与生成
$player_dir_ji = preg_replace('/play-([0-9]+)-([0-9]+)-([0-9]+)/i','play-$1-'.$arr_sid[1].'-'.($pid+1).'',$player_dir);
$this->assign($this->Lable_Vod_Play($arrays['read'],array('id'=>$arrays['read']['vod_id'],'sid'=>$arr_sid[1],'pid'=>$pid+1),true));
$this->buildHtml($player_dir_ji,'./',$arrays['read']['vod_skin_play']);
//echo($arr_sid[1].'-'.($pid+1).' ');
}
echo('ok </li>');
}
}
}
//一键生成全站地图
public function maps(){
$this->check(C('url_html'),'网站地图');
$this->google(true);
$this->baidu(true);
$this->rss(true);
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->success('恭喜您,所有地图生成完毕!');
}
//生成Baidu地图
public function baidu($id){
$baiduall = !empty($_REQUEST['baiduall'])?intval($_REQUEST['baiduall']):10000;
$baidu = !empty($_REQUEST['baidu'])?intval($_REQUEST['baidu']):2000;
$page = ceil(intval($baiduall)/intval($baidu));
for($i=1;$i<=$page;$i++){
$this->map_create('baidu',$baidu,$i);
}
if (empty($id)) {
$this->assign("waitSecond",5);
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->success('Baidu Sitemap地图生成成功!<br />请通过<a href="http://sitemap.baidu.com" target="_blank">百度站长平台</a>提交!');
}
}
//生成Google地图
public function google($id){
$googleall = !empty($_REQUEST['googleall'])?intval($_REQUEST['googleall']):5000;
$google = !empty($_REQUEST['google'])?intval($_REQUEST['google']):1000;
$page = ceil(intval($googleall)/intval($google));
for($i=1;$i<=$page;$i++){
$this->map_create('google',$google,$i);
}
if (empty($id)) {
$this->assign("waitSecond",5);
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->success('Google Sitemap地图生成成功!<br />请通过<a href="http://www.google.com/webmasters/tools" target="_blank">谷歌站长工具</a>提交!');
}
}
//生成Rss订阅
public function rss($id){
$rss = !empty($_REQUEST['rss'])?intval($_REQUEST['rss']):50;
$this->map_create('rss',$rss,1);
if (empty($id)) {
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->success('Rss订阅文件生成成功!');
}
}
//生成地图共用模块
public function map_create($mapname,$limit,$page){
$suffix = C('html_file_suffix');
$listmap = $this->Lable_Maps($mapname,$limit,$page);
if($listmap){
$this->assign('list_map',$listmap);
C('html_file_suffix','.xml');
if ($page == 1){
$this->buildHtml($mapname,'./'.C('url_map'),'./Public/maps/'.$mapname.'.html');
}else{
$this->buildHtml($mapname.'-'.$page,'./'.C('url_map'),'./Public/maps/'.$mapname.'.html');
}
C('html_file_suffix',$suffix);
}
}
//生成网站首页
public function index(){
$jump = intval($_GET['jump']);
$this->check(C('url_html'),'网站首页');
F('_create/nextcreate',NULL);
$this->assign($this->Lable_Index());
$this->buildHtml("index",'./','Home:pp_index');
if ($jump) {
$this->assign("jumpUrl",'?s=Admin-Create-Mytpl-jump-'.$jump);
$this->success('首页生成完毕,准备生成自定义模板!');
}else{
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->success('首页生成完毕。');
}
}
//生成自定义模板
public function mytpl(){
$suffix = C('html_file_suffix');
$jump = intval($_GET['jump']);
$this->check(C('url_html'),'自定义模板');
import("ORG.Io.Dir");
$dir = new Dir(TEMPLATE_PATH.'/Home');
$list_dir = $dir->toArray();
$array_tpl = array();
foreach($list_dir as $key=>$value){
if(ereg("my_(.*)\.html",$value['filename'])){
C('html_file_suffix',$suffix);
$this->buildHtml(str_replace(array('my_','.html'),'',$value['filename']),'./'.C('url_mytpl'),'Home:'.str_replace('.html','',$value['filename']));
}
}
if ($jump) {
$this->assign("jumpUrl",'?s=Admin-Create-Maps-jump-'.$jump);
$this->success('自定义模板生成完毕,准备生成网站地图!');
}else{
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->success('恭喜您,自定义模板生成成功!');
}
}
//生成专题列表
public function speciallist(){
//检测是否需要生成
$this->check(C('url_html'),'专题列表页','?s=Admin-Create-Show');
//查询数据开始
$page = !empty($_GET['page']) ? intval($_GET['page']) : 1;
$limit = gettplnum('ff_mysql_special\(\'(.*)\'\)','pp_speciallist');
$rs = D("Special");
$where['special_status'] = array('eq',1);
$count = $rs->where($where)->count('special_id');
$totalpages = ceil($count/$limit);
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体">';
echo'<li>共有专题<font color=red>'.$count.'</font>篇,专题列表需要生成<font color=blue>'.$totalpages.'</font>页。</li>';
for($i=1;$i<=$totalpages;$i++){
//变量赋值
C('jumpurl',ff_special_url(9999));
C('currentpage',$i);
$channel = $this->Lable_Special_List(array('page'=>$i));
//生成文件
$htmldir = str_replace('{!page!}',$i,ff_special_url_dir($i));
$htmlurl = C('sitepath').$htmldir.C('html_file_suffix');
$this->buildHtml($htmldir,'./','Home:'.$channel['special_skin']);
echo'<li>第<font color=blue>'.$i.'</font>页生成完毕 <a href="'.$htmlurl.'" target="_blank">'.$htmlurl.'</a></li>';
ob_flush();flush();
}
echo'</ul>';
exit();
$this->jump('?s=Admin-Create-Show','恭喜您,专题列表页已经全部生成!');
}
//生成专题内容分页处理
public function specialclass(){
//检测是否需要生成
$this->check(C('url_html'),'专题内容页','?s=Admin-Create-Show');
//查询数据开始
$page = !empty($_GET['page']) ? intval($_GET['page']) : 1;
$rs = D("Special");
$where['special_status'] = array('eq',1);
$count = $rs->where($where)->count('special_id');
$totalpages = ceil($count/C('url_number'));
$array = $rs->field('special_id')->where($where)->order('special_addtime desc')->limit(C('url_number'))->page($page)->select();
if (empty($array)) {
$this->assign("jumpUrl",'?s=Admin-Create-Show');$this->error('没有数据,不需要生成!');
}
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体">';
echo'<li>总共需要生成<font color=blue>'.$count.'</font>个专题内容页,需要分<font color=blue>'.$totalpages.'</font>次来执行,正在执行第<font color=red>'.$page.'</font>次</li>';
foreach($array as $key=>$value){
$this->create_red_special($value['special_id']);
}
echo'</ul>';
//组合回跳URL路径与执行跳转
$jumpurl = '?s=Admin-Create-Show';
if($page < $totalpages){
$jumpurl = '?s=Admin-Create-Specialclass-page-'.($page+1);
$this->jump($jumpurl,'稍等一会,准备生成下一次专题内容页...');
}
$this->jump($jumpurl,'恭喜您,专题内容页全部生成完毕。');
}
//生成专题内容页
public function create_red_special($specialid){
$where = array();
$where['special_id'] = $specialid;
$where['special_status'] = array('eq',1);
$rs = D("Special");
$array_special = $rs->where($where)->find();
if($array_special){
$arrays = $this->Lable_Special_Read($array_special);
$this->assign($arrays['read']);
$this->assign('list_vod',$arrays['list_vod']);
$this->assign('list_news',$arrays['list_news']);
//
$htmldir = ff_data_url_dir('special',$arrays['read']['special_id'],0,$arrays['read']['special_name'],1);
$htmlurl = C('site_path').$htmldir.C('html_file_suffix');
$this->buildHtml($htmldir,'./',$arrays['read']['special_skin']);
echo '<li>'.$arrays['read']['special_id'].' <a href="'.$htmlurl.'" target="_blank">'.$htmlurl.'</a> 生成完毕</li>';
}
}
//显示生成
public function show(){
$array['url_html'] = C('url_html');
if(C('url_html_list')){
$array['url_html_list'] = C('url_html_list');
}else{
$array['url_html_list'] = 0;
}
$listarr = F('_ppvod/list');
foreach($listarr as $key=>$value){
$keynew = $value['list_sid'];
$list[$keynew][$key] = $value['list_id'];
}
$this->assign($array);
$this->assign('jumpurl',F('_create/nextcreate'));
$this->assign('list_vod_all',implode(',',$list[1]));
$this->assign('list_news_all',implode(',',$list[2]));
$this->assign('list_vod',F('_ppvod/listvod'));
$this->assign('list_news',F('_ppvod/listnews'));
$this->display('./Public/system/html_show.html');
}
//判断生成条件
public function check($html_status,$html_err,$jumpurl='?s=Admin-Create-Show'){
if (!$html_status) {
$this->assign("jumpUrl",$jumpurl);
$this->error('"'.$html_err.'"模块动态运行,不需要生成静态网页!');
}
}
//生成跳转
public function jump($jumpurl,$html){
echo '</div><script>if(document.getElementById("show")){document.getElementById("show").style.display="none";}</script>';
$this->assign("waitSecond",C('url_time'));
$this->assign("jumpUrl",$jumpurl);
$this->success($html);
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/CreateHtmliuhuhg2123hu1ws12Action.class.php | PHP | asf20 | 24,410 |
<?php
class UserAction extends BaseAction{
// 后台用户管理
public function show(){
$rs = D("Admin.User");
$join = C('db_prefix').'group on '.C('db_prefix').'user.user_gid = '.C('db_prefix').'group.group_id';
$list = $rs->join($join)->order('user_id desc')->limit(C('url_num_admin'))->page(1)->select();
$this->assign('list',$list);
$this->assign('page',$show);
$this->display('./Public/system/admin_show.html');
}
// 用户添加与编辑表单
public function add(){
$rs = D("Admin.User");
$user_id = $_GET['id'];
if ($user_id>0) {
$where['user_id'] = $user_id;
$array = $rs->where($where)->find();
$array['user_duetime'] = date('Y-m-d H:i:s',$array['user_duetime']);
$array['user_jointime'] = date('Y-m-d H:i:s',$array['user_jointime']);
$array['user_logtime'] = date('Y-m-d H:i:s',$array['user_logintime']);
}else{
$array['user_id']=0;
$array['user_money']=0;
$array['user_duetime'] = date('Y-m-d H:i:s',time());
}
$rsg = D("Admin.Group");
$listgroup = $rsg->order('group_id desc')->select();
$this->assign($array);
$this->assign('listgroup',$listgroup);
$this->display(APP_PATH.'/Public/admin/user/add.html');
}
// 用户添加入库
public function insert() {
$rs = D("Admin.User");
if($rs->create()) {
if($rs->add()) {
$this->success('用户添加成功!');
}else{
$this->error('用户添加失败!');
}
}else{
$this->error($rs->getError());
}
}
// 更新用户
public function update(){
$rs = D("Admin.User");
if ($rs->create()) {
if (false !== $rs->save()) {
$this->assign("jumpUrl",'?s=Admin-User-Show');
$this->success('更新用户信息成功!');
}else{
$this->error("更新用户信息失败!");
}
}else{
$this->error($rs->getError());
}
}
// 删除用户
public function del(){
$rs = D("Admin.User");
$rs->where('user_id = '.$_GET['id'])->delete();
$this->success('删除用户成功!');
}
// 用户组列表
public function showgroup(){
$rs = D("Admin.Group");
$list = $rs->order('group_id asc')->select();
$this->assign('list',$list);
$this->display(APP_PATH.'/Public/admin/user/showgroup.html');
}
// 用户组添加与编辑表单
public function addgroup(){
$group_id = $_GET['id'];
if ($group_id>0) {
$rs = D("Admin.Group");
$where['group_id'] = $group_id;
$array = $rs->where($where)->find();
$this->assign($array);
}
$this->display(APP_PATH.'/Public/admin/user/addgroup.html');
}
// 用户组添加入库
public function insertgroup() {
$rs = D("Admin.Group");
if($rs->create()) {
if ($rs->add()) {
$this->success('用户组添加成功!');
}else{
$this->error('用户组添加失败!');
}
}else{
exit($rs->getError());
}
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/UserAction.class.php | PHP | asf20 | 3,018 |
<?php
class CollectAction extends BaseAction{
// 栏目分类转换
public function change(){
$change_content = trim(F('_collect/change'));
$this->assign('change_content',$change_content);
$this->display('./Public/system/collect_change.html');
}
// 栏目分类转换保存
public function changeup(){
F('_collect/change',trim($_POST["content"]));
$array_rule = explode(chr(13),trim($_POST["content"]));
foreach($array_rule as $key => $listvalue){
$arrlist = explode('|',trim($listvalue));
$array[$arrlist[0]] = intval($arrlist[1]);
}
F('_collect/change_array',$array);
$this->assign("jumpUrl",'?s=Admin-Collect-Change');
$this->success('栏目转换规则编辑成功!');
}
// 栏目分类转换保存
public function test(){
}
// 采集节点列表
public function show(){
dump('2.0正式版才推出。');
exit();
$rs = M("Collect");
$list = $rs->order('collect_id desc')->select();
$this->assign('list_collect',$list);
$this->display('./Public/system/collect_show.html');
}
// 添加编辑采集节点
public function add(){
$rs = M("Collect");
$collect_id = intval($_GET['id']);
if($collect_id){
$where['collect_id'] = $collect_id;
$array = $rs->where($where)->find();
$array['collect_replace'] = explode('|||',$array['collect_replace']);
$array['collect_tpltitle'] = '修改';
}else{
$array['collect_id'] = 0;
$array['collect_encoding'] = '2312';
$array['collect_player'] = 'qvod';
$array['collect_savepic'] = 0;
$array['collect_order'] = 0;
$array['collect_pagetype'] = 1;
$array['collect_pagesid'] = 1;
$array['collect_pageeid'] = 9;
$array['collect_tpltitle'] = '添加';
}
$array['collect_step'] = intval($_GET['step']);
$this->ppvod_play();
$this->assign($array);
$this->assign('listtree',F('_ppvod/listvod'));
$this->display('./Public/system/collect_add.html');
}
// 采集节点数据入库
public function insert() {
$rs = D("Collect");
if($rs->create()){
$id = $rs->add();
if(false !== $id){
//$this->f_replace($_POST['collect_replace'],$id);
redirect('?s=Admin-Collect-Add-id-'.$id.'-step-2');
}else{
$this->error('数据写入错误');
}
}else{
$this->error($rs->getError());
}
}
// 更新数据库信息
public function update(){
if(empty($_POST['collect_savepic'])){
$_POST['collect_savepic'] = 0;
}
if(empty($_POST['collect_order'])){
$_POST['collect_order'] = 0;
}
$rs = D("Collect");
if($rs->create()){
$id = intval($_POST['collect_id']);
if(false !== $rs->save()){
//F('_collects/id_'.$id,NULL);
//F('_collects/id_'.$id.'_rule',NULL);
//$this->f_replace($_POST['collect_replace'],$id);
$this->assign("jumpUrl",'?s=Admin-Collect-Caiji-ids-'.$id.'-tid-2');
$this->success('采集规则更新成功,测试一下是否能正常采集!');
}else{
$this->error("没有更新任何数据!");
}
}else{
$this->error($rs->getError());
}
}
// 复制规则
public function cop(){
$rs = D("Collect");
$id = intval($_GET['id']);
$array = $rs->find($id);
unset($array["collect_id"]);
$array["collect_title"] = $array["collect_title"].'-复制';
$rs->data($array)->add();
$this->success('复制采集规则成功!');
}
// 删除规则
public function del(){
$rs = D("Collect");
$id = intval($_GET['id']);
$where['collect_id'] = $id;
$rs->where($where)->delete();
F('_collects/cid_'.$id.'_rule',NULL);
F('_collects/cid_'.$id.'_replace',NULL);
$this->success('删除ID为'.$id.'的采集规则成功!');
}
// 批量删除规则
public function delall(){
if(empty($_POST['ids'])){
$this->error('请选择需要删除的采集规则!');
}
$array = $_POST['ids'];
$rs = D("Collect");
foreach($array as $value){
$rs->where('collect_id='.$value)->delete();
F('_collects/cid_'.$value.'_rule',NULL);
F('_collects/cid_'.$value.'_replace',NULL);
}
$this->success('批量删除采集规则成功!');
}
// 采集导出
public function export(){
dump('2.0正式版才推出。');
exit();
$rs = M("Collect");
$list = $rs->order('collect_id desc')->select();
$this->assign('list_collect',$list);
$this->display('./Public/system/collect_export.html');
}
// 执行采集导出
public function exportsql(){
$ids = $_POST['ids'];
if(!is_array($ids)){
$this->error("请选择要导出的规则!");
}
$where['collect_id'] = array('in',$ids);
$rs = M("Collect");
$list = $rs->where($where)->order('collect_id desc')->select();
F('_collects/ppvod_collect',$list);
$this->success("恭喜您!您选择的采集规则已经完整导出!");
}
// 采集导入
public function import(){
dump('2.0正式版才推出。');
exit();
$list = F('_collects/ppvod_collect');
if(!is_array($list)){
$this->error("没有找到采集规则文件Runtime/Data/_collects/ppvod_collect.php");
}
$this->assign('list_collect',$list);
$this->display('./Public/system/collect_export.html');
}
// 执行采集导入
public function importsql(){
$ids = $_POST['ids'];
if(!is_array($ids)){
$this->error("请选择要导入的规则!");
}
$list = F('_collects/ppvod_collect');
$rs = D("Collect");
$replace = array('all'=>'','listname'=>'','vodname'=>'','actor'=>'','director'=>'','content'=>'','vodpic'=>'','continu'=>'','url'=>'');
foreach($list as $key=>$val){
if(in_array($val['collect_id'],$ids)){
unset($val['collect_id']);
$cid = $rs->data($val)->add();
$abc = explode('|||',$val['collect_replace']);
$replace = array();
$replace['all'] = $abc[0];
$replace['listname'] = $abc[1];
$replace['vodname'] = $abc[2];
$replace['actor'] = $abc[3];
$replace['director'] = $abc[4];
$replace['content'] = $abc[5];
$replace['vodpic'] = $abc[6];
$replace['continu'] = $abc[7];
$replace['url'] = $abc[8];
//$this->f_replace($replace,$cid);
};
}
$this->assign("jumpUrl",'?s=Admin-Collect-Show');
$this->success("恭喜您,您选择的采集规则已经成功导入!");
}
// 采集主干
public function caiji(){
//判断是否批量采集并生成当前采集ID
$ids = $_REQUEST['ids'];
if(is_array($ids)){
$ids = '1,'.implode(',',$ids);
$id = $ids[0];
}else{
$ids = $_GET['ids'];
$id = $ids;
}
//生成采集列表与规则
$array = $this->caijicreateurl($id);
$pagetype = $array['rule']['collect_pagetype'];
//采集方式分支-开始采集 ids=多个ID id=当前id sid=start eid=end tid=test
if($pagetype<3){
//按列表页采集
$jumpurl = '?s=Admin-Collect-Caijilist-ids-'.$ids.'-id-'.$id.'-sid-0-eid-'.count($array['list']).'-tid-'.$_GET['tid'].'.html';
}else{
//按内容页采集
$jumpurl = '?s=Admin-Collect-Caijiid-ids-'.$ids.'-id-'.$id.'-sid-0-eid-'.count($array['list']).'-tid-'.$_GET['tid'].'.html';
}
redirect($jumpurl);
}
// 按列表页采集
public function caijilist(){
$list = F('_collects/id_'.$_GET['id']);
$rule = F('_collects/id_'.$_GET['id'].'_rule');
if(!$list || !$rule){
$this->error("采集范围或采集规则不正确,请修改!");
}
//判断采集范围是否采集完成
if($_GET['sid'] < $_GET['eid']){
$listurl = trim($list[$_GET['sid']]);
$html = ff_file_get_contents($listurl);
if(!html){
dump('获取网页'.$url.'数据失败!');
exit();
}
//编码转换
if("utf-8" <> $rule['collect_encoding']){
$html = g2u($html);
}
//缩小列表范围
if(!empty($rule['collect_listurlstr'])){
$html = ff_preg_match($html,$rule['collect_listurlstr']);
}
//列表页采集图片
if(!empty($rule['collect_listpicstr'])){
$array_url_pic = ff_preg_match_all($html,$rule['collect_listpicstr']);
$array_url_pic = preg_replace($replace['1']['patterns'],$replace['1']['replaces'],trim(ff_preg_match($html,$rule['collect_content'])));
}
//内容页链接数组
$array_url_detail = ff_preg_match_all($html,$rule['collect_listlink']);
//是否倒序
if(1 == $rule['collect_order']){
$array_url_pic = ff_krsort_url($array_url_pic);
$array_url_detail = ff_krsort_url($array_url_detail);
}
//获取内容页源码并入库
foreach($array_url_detail as $key=>$val){
$list_picurl = preg_replace($replace['0']['patterns'],$replace['0']['replaces'],trim($array_url_pic[$key]));
$vod = $this->caijimdb(get_base_url($listurl,trim($val)),$rule,$list_picurl,$_GET['tid']);
dump($vod);
ob_flush();flush();
}
}else{
F('_collects/id_'.$_GET['id'],NULL);
F('_collects/id_'.$_GET['id'].'_rule',NULL);
$this->checknext($_GET['id']);
$this->assign("jumpUrl",'?s=Admin-Vod-Show-vod_cid-0');
$this->success('恭喜你!所有采集任务成功完成!<br><br>点此查看一些相似的影片是否需要入库!');
}
}
// 按影片ID采集
public function caijiid(){
$list = F('_collects/id_'.$_GET['id']);
$rule = F('_collects/id_'.$_GET['id'].'_rule');
if(!$list || !$rule){
$this->error("采集范围或采集规则不正确,请修改!");
}
//判断是否为采集完测试
if($_GET['tid']){
$vod = $this->caijimdb(trim($list[$_GET['sid']]),$rule,'',$_GET['tid']);
$this->caijishow($vod);
exit();
}
//判断采集范围是否采集完成
if($_GET['sid'] < $_GET['eid']){
$sid = intval($_GET['sid']);
for($ii=0;$ii<10;$ii++){//一次采集5个
$vod = $this->caijimdb(trim($list[$sid]),$rule,'',$_GET['tid']);
$this->caijishow($vod);
$sid++;
if($sid > $_GET['eid']){
dump('采集完成');
exit();
}
}
$jumpurl = '?s=Admin-Collect-Caijiid-ids-'.$_GET['ids'].'-id-'.$_GET['id'].'-sid-'.($sid+1).'-eid-'.$_GET['eid'].'-tid-'.$_GET['tid'].'.html';
$this->caijijumpurl($jumpurl);
}
//判断采集节点是否采集完成
$this->caijiend($_GET['id']);
}
//处理采集内容页并入库
public function caijimdb($url,$rule,$picurl='',$tid=''){
//获取过滤规则
$replace = F('_collects/id_'.$rule['collect_id'].'_replace');
$url = preg_replace($replace['0']['patterns'],$replace['0']['replaces'],$url);
$html = ff_file_get_contents($url);
if(!html){
$vod['vod_state'] = '获取网页'.$url.'数据失败!';
return $vod;
}
//编码转换
if("utf-8" <> $rule['collect_encoding']){
$html = g2u($html);
}
$vod['vod_cid'] = $rule['collect_cid'];
if( 0 == $vod['vod_cid']){
$vod['vod_cid'] = preg_replace($replace['2']['patterns'],$replace['2']['replaces'],trim(ff_preg_match($html,$rule['collect_listname'])));
$vod['vod_cid'] = getlistid($vod['vod_cid']);
}
$vod['vod_name'] = preg_replace($replace['3']['patterns'],$replace['3']['replaces'],trim(ff_preg_match($html,$rule['collect_name'])));
$vod['vod_title'] = preg_replace($replace['4']['patterns'],$replace['4']['replaces'],trim(ff_preg_match($html,$rule['collect_info'])));
$vod['vod_actor'] = preg_replace($replace['5']['patterns'],$replace['5']['replaces'],trim(ff_preg_match($html,$rule['collect_actor'])));
$vod['vod_director'] = preg_replace($replace['6']['patterns'],$replace['6']['replaces'],trim(ff_preg_match($html,$rule['collect_director'])));
$vod['vod_content'] = preg_replace($replace['7']['patterns'],$replace['7']['replaces'],trim(ff_preg_match($html,$rule['collect_content'])));
if(C('play_collect')){
$vod['vod_content'] = ff_rand_str($vod['vod_content']);
}
//是否列表页获取图片
if($picurl){
$vod['vod_pic'] = get_base_url($url,$picurl);
}else{
$vod['vod_pic'] = preg_replace($replace['8']['patterns'],$replace['8']['replaces'],trim(ff_preg_match($html,$rule['collect_pic'])));
$vod['vod_pic'] = get_base_url($url,$vod['vod_pic']);
}
$vod['vod_continu'] = preg_replace($replace['9']['patterns'],$replace['9']['replaces'],trim(ff_preg_match($html,$rule['collect_continu'])));
if(empty($vod['vod_continu'])){
$vod['vod_continu'] = 0;
}
$vod['vod_area'] = preg_replace($replace['10']['patterns'],$replace['10']['replaces'],trim(ff_preg_match($html,$rule['collect_area'])));
$vod['vod_language'] = preg_replace($replace['11']['patterns'],$replace['11']['replaces'],trim(ff_preg_match($html,$rule['collect_language'])));
$vod['vod_year'] = preg_replace($replace['12']['patterns'],$replace['12']['replaces'],trim(ff_preg_match($html,$rule['collect_year'])));
$vod['vod_zimu'] = preg_replace($replace['13']['patterns'],$replace['13']['replaces'],trim(ff_preg_match($html,$rule['collect_zimu']))); //QQ:182377860
//默认值
$vod['vod_savepic'] = $rule['collect_savepic'];
$vod['vod_addtime'] = time();
$vod['vod_inputer'] = 'collect'.$rule['collect_id'];
$vod['vod_stars'] = 1;
$vod['vod_letter'] = ff_letter_first($vod['vod_name']);
$vod['vod_play'] = $rule['collect_player'];
$vod['vod_reurl'] = $url;
//是否缩小地址范围
if(!empty($rule['collect_urlstr'])){
$html = ff_preg_match($html,$rule['collect_urlstr']);
}
//是否采集分集名称
if(!empty($rule['collect_urlname'])){
$arrname = ff_preg_match_all($html,$rule['collect_urlname']);
}
$arrurl = ff_preg_match_all($html,$rule['collect_urllink']);
$playurl = '';
foreach($arrurl as $key=>$val){
if(is_array($arrname)){
$playname = $arrname[$key].'$';
}else{
$playname = '';
}
//播放页是否新窗口
if(!empty($rule['collect_url'])){
$val = preg_replace($replace['url']['patterns'],$replace['url']['replaces'],$val);
$html = ff_file_get_contents(get_base_url($url,$val));
if("utf-8"<>$rule['collect_encoding']){
$html = g2u($html);
}
$playurl = $playurl.chr(13).$playname.trim(ff_preg_match($html,$rule['collect_url']));
}else{
$playurl = $playurl.chr(13).$playname.trim($val);
}
}
$vod['vod_url'] = trim(preg_replace($replace['13']['patterns'],$replace['13']['replaces'],$playurl));
//处理是否写入数据
if($tid){
$vod['vod_state'] = '采集测试,数据不写入数据库!';
}else{
$vod['vod_state'] = $this->xml_insert($vod);
}
return $vod;
}
//定时采集
public function dingshi(){
if(in_array(date("w"),$_POST['collect_week'])){
if(in_array(date("H"),$_POST['collect_hour'])){
$gid=implode(',',$_REQUEST['collect_id']);
$gid='?s=Admin-Collect-Ing-collect_id-'.$_REQUEST['collect_id'][0].'-gid-1,'.$gid;
}
}
$this->assign('gid',$gid);
$this->display(APP_PATH.'/Public/admin/collect.html');
}
// 生成采集列表缓存/采集规则缓存/替换规则缓存
public function caijicreateurl($id){
$rs = M("Collect");
$array = $rs->where('collect_id='.$id)->find();
if(!$array){
exit();
}
// 组合替换规则($rule)
foreach($array as $key =>$val){
if(strpos($val,'[$ppvod]')>0){
$rule[$key] = ff_replace_rule($val);
}else{
$rule[$key] = $val;
}
}
//组合采集范围($listurl)
if($array['collect_pagetype']==2 || $array['collect_pagetype']==3){
for($i=0;$i <= abs(intval($array['collect_pagesid']-$array['collect_pageeid']));$i++){
$listurl[$i] = str_replace('[$ppvod]',$i+$array['collect_pagesid'],$array['collect_pagestr']);
}
}elseif($array['collect_pagetype']==1 || $array['collect_pagetype']==4){
$listurl = explode(chr(13),$array['collect_liststr']);
};
//是否倒序($listurl)
if(1 == $array['collect_order']){
$listurl = ff_krsort_url($listurl);
}
//生成采集范围与采集规则缓存
F('_collects/id_'.$id,$listurl);
F('_collects/id_'.$id.'_rule',$rule);
//生成替换规则缓存
$arr_replace = explode('|||',$array['collect_replace']);
foreach($arr_replace as $i=>$v1){
foreach(explode(chr(13),trim($v1)) as $j=>$v){
list($key,$val) = explode('$$$',trim($v));
$arr1[$j] = '/'.trim(stripslashes($key)).'/si';
$arr2[$j] = trim($val);
}
$arr[$i] = array('patterns'=>$arr1,'replaces'=>$arr2);
}
F('_collects/id_'.$id.'_replace',$arr);
//返回采集列表与规则数组
return array('list'=>$listurl,'rule'=>$rule);
}
//显示采集信息
public function caijishow($vod){
echo('<div style="font-size:12px;margin-bottom:5px;">');
echo('影片:'.$vod['vod_name'].'<br />');
echo('主演:'.$vod['vod_actor'].'<br />');
echo('图片:<a href="'.$vod['vod_pic'].'" target="_blank">'.$vod['vod_pic'].'</a><br />');
echo('来源:<a href="'.$vod['vod_reurl'].'" target="_blank">'.$vod['vod_reurl'].'</a><br />');
echo('状态:<font color=red>'.$vod['vod_state'].'</font><br />');
echo('</div>');
ob_flush();flush();
}
//采集节点跳转
public function caijijumpurl($jumpurl){
echo('<div style="font-size:12px;margin-bottom:5px;color:read">');
echo C('play_collect_time').'秒后将自动采集下一页!';
echo('</div>');
echo '<meta http-equiv="refresh" content='.C('play_collect_time').';url='.$jumpurl.'>';
ob_flush();flush();
exit();
}
//检测采集任务是否完成
public function caijiend($id){
$this->checknext($_GET['id']);
F('_collects/id_'.$_GET['id'],NULL);
F('_collects/id_'.$_GET['id'].'_rule',NULL);
F('_collects/id_'.$_GET['id'].'_replace',NULL);
$this->assign("jumpUrl",'?s=Admin-Vod-Show-vod_cid-0');
$this->success('恭喜你!所有采集任务成功完成!<br><br>点此查看一些相似的影片是否需要入库!');
}
//判断与处理下一个采集节点转向地址
public function checknext($string){
if(!empty($string)){
$gid=explode(',',$string);
$collect_nowid=$gid[0];
$gid[0]=$collect_nowid+1;
$collect_nexturl='?s=Admin-Collect-Ing-collect_id-'.$gid[$gid[0]];
$collect_count=count($gid)-1;
$gid=implode(',',$gid);
$collect_nexturl=$collect_nexturl.'-gid-'.$gid;//生成下一个采集节点地址
if($collect_nowid==$collect_count){
if(c('url_html')){
header("Location: ?s=Admin-Html-Showvod-did-1-gid-1");//生成当天静态
}else{
if(c('html_cache_on')){
header("Location: ?s=Admin-Cache-Vodday");//清空当天缓存
}
}
}else{
header("Location: ".$collect_nexturl."");
}
}
}
// 写入替换规则缓存
public function f_replace($rearr,$collectid){
foreach($rearr as $i=>$v1){
foreach(explode(chr(13),trim($v1)) as $j=>$v){
list($key,$val)=explode('$$$',trim($v));
$arr1[$j]='/'.trim(stripslashes($key)).'/si';
$arr2[$j]=trim($val);
}
$arr[$i]=array('patterns'=>$arr1,'replaces'=>$arr2);
}
F('_collects/id_'.$collectid.'_replace',$arr);
return $arr;
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/CollectAction.class.php | PHP | asf20 | 19,063 |
<?php
class GbAction extends BaseAction{
// 用户留言管理
public function show(){
$admin = array();$where = array();
$admin['cid'] = intval($_REQUEST['cid']);
$admin['status'] = intval($_GET['status']);
$admin['intro'] = intval($_GET['intro']);
$admin['wd'] = urldecode(trim($_REQUEST['wd']));
if ($admin['cid']) {
$where['gb_cid'] = array('gt',0);
$admin['gb_title'] = '报错';
}else{
$where['gb_cid'] = array('eq',0);
$admin['gb_title'] = '留言';
}
if ($admin['status'] == 2) {
$where['gb_status'] = array('eq',0);
}elseif ($admin['status'] == 1) {
$where['gb_status'] = array('eq',1);
}
if ($admin['intro']) {
$where['gb_intro'] = array('eq','');
}
if (!empty($admin['wd'])) {
$search['gb_ip'] = array('like','%'.$admin['wd'].'%');
$search['gb_content'] = array('like','%'.$admin['wd'].'%');
$search['user_name'] = array('like','%'.$admin['wd'].'%');
$search['_logic'] = 'or';
$where['_complex'] = $search;
$admin['wd'] = urlencode($admin['wd']);
}
//
$admin['p'] = '';
$rs = D('GbView');
$count = $rs->where($where)->count();
$limit = intval(C('url_num_admin'));
$currentpage = !empty($_GET['p'])?intval($_GET['p']):1;
$totalpages = ceil($count/$limit);
$currentpage = get_maxpage($currentpage,$totalpages);
$pageurl = U('Admin-Gb/Show',$admin,false,false).'{!page!}';
//
$admin['p'] = $currentpage;$_SESSION['gb_jumpurl'] = U('Admin-Gb/Show',$admin);
$admin['pages'] = '共'.$count.'篇留言 当前:'.$currentpage.'/'.$totalpages.'页 '.getpage($currentpage,$totalpages,8,$pageurl,'pagego(\''.$pageurl.'\','.$totalpages.')');
$admin['list'] = $rs->where($where)->limit($limit)->page($currentpage)->order('gb_oid desc,gb_addtime desc')->select();
$this->assign($admin);
$this->display('./Public/system/gb_show.html');
}
// 用户留言编辑
public function add(){
$rs = D('Gb');
$where['gb_id'] = $_GET['id'];
$array = $rs->where($where)->find();
$this->assign($array);
$this->display('./Public/system/gb_add.html');
}
// 更新用户留言
public function update(){
$rs = D('Gb');
if ($rs->create()) {
if (false !== $rs->save()) {
$this->assign("jumpUrl",$_SESSION['gb_jumpurl']);
$this->success('更新留言信息成功!');
}else{
$this->error("更新留言信息失败!");
}
}
$this->error($rs->getError());
}
// 删除留言BY-ID
public function del(){
$rs = D('Gb');
$where['gb_id'] = $_GET['id'];
$rs->where($where)->delete();
redirect($_SERVER['HTTP_REFERER']);
}
// 删除留言All
public function delall($uid){
if(empty($_POST['ids'])){
$this->error('请选择需要删除的留言信息!');
}
$rs = D('Gb');
$where['gb_id'] = array('in',implode(',',$_POST['ids']));
$rs->where($where)->delete();
redirect($_SERVER['HTTP_REFERER']);
}
// 清空留言
public function delclear(){
$rs = D('Gb');
if ($_REQUEST['cid']) {
$rs->where('gb_cid > 0')->delete();
}else{
$rs->where('gb_cid = 0')->delete();
}
$this->success('所有用户留言或报错信息已经清空!');
}
// 隐藏与显示留言
public function status(){
$rs = D('Gb');
$where['gb_id'] = $_GET['id'];
if(intval($_GET['value'])){
$rs->where($where)->setField('gb_status',1);
}else{
$rs->where($where)->setField('gb_status',0);
}
redirect($_SERVER['HTTP_REFERER']);
}
// 置顶留言
public function order(){
$rs = D('Gb');
$where['gb_id'] = $_GET['id'];
if(intval($_GET['value'])){
$rs->where($where)->setField('gb_oid',1);
}else{
$rs->where($where)->setField('gb_oid',0);
}
redirect($_SERVER['HTTP_REFERER']);
}
// 批量隐藏与显示留言
public function statusall(){
if(empty($_POST['ids'])){
$this->error('请选择需要操作的留言内容!');
}
$rs = D('Gb');
$where['gb_id'] = array('in',implode(',',$_POST['ids']));
if(intval($_GET['value'])){
$rs->where($where)->setField('gb_status',1);
}else{
$rs->where($where)->setField('gb_status',0);
}
redirect($_SERVER['HTTP_REFERER']);
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/GbAction.class.php | PHP | asf20 | 4,298 |
<?php
// 本后管理框架
class IndexAction extends BaseAction{
public function index(){
$this->display('./Public/system/index.html');
}
public function top(){
$this->display('./Public/system/top.html');
}
public function left(){
$array = F('_nav/list');
$this->assign('array_nav',$array);
$this->display('./Public/system/left.html');
}
public function right(){
$this->display('./Public/system/right.html');
}
public function phpinfo(){
phpinfo();
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/IndexAction.class.php | PHP | asf20 | 575 |
<?php
class Caches291sy3shjssi190k012j2Action extends Based1923d0j1i29szsakhodsaAction{
//缓存管理列表
public function show(){
$this->display('./Public/system/cache_show.html');
}
//清除系统缓存AJAX
public function del(){
import("ORG.Io.Dir");
$dir = new Dir;
$this->ppvod_list();
@unlink('./Runtime/~app.php');
@unlink('./Runtime/~runtime.php');
if(!$dir->isEmpty('./Runtime/Data/_fields')){$dir->del('./Runtime/Data/_fields');}
if(!$dir->isEmpty('./Runtime/Temp')){$dir->delDir('./Runtime/Temp');}
if(!$dir->isEmpty('./Runtime/Cache')){$dir->delDir('./Runtime/Cache');}
if(!$dir->isEmpty('./Runtime/Logs')){$dir->delDir('./Runtime/Logs');}
echo('清除成功');
}
// 删除静态缓存
public function delhtml(){
$id = $_GET['id'];
import("ORG.Io.Dir");
$dir = new Dir;
if('index' == $id){
@unlink(HTML_PATH.'index'.C('html_file_suffix'));
}elseif('vodlist'== $id){
if(is_dir(HTML_PATH.'Vod_show')){$dir->delDir(HTML_PATH.'Vod_show');}
}elseif('vodread' == $id){
if(is_dir(HTML_PATH.'Vod_read')){$dir->delDir(HTML_PATH.'Vod_read');}
}elseif('vodplay' == $id){
if(is_dir(HTML_PATH.'Vod_play')){$dir->delDir(HTML_PATH.'Vod_play');}
}elseif('newslist' == $id){
if(is_dir(HTML_PATH.'News_show')){$dir->delDir(HTML_PATH.'News_show');}
}elseif('newsread' == $id){
if(is_dir(HTML_PATH.'News_read')){$dir->delDir(HTML_PATH.'News_read');}
}elseif('ajax' == $id){
if(is_dir(HTML_PATH.'Ajax_show')){$dir->delDir(HTML_PATH.'Ajax_show');}
}else{
@unlink(HTML_PATH.'index'.C('html_file_suffix'));
if(is_dir(HTML_PATH.'Vod_show')){$dir->delDir(HTML_PATH.'Vod_show');}
if(is_dir(HTML_PATH.'Vod_read')){$dir->delDir(HTML_PATH.'Vod_read');}
if(is_dir(HTML_PATH.'Vod_play')){$dir->delDir(HTML_PATH.'Vod_play');}
if(is_dir(HTML_PATH.'News_show')){$dir->delDir(HTML_PATH.'News_show');}
if(is_dir(HTML_PATH.'News_read')){$dir->delDir(HTML_PATH.'News_read');}
if(is_dir(HTML_PATH.'Ajax_show')){$dir->delDir(HTML_PATH.'Ajax_show');}
}
echo('清除成功');
}
//
public function vodday(){
$this->ppvod_cachevodday();
$this->assign("jumpUrl",'?s=Admin-Caches291sy3shjssi190k012j2-Show');
$this->success('清空当天静态缓存成功!');
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/Caches291sy3shjssi190k012j2Action.class.php | PHP | asf20 | 2,385 |
<?php
class UploadAction extends BaseAction{
// 列表
public function show(){
$this->display('./Public/system/upload_show.html');
}
// 本地图片上传
public function upload(){
echo('<div style="font-size:12px; height:30px; line-height:30px">');
$uppath = './'.C('upload_path').'/';
$uppath_s = './'.C('upload_path').'-s/';
$sid = trim($_POST['sid']);//模型
$fileback = !empty($_POST['fileback']) ? trim($_POST['fileback']) : 'vod_pic';//回跳input
if ($sid) {
$uppath.= $sid.'/';
$uppath_s.= $sid.'/';
mkdirss($uppath);
mkdirss($uppath_s);
}
import("ORG.Net.UploadFile");
$up = new UploadFile();
//$up->maxSize = 3292200;
$up->savePath = $uppath;
$up->saveRule = uniqid;
$up->uploadReplace = true;
$up->allowExts = explode(',',C('upload_class'));
$up->autoSub = true;
$up->subType = date;
$up->dateFormat = C('upload_style');
if (!$up->upload()) {
$error = $up->getErrorMsg();
if($error == '上传文件类型不允许'){
$error .= ',可上传<font color=red>'.C('upload_class').'</font>';
}
exit($error.' [<a href="?s=Admin-Upload-Show-sid-'.$sid.'-fileback-'.$fileback.'">重新上传</a>]');
//dump($up->getErrorMsg());
}
$uploadList = $up->getUploadFileInfo();
//是否添加水印
if (C('upload_water')) {
import("ORG.Util.Image");
Image::water($uppath.$uploadList[0]['savename'],C('upload_water_img'),'',C('upload_water_pct'),C('upload_water_pos'));
}
//是否生成缩略图
if (C('upload_thumb')) {
$thumbdir = substr($uploadList[0]['savename'],0,strrpos($uploadList[0]['savename'], '/'));
mkdirss($uppath_s.$thumbdir);
import("ORG.Util.Image");
Image::thumb($uppath.$uploadList[0]['savename'],$uppath_s.$uploadList[0]['savename'],'',C('upload_thumb_w'),C('upload_thumb_h'),true);
}
//是否远程图片
if (C('upload_ftp')) {
$img = D('Img');
$img->ftp_upload($sid.'/'.$uploadList[0]['savename']);
}
echo "<script type='text/javascript'>parent.document.getElementById('".$fileback."').value='".$sid.'/'.$uploadList[0]['savename']."';</script>";
echo '文件上传成功 [<a href="?s=Admin-Upload-Show-sid-'.$sid.'-fileback-'.$fileback.'">重新上传</a>]';
//<a href="'.$uppath.$uploadList[0]['savename'].'" target="_blank"><font color=red>'.$uploadList[0]['savename'].'</font></a>
echo '</div>';
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/UploadAction.class.php | PHP | asf20 | 2,446 |
<?php
class VodAction extends BaseAction{
// 影片列表
public function show(){
$admin = array();
//获取地址栏参数
$admin['cid']= $_REQUEST['cid'];
$admin['continu'] = $_REQUEST['continu'];
$admin['status'] = intval($_REQUEST['status']);
$admin['player'] = trim($_REQUEST['player']);
$admin['stars'] = intval($_REQUEST['stars']);
$admin['type'] = !empty($_GET['type'])?$_GET['type']:C('admin_order_type');
$admin['order'] = !empty($_GET['order'])?$_GET['order']:'desc';
$admin['orders'] = 'vod_'.$admin["type"].' '.$admin['order'];
$admin['wd'] = urldecode(trim($_REQUEST['wd']));
$admin['tag'] = urldecode(trim($_REQUEST['tag']));
$admin['diantai'] = urldecode(trim($_REQUEST['diantai']));
$admin['tid'] = $_REQUEST['tid'];//专题ID
$admin['p'] = '';
//生成查询参数
$limit = C('url_num_admin');
$order = 'vod_'.$admin["type"].' '.$admin['order'];
if ($admin['cid']) {
$where['vod_cid']= getlistsqlin($admin['cid']);
}
if($admin["continu"] == 1){
$where['vod_continu'] = array('neq','0');
}
if ($admin['status'] == 2) {
$where['vod_status'] = array('eq',0);
}elseif ($admin['status'] == 1) {
$where['vod_status'] = array('eq',1);
}elseif ($admin['status'] == 3) {
$where['vod_status'] = array('eq',-1);
}
if($admin['player']){
$where['vod_play'] = array('like','%'.trim($admin['player']).'%');
}
if($admin['stars']){
$where['vod_stars'] = $admin['stars'];
}
if ($admin['wd']) {
$search['vod_name'] = array('like','%'.$admin['wd'].'%');
$search['vod_title'] = array('like','%'.$admin['wd'].'%');
$search['vod_actor'] = array('like','%'.$admin['wd'].'%');
$search['vod_director'] = array('like','%'.$admin['wd'].'%');
$search['_logic'] = 'or';
$where['_complex'] = $search;
$admin['wd'] = urlencode($admin['wd']);
}
//根据不同条件加载模型
if($admin['tag']){
$where['tag_sid'] = 1;
$where['tag_name'] = $admin['tag'];
$rs = D('TagView');
$admin['tag'] = urlencode($_REQUEST['tag']);
}else{
$rs = D("Vod");
}
//组合分页信息
$count = $rs->where($where)->count('vod_id');
$totalpages = ceil($count/$limit);
$currentpage = !empty($_GET['p'])?intval($_GET['p']):1;
$currentpage = get_maxpage($currentpage,$totalpages);//$admin['page'] = $currentpage;
$pageurl = U('Admin-Vod/Show',$admin,false,false).'{!page!}'.C('url_html_suffix');
$admin['p'] = $currentpage;$_SESSION['vod_jumpurl'] = U('Admin-Vod/Show',$admin).C('url_html_suffix');
$pages = '共'.$count.'部影片 当前:'.$currentpage.'/'.$totalpages.'页 '.getpage($currentpage,$totalpages,8,$pageurl,'pagego(\''.$pageurl.'\','.$totalpages.')');
$admin['pages'] = $pages;
//查询数据
$list = $rs->where($where)->order($order)->limit($limit)->page($currentpage)->select();
foreach($list as $key=>$val){
$list[$key]['list_url'] = '?s=Admin-Vod-Show-cid-'.$list[$key]['vod_cid'];
$list[$key]['vod_url'] = ff_data_url('vod',$list[$key]['vod_id'],$list[$key]['vod_cid'],$list[$key]['vod_name'],1,$list[$key]['vod_jumpurl']);
$list[$key]['vod_starsarr'] = admin_star_arr($list[$key]['vod_stars']);
}
//dump($rs->getLastSql());
//变量赋值并输出模板
$this->ppvod_play();
$this->assign($admin);
$this->assign('list',$list);
$this->assign('list_vod',F('_ppvod/listvod'));
if($admin['tid']){
$this->display('./Public/system/special_vod.html');
}else{
$this->display('./Public/system/vod_show.html');
}
}
// 添加编辑影片
public function add(){
$rs = D("Vod");
$vod_id = intval($_GET['id']);
if($vod_id){
$where['vod_id'] = $vod_id;
$array = $rs->where($where)->relation('Tag')->find();
foreach($array['Tag'] as $key=>$value){
$tag[$key] = $value['tag_name'];
}
foreach(explode('$$$',$array['vod_play']) as $key=>$val){
$play[array_search($val,C('play_player'))] = $val;
}
$array['vod_play_list'] = C('play_player');
$array['vod_server_list'] = C('play_server');
$array['vod_play'] = explode('$$$',$array['vod_play']);
$array['vod_server'] = explode('$$$',$array['vod_server']);
$array['vod_url'] = explode('$$$',$array['vod_url']);
$array['vod_starsarr'] = admin_star_arr($array['vod_stars']);
$array['vod_tags'] = implode(' ',$tag);
if (C('admin_time_edit')){
$array['checktime'] = 'checked';
}
$array['vod_tplname'] = '编辑';
$_SESSION['vod_jumpurl'] = $_SERVER['HTTP_REFERER'];
}else{
$array['vod_cid'] = cookie('vod_cid');
$array['vod_stars'] = 1;
$array['vod_status'] = 1;
$array['vod_hits'] = 0;
$array['vod_addtime'] = time();
$array['vod_continu'] = 0;
$array['vod_inputer'] = $_SESSION['admin_name'];
$array['vod_play_list'] = C('play_player');
$array['vod_server_list'] = C('play_server');
$array['vod_url']=array(0=>'');
$array['vod_starsarr'] = admin_star_arr(1);
$array['checktime'] = 'checked';
$array['vod_tplname'] = '添加';
}
$array['vod_language_list']=explode(',',C('play_language'));
$array['vod_area_list']=explode(',',C('play_area'));
$array['vod_zimu_list']=explode(',',C('play_zimu'));//QQ182377860
$array['vod_year_list']=explode(',',C('play_year'));
/*
* 多选选择类型
* QQ182377860
*/
if($array['vod_cid']){
$array['vod_cat_list'] = D('Mcat')->list_cat($array['vod_cid']);
}
$this->ppvod_play();
$this->assign($array);
$this->assign("jumpUrl",$_SESSION['vod_jumpurl']);
$this->assign('listvod',F('_ppvod/listvod'));
$this->display('./Public/system/vod_add.html');
}
// 数据库写入前置操作
public function _before_insert(){
//自动获取关键词tag
if(empty($_POST["vod_tags"]) && C('rand_tag')){
$_POST["vod_tags"] = ff_tag_auto($_POST["vod_name"],$_POST["vod_content"]);
}
//播放器组与地址组
$play = $_POST["vod_play"];
$server = $_POST["vod_server"];
foreach($_POST["vod_url"] as $key=>$val){
$val = trim($val);
if($val){
$vod_play[] = $play[$key];
$vod_server[] = $server[$key];
$vod_url[] = $val;
};
}
$_POST["vod_play"] = implode('$$$',$vod_play);
$_POST["vod_server"] = implode('$$$',$vod_server);
$_POST["vod_url"] = implode('$$$',$vod_url);
$_POST['vod_prty'] = empty($_POST['vod_prty']) ? 0 : implode(',', $_POST['vod_prty']);//QQ182377860
$_POST['vod_exp'] = empty($_POST['vod_exp']) ? 0 : implode(',', $_POST['vod_exp']);//QQ182377860
$_POST['vod_mcid'] = empty($_POST['vod_mcids']) ? 0 : implode(',', $_POST['vod_mcids']);//QQ182377860
}
// 新增数据
public function insert(){
$tag = D('Tag');$rs = D("Vod");
if($rs->create()){
//关联操作>>写入tag
if($_POST["vod_tags"]){
$rs->Tag = $tag->tag_array($_POST["vod_tags"],1);
$id = $rs->relation('Tag')->add();
}else{
$id = $rs->add();
}
$rs->$vod_id = $id;
}else{
$this->error($rs->getError());
}
}
// 数据库写入-后置操作
public function _after_insert(){
$rs = D("Vod");
$vod_id = $rs->$vod_id;
if($vod_id){
cookie('vod_cid',$vod_id);
$this->_after_add_update($vod_id);
$this->assign("jumpUrl",'?s=Admin-Vod-Add');
$this->success('视频添加成功,继续添加新视频!');
}else{
$this->error('视频添加失败。');
}
}
// 更新数据
public function update(){
$this->_before_insert();
$tag = D('Tag');$rs = D("Vod");
if($rs->create()){
if(false !== $rs->save()){
//手动更新TAG
if($_POST["vod_tags"]){
$tag->tag_update($_POST["vod_id"],$_POST["vod_tags"],1);
}
//后置操作条件
$rs->$vod_id = $_POST["vod_id"];
}else{
$this->error("修改影片信息失败!");
}
}else{
$this->error($rs->getError());
}
}
// 后置操作
public function _after_update(){
$rs = D("Vod");
$vod_id = $rs->$vod_id;
if($vod_id){
$this->_after_add_update($vod_id);
$this->assign("jumpUrl",$_SESSION['vod_jumpurl']);
$this->success('视频更新成功!');
}else{
$this->error('视频更新失败。');
}
}
//操作完毕后
public function _after_add_update($vod_id){
//删除数据缓存
if(C('data_cache_vod')){
S('data_cache_vod_'.$vod_id,NULL);
}
//删除静态缓存
if(C('html_cache_on')){
$id = md5($vod_id).C('html_file_suffix');
@unlink('./Html/Vod_read/'.$vod_id);
@unlink('./Html/Vod_play/'.$vod_id);
}
//生成网页
if(C('url_html')){
echo'<iframe scrolling="no" src="?s=Admin-Create-vodid-id-'.$vod_id.'" frameborder="0" style="display:none"></iframe>';
}
}
// 删除影片
public function del(){
$this->delfile($_GET['id']);
redirect($_SESSION['vod_jumpurl']);
}
// 删除影片all
public function delall(){
if(empty($_POST['ids'])){
$this->error('请选择需要删除的影片!');
}
$array = $_POST['ids'];
foreach($array as $val){
$this->delfile($val);
}
redirect($_SESSION['vod_jumpurl']);
}
// 删除静态文件与图片
public function delfile($id){
$where = array();
//删除影片观看记录
//$rs = D("View");
//$where['did'] = $id;
//$rs->where($where)->delete();
//删除专题收录
$rs = D("Topic");
$where['topic_sid'] = 1;
$where['topic_did'] = $id;
$rs->where($where)->delete();
unset($where);
//删除影片评论
$rs = D("Cm");
$where['cm_cid'] = $id;
$where['cm_sid'] = 1;
$rs->where($where)->delete();
unset($where);
//删除影片TAG
$rs = D("Tag");
$where['tag_id'] = $id;
$where['tag_sid'] = 1;
$rs->where($where)->delete();
unset($where);
//删除静态文件与图片
$rs = D("Vod");
$where['vod_id'] = $id;
$array = $rs->field('vod_id,vod_cid,vod_pic,vod_name')->where($where)->find();
@unlink(ff_img_url($arr['vod_pic']));
if(C('url_html') > 0){
@unlink(ff_data_url_dir('vod',$array['vod_id'],$array['vod_cid'],$array['vod_name'],1).C('html_file_suffix'));
@unlink(ff_play_url_dir($array['vod_id'],0,1,$array['vod_cid'],$array['vod_name']).C('html_file_suffix'));
@unlink(ff_play_url_dir($array['vod_id'],0,1,$array['vod_cid'],$array['vod_name']).'js');
}
unset($where);
//删除影片ID
$where['vod_id'] = $id;
$rs->where($where)->delete();
unset($where);
}
// 批量生成数据
public function create(){
echo'<iframe scrolling="no" src="?s=Admin-Create-vodid-id-'.implode(',',$_POST['ids']).'" frameborder="0" style="display:none"></iframe>';
$this->assign("jumpUrl",$_SESSION['vod_jumpurl']);
$this->success('批量生成数据成功!');
}
// 批量转移影片
public function pestcid(){
if(empty($_POST['ids'])){
$this->error('请选择需要转移的影片!');
}
$cid = intval($_POST['pestcid']);
if (getlistson($cid)) {
$rs = D("Vod");
$data['vod_cid'] = $cid;
$where['vod_id'] = array('in',$_POST['ids']);
$rs->where($where)->save($data);
redirect($_SESSION['vod_jumpurl']);
}else{
$this->error('请选择当前大类下面的子分类!');
}
}
// 设置状态
public function status(){
$where['vod_id'] = $_GET['id'];
$rs = D("Vod");
if($_GET['value']){
$rs->where($where)->setField('vod_status',1);
}else{
$rs->where($where)->setField('vod_status',0);
}
redirect($_SESSION['vod_jumpurl']);
}
// Ajax设置星级
public function ajaxstars(){
$where['vod_id'] = $_GET['id'];
$data['vod_stars'] = intval($_GET['stars']);
$rs = D("Vod");
$rs->where($where)->save($data);
echo('ok');
}
// Ajax设置连载
public function ajaxcontinu(){
$where['vod_id'] = $_GET['id'];
$data['vod_continu'] = trim($_GET['continu']);
$rs = D("Vod");
$rs->where($where)->save($data);
echo('ok');
}
/*
* ajax 获取类型数据
* QQ 182377860
*/
public function ajaxcat(){
$list_id = intval($_GET['id']);
$cat_data = D('Mcat')->list_cat($list_id);
$this->assign('cat_list',$cat_data);
$this->display('./Public/system/vod_ajaxcat.html');
}
public function modify_cat(){
$id = intval($_GET['id']);
$vodData = D('Vod')->field('vod_id,vod_cid,vod_mcid')->where(array('vod_id' => $id))->find();
$data['listvod'] = F('_ppvod/listvod');
$data['vod_cat_list'] = D('Mcat')->list_cat($vodData['vod_cid']);
$data['vodData'] = $vodData;
$this->assign('data',$data);
$this->display('./Public/system/modify_cat.html');
}
public function modify_cat_post(){
$vod_id = intval($_POST['vod_id']);
if(isset($_POST['vod_mcids'])) {
$mcids = implode(',', $_POST['vod_mcids']);
} else {
$mcids = '';
}
D('Vod')->where(array('vod_id'=>$vod_id))->save(array('vod_mcid' => $mcids));
echo 1;
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/VodAction.class.php | PHP | asf20 | 13,114 |
<?php
class CreateAction extends BaseAction{
//构造函数
public function _initialize(){
$_SESSION[C('USER_AUTH_KEY')] = "ffvod";// 无需权限认证
parent::_initialize();
$this->assign($this->Lable_Style());
$this->assign("waitSecond",C('url_time'));
}
//组合需要生成的资讯列表并缓存
public function newslist(){
$this->list_cache_array(2);
}
//生成资讯列表从缓存任务列表
public function newslist_create(){
$this->list_create_array(2);
}
//组合需要生成的视频列表并缓存
public function vodlist(){
$this->list_cache_array(1);
}
//生成视频列表从缓存任务列表
public function vodlist_create(){
$this->list_create_array(1);
}
//缓存视频/资讯列表列表路径为数组
public function list_cache_array($sid=1){
$jump = intval($_REQUEST['jump']);
$this->check(C('url_html_list'),getsidname($sid).'列表页','?s=Admin-Create-Index-jump-'.$jump);
$array_list = F('_ppvod/list');
$array_listids = explode(',',$_REQUEST['ids_list_'.$sid]);
$k = 0;
foreach($array_listids as $key=>$value){
$list = list_search($array_list,'list_id='.$value);
if($list[0]["list_limit"]){
$totalpages = ceil(getcount($value)/$list[0]["list_limit"]);
}else{
$totalpages = 1;
}
for($page = 1; $page <= $totalpages; $page++){
$array[$k]['id'] = $value;
$array[$k]['page'] = $page;
$k++;
}
}
F('_create/list',$array);
if($sid == 1){
$this->vodlist_create();
}else{
$this->newslist_create();
}
}
//生成视频/资讯列表列表从缓存数组(分页生成)
public function list_create_array($sid){
$List = F('_ppvod/list');
$Url = F('_create/list');
$key = intval($_REQUEST['key']);
$jump = intval($_REQUEST['jump']);
if($sid==1){
$nextcreate = '?s=Admin-Create-Vodlist_create-jump-'.$jump.'-key-'.$key;
$sidname = '视频';
}else{
$nextcreate = '?s=Admin-Create-Newslist_create-jump-'.$jump.'-key-'.$key;
$sidname = '资讯';
}
//断点生成(写入缓存)
F('_create/nextcreate',$nextcreate);
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体">';
echo'<li>总共需要生成<font color=blue>'.count($Url).'</font>个'.$sidname.'列表页,每页生成'.C('url_number').'个。</li>';
for($i=1;$i<=C('url_number');$i++){
if(!$Url[$key]){
break;
}
//变量赋值
C('jumpurl',ff_list_url(getsidname($sid),array('id'=>$Url[$key]['id'],'p'=>'{!page!}'),9999));
C('currentpage',$Url[$key]['page']);
$channel = list_search($List,'list_id='.$Url[$key]['id']);
if($sid == 1){
$channel = $this->Lable_Vod_List(array('id'=>$Url[$key]['id'],'page'=>$Url[$key]['page'],'order'=>'addtime'),$channel[0]);
// by 类型静态生成
$mcat = D('Mcat')->list_cat($Url[$key]['id']);
foreach ((array)$mcat as $k=>$v){
$mcat[$k]['m_url'] = UU('Home-vod/show', array('id'=>$Url[$key]['id'],'mcid'=>$v['m_cid']),false,true);
}
$this->assign('mcat',$mcat);//
}else{
$channel = $this->Lable_News_List(array('id'=>$Url[$key]['id'],'page'=>$Url[$key]['page'],'order'=>'addtime'),$channel[0]);
}
$this->assign($channel);
//目录路径并生成
//字母封面
if($createLetter == false && $channel['list_skin'] == 'pp_vodlist') {
$list_letter_dir = str_replace('{!page!}',$Url[$key]['page'],ff_list_letter_url_dir(getsidname($sid),$Url[$key]['id'],$Url[$key]['page']));
$this->buildHtml($list_letter_dir,'./','Home:pp_letter');
$createLetter = true;
}
//字母封面:
$listdir = str_replace('{!page!}',$Url[$key]['page'],ff_list_url_dir(getsidname($sid),$Url[$key]['id'],$Url[$key]['page']));
$this->buildHtml($listdir,'./','Home:'.$channel['list_skin']);
//预览路径
$showurl = C('sitepath').$listdir.C('html_file_suffix');
echo'<li>第<font color=red>'.($key+1).'</font>个生成完毕 <a href="'.$showurl.'" target="_blank">'.$showurl.'</a></li>';
ob_flush();flush();
$key++;
}
echo'</ul>';
if($key < count($Url)){
if($sid==1){
$nextcreate = '?s=Admin-Create-Vodlist_create-jump-'.$jump.'-key-'.$key;
}else{
$nextcreate = '?s=Admin-Create-Newslist_create-jump-'.$jump.'-key-'.$key;
}
$this->jump($nextcreate,'让服务器休息一会,生成任务等待中...');
}
F('_create/list',NULL);
if($jump){
$this->jump('?s=Admin-Create-Index-jump-'.$jump,'列表页已经全部生成,下次将生成网站首页。');
}
F('_create/nextcreate',NULL);
$this->jump('?s=Admin-Create-Show','恭喜您,列表页已经全部生成!');
}
//读取资讯内容按分类
public function newsclass(){
$jump = intval($_REQUEST['jump']);
$ids = trim($_REQUEST['ids_2']);
$page = !empty($_GET['page']) ? intval($_GET['page']) : 1;
//检测是否需要生成
$this->check(C('url_html'),'资讯内容页','?s=Admin-Create-Newslist-ids_2-'.$ids.'-jump-'.$jump);
//断点生成(写入缓存)
F('_create/nextcreate','?s=Admin-Create-Vodclass-ids_2-'.$ids.'-jump-'.$jump.'-page-'.$page);
//查询数据开始
$rs = D("News");
$where['news_status'] = array('eq',1);
$where['news_cid'] = array('in',$ids);
$count = $rs->where($where)->count('news_id');
$totalpages = ceil($count/C('url_number'));
$array = $rs->where($where)->order('news_addtime desc')->limit(C('url_number'))->page($page)->relation('Tag')->select();
if (empty($array)) {
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->error('当前分类没有数据,暂不需要生成!');
}
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体">';
echo'<li>总共需要生成<font color=blue>'.$count.'</font>个资讯内容页,需要分<font color=blue>'.$totalpages.'</font>次来执行,正在执行第<font color=red>'.$page.'</font>次</li>';
foreach($array as $key=>$value){
$this->news_read_create($value);
}
echo'</ul>';
//组合回跳URL路径与执行跳转
$jumpurl = '?s=Admin-Create-Show';
if($page < $totalpages){
$jumpurl = '?s=Admin-Create-Newsclass-ids_2-'.$ids.'-jump-'.$jump.'-page-'.($page+1);
}else{
if($jump){
$jumpurl = '?s=Admin-Create-Newslist-ids_list_2-'.$ids.'-jump-'.$jump;
}
}
if($page < $totalpages){
$this->jump($jumpurl,'稍等一会,准备生成下一次资讯内容页...');
}
F('_create/nextcreate',NULL);
$this->jump($jumpurl,'恭喜您,资讯内容页全部生成完毕。');
}
//读取资讯内容按时间
public function newsday(){
$jump = intval($_REQUEST['jump']);
$this->check(C('url_html'),'资讯内容页');
//查询数据开始
$rs = D("News");
$mday = intval($_REQUEST['mday_2']);
$min = intval($_REQUEST['min']);
$where['news_status'] = array('eq',1);
$where['news_cid'] = array('gt',0);
if($min){//生成多少分钟内的影片
$where['news_addtime'] = array('gt',time()-$min*60);
}else{
$where['news_addtime'] = array('gt',getxtime($mday));
}
//
$count = $rs->where($where)->count('news_id');
$totalpages = ceil($count/C('url_number'));
$page = !empty($_GET['page'])?intval($_GET['page']):1;
$array = $rs->where($where)->order('news_addtime desc')->limit(C('url_number'))->page($page)->relation('Tag')->select();
if (empty($array )) {
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->error('今日没有数据更新,暂不需要生成!');
}
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体">';
echo'<li>总共需要生成<font color=blue>'.$count.'</font>个资讯内容页,需要分<font color=blue>'.$totalpages.'</font>次来执行,正在执行第<font color=red>'.$page.'</font>次</li>';
foreach($array as $key=>$value){
$this->news_read_create($value);
}
echo'</ul>';
//组合回跳URL路径与执行跳转
$jumpurl = '?s=Admin-Create-Show';
if ($page < $totalpages) {
$jumpurl = '?s=Admin-Create-Newsday-jump-'.$jump.'-mday_2-'.$mday.'-min-'.$mid.'-page-'.($page+1);
}else{
if($jump){
$listarr = F('_ppvod/list');
foreach($listarr as $key=>$value){
$keynew = $value['list_sid'];
$list[$keynew][$key] = $value['list_id'];
}
$ids = implode(',',$list[1]);
$jumpurl = '?s=Admin-Create-Newslist-jump-1-ids_list_2-'.$ids;
}
}
if ($page < $totalpages) {
$this->jump($jumpurl,'第('.$page.')页已经生成完毕,正在准备下一个。');
}
F('_create/nextcreate',NULL);
$this->jump($jumpurl,'恭喜您,生成完毕。');
}
//读取资讯内容按ID
public function newsid(){
$where = array();
$rs = D("News");
$where['news_id'] = array('in',$_REQUEST["id"]);
$where['news_status'] = 1;
$where['news_cid'] = array('gt',0);
$array = $rs->where($where)->relation('Tag')->select();
foreach($array as $value){
$this->news_read_create($value);
}
}
//生成资讯内容页
public function news_read_create($array){
$arrays = $this->Lable_News_Read($array);
$this->assign($arrays['show']);
$this->assign($arrays['read']);
$newsdir = ff_data_url_dir('news',$arrays['read']['news_id'],$arrays['read']['news_cid'],$arrays['read']['news_name'],1);
$this->buildHtml($newsdir,'./',$arrays['read']['news_skin']);
$newsurl = C('site_path').$newsdir.C('html_file_suffix');
echo '<li>'.$arrays['read']['news_id'].' <a href="'.$newsurl.'" target="_blank">'.$newsurl.'</a> 生成完毕</li>';
ob_flush();flush();
}
//读取视频内容按分类
public function vodclass(){
$jump = intval($_REQUEST['jump']);
$ids = trim($_REQUEST['ids_1']);
$page = !empty($_GET['page']) ? intval($_GET['page']) : 1;
$this->check(C('url_html'),'视频内容页','?s=Admin-Create-Vodlist-ids_1-'.$ids.'-jump-'.$jump);
//断点生成(写入缓存)
F('_create/nextcreate','?s=Admin-Create-Vodclass-ids_1-'.$ids.'-jump-'.$jump.'-page-'.$page);
$rs = D("Vod");
$where['vod_status'] = array('eq',1);
$where['vod_cid'] = array('in',$ids);
$count = $rs->where($where)->count('vod_id');
$totalpages = ceil($count/C('url_number'));
$array = $rs->where($where)->order('vod_addtime desc')->limit(C('url_number'))->page($page)->relation('Tag')->select();
if (empty($array)) {
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->error('当前分类没有数据,暂不需要生成!');
}
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体"><li>总共需要生成<font color=blue>'.$count.'</font>个视频内容页,需要分<font color=blue>'.$totalpages.'</font>次来执行,正在执行第<font color=blue>'.$page.'</font>次</li>';
foreach($array as $key=>$value){
$this->vod_read_create2($value);
}
echo'</ul>';
//组合回跳URL路径与执行跳转
$jumpurl = '?s=Admin-Create-Show';
if($page < $totalpages){
$jumpurl = '?s=Admin-Create-Vodclass-ids_1-'.$ids.'-jump-'.$jump.'-page-'.($page+1);
}else{
if($jump){
$jumpurl = '?s=Admin-Create-Vodlist-ids_list_1-'.$ids.'-jump-'.$jump;
}
}
if($page < $totalpages){
$this->jump($jumpurl,'稍等一会,准备生成下一次视频内容页...');
}
F('_create/nextcreate',NULL);
$this->jump($jumpurl,'恭喜您,视频内容页全部生成完毕。');
}
//读取视频内容按时间
public function vodday(){
$jump = intval($_REQUEST['jump']);
$this->check(C('url_html'),'视频内容页');
$rs = D("Vod");
$mday = intval($_REQUEST['mday_1']);
$min = intval($_REQUEST['min']);
$where['vod_status'] = array('eq',1);
$where['vod_cid'] = array('gt',0);
//
if($min){//生成多少分钟内的影片
$where['vod_addtime'] = array('gt',time()-$min*60);
}else{
$where['vod_addtime'] = array('gt',getxtime($mday));
}
//
$count = $rs->where($where)->count('vod_id');
$totalpages = ceil($count/C('url_number'));
$page = !empty($_GET['page'])?intval($_GET['page']):1;
$array = $rs->where($where)->order('vod_addtime desc')->limit(C('url_number'))->page($page)->relation('Tag')->select();
if (empty($array )) {
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->error('今日没有数据更新,暂不需要生成!');
}
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体"><li>总共需要生成<font color=blue>'.$count.'</font>个视频内容页,需要分<font color=blue>'.$totalpages.'</font>次来执行,正在执行第<font color=blue>'.$page.'</font>次</li>';
foreach($array as $key=>$value){
$this->vod_read_create($value);
}
echo'</ul>';
if ($page < $totalpages) {
$jumpurl = '?s=Admin-Create-Vodday-jump-'.$jump.'-mday_1-'.$mday.'-min-'.$min.'-page-'.($page+1);
}else{
if($jump){
$listarr = F('_ppvod/list');
foreach($listarr as $key=>$value){
$keynew = $value['list_sid'];
$list[$keynew][$key] = $value['list_id'];
}
$ids = implode(',',$list[1]);
$jumpurl = '?s=Admin-Create-Vodlist-jump-1-ids_list_1-'.$ids;
}else{
$jumpurl = '?s=Admin-Create-Show';
}
}
if ($page < $totalpages) {
$this->jump($jumpurl,'第('.$page.')页已经生成完毕,正在准备下一个。');
}
F('_create/nextcreate',NULL);
$this->jump($jumpurl,'恭喜您,生成完毕。');
}
//读取影片内容按ID
public function vodid(){
$where = array();
$rs = D("Vod");
$where['vod_id'] = array('in',$_REQUEST["id"]);
$where['vod_cid'] = array('gt',0);
$where['vod_status'] = 1;
$array = $rs->where($where)->relation('Tag')->select();
foreach($array as $value){
$this->vod_read_create($value);
}
}
/***************************只生成动态页面不生成动态, start****************************************/
//修改。读取视频内容按未生成的静态,时间。
public function dongtai(){
$jump = intval($_REQUEST['jump']);
$this->check(C('url_html'),'视频内容页');
$rs = D("Vod");
$mday = intval($_REQUEST['mday_1']);
$min = intval($_REQUEST['min']);
$where['vod_status'] = array('eq',1);
$where['vod_cid'] = array('gt',0);
//
if($min){//生成多少分钟内的影片
$where['vod_addtime'] = array('gt',time()-$min*60);
}else{
$where['vod_addtime'] = array('gt',getxtime($mday));
}
//
$count = $rs->where($where)->count('vod_id');
$totalpages = ceil($count/C('url_number'));
$page = !empty($_GET['page'])?intval($_GET['page']):1;
$array = $rs->where($where)->order('vod_addtime desc')->limit(C('url_number'))->page($page)->relation('Tag')->select();
if (empty($array)) {
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->error('今日没有数据更新,暂不需要生成!');
}
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体"><li>总共需要生成<font color=blue>'.$count.'</font>个视频内容页,需要分<font color=blue>'.$totalpages.'</font>次来执行,正在执行第<font color=blue>'.$page.'</font>次</li>';
foreach($array as $key=>$value){
$this->vod_read_create2($value);
}
echo'</ul>';
if ($page < $totalpages) {
//$jumpurl = '?s=Admin-Create-dongtai-jump-'.$jump.'-mday_1-'.$mday.'-min-'.$mid.'-page-'.($page+1);
$jumpurl = '?s=Admin-Create-dongtai-jump-'.$jump.'-mday_1-'.$mday.'-min-'.$min.'-page-'.($page+1);//修改,疑似官方写错了,将$mid改成$min 正常!
}else{
if($jump){
$listarr = F('_ppvod/list');
foreach($listarr as $key=>$value){
$keynew = $value['list_sid'];
$list[$keynew][$key] = $value['list_id'];
}
$ids = implode(',',$list[1]);
$jumpurl = '?s=Admin-Create-Vodlist-jump-1-ids_list_1-'.$ids;
}else{
$jumpurl = '?s=Admin-Create-Show';
}
}
if ($page < $totalpages) {
$this->jump($jumpurl,'第('.$page.')页已经生成完毕,正在准备下一个。');
}
F('_create/nextcreate',NULL);
$this->jump($jumpurl,'恭喜您,生成完毕。');
}
//生成影视内容页
public function vod_read_create2($array){
$arrays = $this->Lable_Vod_Read($array);
$this->assign($arrays['show']);
$this->assign($arrays['read']);
//生成内容页
$videodir = ff_data_url_dir('vod',$arrays['read']['vod_id'],$arrays['read']['vod_cid'],$arrays['read']['vod_name'],1);
//判断需要生成的网址是否存在
clearstatcache();//清空内存
// 文件不存在或数据更新过了
if(is_file($_SERVER['DOCUMENT_ROOT'].C('site_path').$videodir.C('html_file_suffix')) == false || $this->insert($arrays['read']['vod_id'],$arrays['read']['vod_addtime']) == true){
$this->buildHtml($videodir,'./',$arrays['read']['vod_skin']);
echo('<li><a href="'.C('site_path').$videodir.C('html_file_suffix').'" target="_blank">'.$arrays['read']['vod_id'].'</a> detail ok!!!</li>');
//生成播放页
if(C('url_html')){
$this->vod_play_create($arrays);
}
ob_flush();
flush();
} else {
echo('<li><a href="'.C('site_path').$videodir.C('html_file_suffix').'" target="_blank">'.$arrays['read']['vod_id'].'</a> 无需重新更新!!!</li>');
}
}
// 新增数据
public function insert($id,$addtime){
$rs = D("Vodhis");
$condition['vod_id'] = $id;
$_POST['vod_id']= $id;
$_POST['vod_addtime']=$addtime;
// 把查询条件传入查询方法
$ex=$rs->where($condition)->select();
if($ex){
if($ex[0]['vod_addtime'] == $addtime)
{
return false; // 无需再生成
} else {
$this->vodhis_update();
}
} elseif ($rs->create()){
$rs->add();
}else{
return false;
}
return true;
}
// 更新数据
public function vodhis_update(){
$rs = D("Vodhis");
if($rs->create()){
/*只更新部分字段*/
$updateFields = array(
'vod_addtime' => $_POST['vod_addtime']
);
$rs->where(array('vod_id' => $_POST['vod_id']))->save($updateFields);
}else{
echo "执行异常发生。";
}
}
/***************************只生成动态页面不生成动态, end****************************************/
//生成影视内容页
public function vod_read_create($array){
$arrays = $this->Lable_Vod_Read($array);
$this->assign($arrays['show']);
$this->assign($arrays['read']);
//生成内容页
$videodir = ff_data_url_dir('vod',$arrays['read']['vod_id'],$arrays['read']['vod_cid'],$arrays['read']['vod_name'],1);
$this->buildHtml($videodir,'./',$arrays['read']['vod_skin']);
echo('<li><a href="'.C('site_path').$videodir.C('html_file_suffix').'" target="_blank">'.$arrays['read']['vod_id'].'</a> detail ok</li>');
//生成播放页
if(C('url_html')){
$this->vod_play_create($arrays);
}
ob_flush();
flush();
}
//生成播放页
public function vod_play_create($arrays){
//合集在一个页面
if(C('url_html_play')==1){
$this->assign($arrays['show']);
$arrays['read'] = $this->Lable_Vod_Play($arrays['read'],array('id'=>$arrays['read']['vod_id'],'sid'=>0,'pid'=>1));
$this->assign($arrays['read']);
$playdir = ff_play_url_dir($arrays['read']['vod_id'],0,1,$arrays['read']['vod_cid'],$arrays['read']['vod_name']);
$this->buildHtml($playdir,'./',$arrays['read']['vod_skin_play']);
echo('<li>'.$arrays['read']['vod_id'].' play ok</li>');
}elseif(C('url_html_play')==2){
echo('<li>'.$arrays['read']['vod_id'].' play ');
//生成播放地址js(只需要一次)
$player_dir = ff_play_url_dir($arrays['read']['vod_id'],0,1,$arrays['read']['vod_cid'],$arrays['read']['vod_name']);
write_file('./'.$player_dir.'.js',$arrays['read']['vod_player']);
//播放页模板通用变量解析
$this->assign($arrays['show']);
//第一个分集生成完后
foreach($arrays['read']['vod_playlist'] as $sid=>$son){
$arr_sid = explode('-',$sid);
$arr_play = array();
foreach($son["son"] as $pid=>$value){
//路径替换与生成
$player_dir_ji = preg_replace('/play-([0-9]+)-([0-9]+)-([0-9]+)/i','play-$1-'.$arr_sid[1].'-'.($pid+1).'',$player_dir);
$this->assign($this->Lable_Vod_Play($arrays['read'],array('id'=>$arrays['read']['vod_id'],'sid'=>$arr_sid[1],'pid'=>$pid+1),true));
$this->buildHtml($player_dir_ji,'./',$arrays['read']['vod_skin_play']);
//echo($arr_sid[1].'-'.($pid+1).' ');
}
echo('ok </li>');
}
}
}
//一键生成全站地图
public function maps(){
$this->check(C('url_html'),'网站地图');
$this->google(true);
$this->baidu(true);
$this->rss(true);
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->success('恭喜您,所有地图生成完毕!');
}
//生成Baidu地图
public function baidu($id){
$baiduall = !empty($_REQUEST['baiduall'])?intval($_REQUEST['baiduall']):10000;
$baidu = !empty($_REQUEST['baidu'])?intval($_REQUEST['baidu']):2000;
$page = ceil(intval($baiduall)/intval($baidu));
for($i=1;$i<=$page;$i++){
$this->map_create('baidu',$baidu,$i);
}
if (empty($id)) {
$this->assign("waitSecond",5);
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->success('Baidu Sitemap地图生成成功!<br />请通过<a href="http://sitemap.baidu.com" target="_blank">百度站长平台</a>提交!');
}
}
//生成Google地图
public function google($id){
$googleall = !empty($_REQUEST['googleall'])?intval($_REQUEST['googleall']):5000;
$google = !empty($_REQUEST['google'])?intval($_REQUEST['google']):1000;
$page = ceil(intval($googleall)/intval($google));
for($i=1;$i<=$page;$i++){
$this->map_create('google',$google,$i);
}
if (empty($id)) {
$this->assign("waitSecond",5);
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->success('Google Sitemap地图生成成功!<br />请通过<a href="http://www.google.com/webmasters/tools" target="_blank">谷歌站长工具</a>提交!');
}
}
//生成Rss订阅
public function rss($id){
$rss = !empty($_REQUEST['rss'])?intval($_REQUEST['rss']):50;
$this->map_create('rss',$rss,1);
if (empty($id)) {
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->success('Rss订阅文件生成成功!');
}
}
//生成地图共用模块
public function map_create($mapname,$limit,$page){
$suffix = C('html_file_suffix');
$listmap = $this->Lable_Maps($mapname,$limit,$page);
if($listmap){
$this->assign('list_map',$listmap);
C('html_file_suffix','.xml');
if ($page == 1){
$this->buildHtml($mapname,'./'.C('url_map'),'./Public/maps/'.$mapname.'.html');
}else{
$this->buildHtml($mapname.'-'.$page,'./'.C('url_map'),'./Public/maps/'.$mapname.'.html');
}
C('html_file_suffix',$suffix);
}
}
//生成网站首页
public function index(){
$jump = intval($_GET['jump']);
$this->check(C('url_html'),'网站首页');
F('_create/nextcreate',NULL);
$this->assign($this->Lable_Index());
$this->buildHtml("index",'./','Home:pp_index');
if ($jump) {
$this->assign("jumpUrl",'?s=Admin-Create-Mytpl-jump-'.$jump);
$this->success('首页生成完毕,准备生成自定义模板!');
}else{
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->success('首页生成完毕。');
}
}
//生成自定义模板
public function mytpl(){
$suffix = C('html_file_suffix');
$jump = intval($_GET['jump']);
$this->check(C('url_html'),'自定义模板');
import("ORG.Io.Dir");
$dir = new Dir(TEMPLATE_PATH.'/Home');
$list_dir = $dir->toArray();
$array_tpl = array();
foreach($list_dir as $key=>$value){
if(ereg("my_(.*)\.html",$value['filename'])){
C('html_file_suffix',$suffix);
$this->buildHtml(str_replace(array('my_','.html'),'',$value['filename']),'./'.C('url_mytpl'),'Home:'.str_replace('.html','',$value['filename']));
}
}
if ($jump) {
$this->assign("jumpUrl",'?s=Admin-Create-Maps-jump-'.$jump);
$this->success('自定义模板生成完毕,准备生成网站地图!');
}else{
$this->assign("jumpUrl",'?s=Admin-Create-Show');
$this->success('恭喜您,自定义模板生成成功!');
}
}
//生成专题列表
public function speciallist(){
//检测是否需要生成
$this->check(C('url_html'),'专题列表页','?s=Admin-Create-Show');
//查询数据开始
$page = !empty($_GET['page']) ? intval($_GET['page']) : 1;
$limit = gettplnum('ff_mysql_special\(\'(.*)\'\)','pp_speciallist');
$rs = D("Special");
$where['special_status'] = array('eq',1);
$count = $rs->where($where)->count('special_id');
$totalpages = ceil($count/$limit);
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体">';
echo'<li>共有专题<font color=red>'.$count.'</font>篇,专题列表需要生成<font color=blue>'.$totalpages.'</font>页。</li>';
for($i=1;$i<=$totalpages;$i++){
//变量赋值
C('jumpurl',ff_special_url(9999));
C('currentpage',$i);
$channel = $this->Lable_Special_List(array('page'=>$i));
//生成文件
$htmldir = str_replace('{!page!}',$i,ff_special_url_dir($i));
$htmlurl = C('sitepath').$htmldir.C('html_file_suffix');
$this->buildHtml($htmldir,'./','Home:'.$channel['special_skin']);
echo'<li>第<font color=blue>'.$i.'</font>页生成完毕 <a href="'.$htmlurl.'" target="_blank">'.$htmlurl.'</a></li>';
ob_flush();flush();
}
echo'</ul>';
exit();
$this->jump('?s=Admin-Create-Show','恭喜您,专题列表页已经全部生成!');
}
//生成专题内容分页处理
public function specialclass(){
//检测是否需要生成
$this->check(C('url_html'),'专题内容页','?s=Admin-Create-Show');
//查询数据开始
$page = !empty($_GET['page']) ? intval($_GET['page']) : 1;
$rs = D("Special");
$where['special_status'] = array('eq',1);
$count = $rs->where($where)->count('special_id');
$totalpages = ceil($count/C('url_number'));
$array = $rs->field('special_id')->where($where)->order('special_addtime desc')->limit(C('url_number'))->page($page)->select();
if (empty($array)) {
$this->assign("jumpUrl",'?s=Admin-Create-Show');$this->error('没有数据,不需要生成!');
}
echo'<ul id="show" style="font-size:12px;list-style:none;margin:0px;padding:0px;font-family:宋体">';
echo'<li>总共需要生成<font color=blue>'.$count.'</font>个专题内容页,需要分<font color=blue>'.$totalpages.'</font>次来执行,正在执行第<font color=red>'.$page.'</font>次</li>';
foreach($array as $key=>$value){
$this->create_red_special($value['special_id']);
}
echo'</ul>';
//组合回跳URL路径与执行跳转
$jumpurl = '?s=Admin-Create-Show';
if($page < $totalpages){
$jumpurl = '?s=Admin-Create-Specialclass-page-'.($page+1);
$this->jump($jumpurl,'稍等一会,准备生成下一次专题内容页...');
}
$this->jump($jumpurl,'恭喜您,专题内容页全部生成完毕。');
}
//生成专题内容页
public function create_red_special($specialid){
$where = array();
$where['special_id'] = $specialid;
$where['special_status'] = array('eq',1);
$rs = D("Special");
$array_special = $rs->where($where)->find();
if($array_special){
$arrays = $this->Lable_Special_Read($array_special);
$this->assign($arrays['read']);
$this->assign('list_vod',$arrays['list_vod']);
$this->assign('list_news',$arrays['list_news']);
//
$htmldir = ff_data_url_dir('special',$arrays['read']['special_id'],0,$arrays['read']['special_name'],1);
$htmlurl = C('site_path').$htmldir.C('html_file_suffix');
$this->buildHtml($htmldir,'./',$arrays['read']['special_skin']);
echo '<li>'.$arrays['read']['special_id'].' <a href="'.$htmlurl.'" target="_blank">'.$htmlurl.'</a> 生成完毕</li>';
}
}
//显示生成
public function show(){
$array['url_html'] = C('url_html');
if(C('url_html_list')){
$array['url_html_list'] = C('url_html_list');
}else{
$array['url_html_list'] = 0;
}
$listarr = F('_ppvod/list');
foreach($listarr as $key=>$value){
$keynew = $value['list_sid'];
$list[$keynew][$key] = $value['list_id'];
}
$this->assign($array);
$this->assign('jumpurl',F('_create/nextcreate'));
$this->assign('list_vod_all',implode(',',$list[1]));
$this->assign('list_news_all',implode(',',$list[2]));
$this->assign('list_vod',F('_ppvod/listvod'));
$this->assign('list_news',F('_ppvod/listnews'));
$this->display('./Public/system/html_show.html');
}
//判断生成条件
public function check($html_status,$html_err,$jumpurl='?s=Admin-Create-Show'){
if (!$html_status) {
$this->assign("jumpUrl",$jumpurl);
$this->error('"'.$html_err.'"模块动态运行,不需要生成静态网页!');
}
}
//生成跳转
public function jump($jumpurl,$html){
echo '</div><script>if(document.getElementById("show")){document.getElementById("show").style.display="none";}</script>';
$this->assign("waitSecond",C('url_time'));
$this->assign("jumpUrl",$jumpurl);
$this->success($html);
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/CreateAction.class.php | PHP | asf20 | 29,715 |
<?php
class DataAction extends BaseAction{
// 数据库备份展示
public function show(){
$rs = new Model();
$list = $rs->query('SHOW TABLES FROM '.C('db_name'));
$tablearr = array();
foreach ($list as $key => $val) {
$tablearr[$key] = current($val);
}
$this->assign('list_table',$tablearr);
$this->display('./Public/system/data_show.html');
}
//处理数据库备份
public function insert(){
if(empty($_POST['ids'])){
$this->error('请选择需要备份的数据库表!');
}
$filesize = intval($_POST['filesize']);
if ($filesize < 512) {
$this->error('出错了,请为分卷大小设置一个大于512的整数值!');
}
$file = DATA_PATH.'_bak/';
$random = mt_rand(1000, 9999);
$sql = '';
$p = 1;
foreach($_POST['ids'] as $table){
$rs = D('Admin.'.str_replace(C('db_prefix'),'',$table));
$array = $rs->select();
$sql.= "TRUNCATE TABLE `$table`;\n";
foreach($array as $value){
$sql.= $this->insertsql($table, $value);
if (strlen($sql) >= $filesize*1000) {
$filename = $file.date('Ymd').'_'.$random.'_'.$p.'.sql';
write_file($filename,$sql);
$p++;
$sql='';
}
}
}
if(!empty($sql)){
$filename = $file.date('Ymd').'_'.$random.'_'.$p.'.sql';
write_file($filename,$sql);
}
$this->assign("jumpUrl",'?s=Admin-Data-Show');
$this->success('数据库分卷备份已完成,共分成'.$p.'个sql文件存放!');
}
//生成SQL备份语句
public function insertsql($table, $row){
$sql = "INSERT INTO `{$table}` VALUES (";
$values = array();
foreach ($row as $value) {
$values[] = "'" . mysql_real_escape_string($value) . "'";
}
$sql .= implode(', ', $values) . ");\n";
return $sql;
}
//展示还原
public function restore(){
$filepath = DATA_PATH.'_bak/*.sql';
$filearr = glob($filepath);
if (!empty($filearr)) {
foreach($filearr as $k=>$sqlfile){
preg_match("/([0-9]{8}_[0-9a-z]{4}_)([0-9]+)\.sql/i",basename($sqlfile),$num);
$restore[$k]['filename'] = basename($sqlfile);
$restore[$k]['filesize'] = round(filesize($sqlfile)/(1024*1024), 2);
$restore[$k]['maketime'] = date('Y-m-d H:i:s', filemtime($sqlfile));
$restore[$k]['pre'] = $num[1];
$restore[$k]['number'] = $num[2];
$restore[$k]['path'] = DATA_PATH.'_bak/';
}
$this->assign('list_restore',$restore);
$this->display('./Public/system/data_restore.html');
}else{
$this->assign("jumpUrl",'?s=Admin-Data-Show');
$this->error('没有检测到备份文件,请先备份或上传备份文件到'.DATA_PATH.'_bak/');
}
}
//导入还原
public function back(){
$rs = new Model();
$pre = $_GET['id'];
$fileid = $_GET['fileid'] ? intval($_GET['fileid']) : 1;
$filename = $pre.$fileid.'.sql';
$filepath = DATA_PATH.'_bak/'.$filename;
if(file_exists($filepath)){
$sql = read_file($filepath);
$sql = str_replace("\r\n", "\n", $sql);
foreach(explode(";\n", trim($sql)) as $query) {
$rs->query(trim($query));
}
$this->assign("jumpUrl",'?s=Admin-Data-Back-id-'.$pre.'-fileid-'.($fileid+1).'');
$this->success('第'.$fileid.'个备份文件恢复成功,准备恢复下一个,请稍等!');
}else{
$this->ppvod_list();
$this->assign("jumpUrl",'?s=Admin-Data-Show');
$this->success('数据库恢复成功!');
}
}
//下载还原
public function down(){
$filepath = DATA_PATH.'_bak/'.$_GET['id'];
if (file_exists($filepath)) {
$filename = $filename ? $filename : basename($filepath);
$filetype = trim(substr(strrchr($filename, '.'), 1));
$filesize = filesize($filepath);
header('Cache-control: max-age=31536000');
header('Expires: '.gmdate('D, d M Y H:i:s', time() + 31536000).' GMT');
header('Content-Encoding: none');
header('Content-Length: '.$filesize);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Type: '.$filetype);
readfile($filepath);
exit;
}else{
$this->error('出错了,没有找到分卷文件!');
}
}
//删除分卷文件
public function del(){
$filename = trim($_GET['id']);
@unlink(DATA_PATH.'_bak/'.$filename);
$this->success($filename.'已经删除!');
}
//删除所有分卷文件
public function delall(){
foreach($_POST['ids'] as $value){
@unlink(DATA_PATH.'_bak/'.$value);
}
$this->success('批量删除分卷文件成功!');
}
//展示高级SQL
public function sql(){
$this->display('./Public/system/data_sql.html');
}
//执行SQL语句
public function upsql(){
$sql = trim($_POST['sql']);
if (empty($sql)) {
$this->error('SQL语句不能为空!');
}else{
$sql = trim(stripslashes($sql));
$rs = new Model();
$rs->query($sql);
$lastsql = $rs->getLastSql();
$this->assign("waitSecond",5);
$this->success('SQL语句成功运行!<br>'.$lastsql);
}
}
//展示批量替换
public function replace(){
$rs = new Model();
$list = $rs->query('SHOW TABLES FROM '.C('db_name'));
$tablearr = array();
foreach ($list as $key => $val) {
$tablearr[$key] = current($val);
}
$this->assign('list_table',$tablearr);
$this->display('./Public/system/data_replace.html');
}
//Ajax展示字段信息
public function ajaxfields(){
$id = str_replace(C('db_prefix'),'',$_GET['id']);
if (!empty($id)) {
$rs = D("Admin.".$id);
$array = $rs->getDbFields();
echo "<div style='border:1px solid #ababab;width:500px;background-color:#FEFFF0;margin-top:6px;padding:3px;line-height:160%'>";
echo "表(".C('db_prefix').$id.")含有的字段:<br>";
foreach($array as $key=>$val){
if(!is_int($key)){
break;
}
if (ereg("cfile|username|userpwd|user|pwd",$val)){
continue;
}
echo "<a href=\"javascript:rpfield('".$val."')\">".$val."</a>\r\n";
}
echo "</div>";
}else{
echo 'no fields';
}
}
//执行批量替换
public function upreplace(){
if(empty($_POST['rpfield'])){
$this->error("请手工指定要替换的字段!");
}
if(empty($_POST['rpstring'])){
$this->error("请指定要被替换内容!");
}
$exptable = str_replace(C('db_prefix'),'',$_POST['exptable']);
$rs = D("Admin.".$exptable);
$exptable = C('db_prefix').$exptable;//表
$rpfield = trim($_POST['rpfield']);//字段
$rpstring = $_POST['rpstring'];//被替换的
$tostring = $_POST['tostring'];//替换内容
$condition = trim(stripslashes($_POST['condition']));//条件
$condition = empty($condition) ? '' : " where $condition ";
$rs->execute(" update $exptable set $rpfield = Replace($rpfield,'$rpstring','$tostring') $condition ");
$lastsql = $rs->getLastSql();
$this->success('批量替换完成!SQL执行语句!<br>'.$lastsql);
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/DataAction.class.php | PHP | asf20 | 6,958 |
<?php
class AdsAction extends BaseAction{
// 广告列表
public function show(){
$rs = D("Ads");
$list = $rs->order('ads_id desc')->select();
$this->assign('list_ads',$list);
$this->display('./Public/system/ads_show.html');
}
// 添加广告
public function add(){
$this->display('./Public/system/ads_add.html');
}
// 添加广告入库
public function insert(){
$rs = D("Ads");
if ($rs->create()) {
if (false !== $rs->add()) {
$this->assign("jumpUrl",'?s=Admin-Ads-Show');
}else{
$this->error('添加广告位出错!');
}
}else{
$this->error($rs->getError());
}
}
//后置操作
public function _after_insert(){
$array = $_POST;
write_file('./'.C('admin_ads_file').'/'.$array['ads_name'].'.js',t2js(stripslashes(trim($array['ads_content']))));
$this->success('添加广告位成功!');
}
// 更新广告
public function update(){
$array = $_POST;
$rs = D("Ads");
foreach($array['ads_id'] as $value){
$data['ads_id'] = $array['ads_id'][$value];
$data['ads_name'] = trim($array['ads_name'][$value]);
$data['ads_content'] = stripslashes(trim($array['ads_content'][$value]));
if(empty($data['ads_name'])){
$rs->where('ads_id='.$data['ads_id'])->delete();
}else{
write_file('./'.C('admin_ads_file').'/'.$data['ads_name'].'.js',t2js($data['ads_content']));
$rs->save($data);
}
}
$this->success('广告数据更新成功!');
}
// 预览广告
public function view(){
$id = $_GET['id'];
if ($id) {
$rs = D("Ads");
$list = $rs->field('ads_name')->where('ads_id='.$id)->find();
echo(getadsurl($list['ads_name']));
}
}
// 删除广告
public function del(){
$rs = D("Ads");
$where['ads_id'] = $_GET['id'];
$array = $rs->field('ads_name')->where($where)->find();
$rs->where($where)->delete();
@unlink('./'.C('admin_ads_file').'/'.$array['ads_name'].'.js');
redirect('?s=Admin-Ads-Show');
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/AdsAction.class.php | PHP | asf20 | 2,064 |
<?php
class SpecialAction extends BaseAction{
// 显示专题
public function show(){
//获取地址栏参数
$admin['cid']= $_REQUEST['cid'];
$admin['continu'] = $_REQUEST['continu'];
$admin['status'] = intval($_REQUEST['status']);
$admin['player'] = trim($_REQUEST['player']);
$admin['stars'] = intval($_REQUEST['stars']);
$admin['type'] = !empty($_GET['type'])?$_GET['type']:C('admin_order_type');
$admin['order'] = !empty($_GET['order'])?$_GET['order']:'desc';
$admin['orders'] = 'special_'.$admin["type"].' '.$admin['order'];
$admin['p'] = '';
//生成查询参数
$limit = C('url_num_admin');
$order = 'special_'.$admin["type"].' '.$admin['order'];
//组合分页信息
$rs = D("Special");
$count = $rs->count('special_id');
$totalpages = ceil($count/$limit);
$currentpage = !empty($_GET['p'])?intval($_GET['p']):1;
$currentpage = get_maxpage($currentpage,$totalpages);
$pageurl = U('Admin-Special/Show',$admin,false,false).'{!page!}'.C('url_html_suffix');
$admin['p'] = $currentpage;
$pages = '共'.$count.'篇专题 当前:'.$currentpage.'/'.$totalpages.'页 '.getpage($currentpage,$totalpages,8,$pageurl,'pagego(\''.$pageurl.'\','.$totalpages.')');
$admin['pages'] = $pages;
//查询数据
$list = $rs->where($where)->page($currentpage)->limit($limit)->order($order)->select();
foreach($list as $key=>$val){
$list[$key]['special_url'] = ff_data_url('special',$list[$key]['special_id'],0,$list[$key]['special_name'],1,'');
$list[$key]['special_starsarr'] = admin_star_arr($list[$key]['special_stars']);
}
//组合专题收录统计
$rs = D("Topic");
$list_topic = $rs->select();
foreach($list_topic as $key=>$value){
$array_topic[$value['topic_sid'].'-'.$value['topic_tid']][$key] = $value['topic_tid'];
}
$this->assign($admin);
$this->assign('list',$list);
$this->assign('array_count',$array_topic);
$this->display('./Public/system/special_show.html');
}
// 添加与编辑专题
public function add(){
$where = array();
$where['special_id'] = intval($_GET['id']);
if ($where['special_id']) {
$rs = D("Special");
$array = $rs->where($where)->find();
if (C('admin_time_edit')){
$array['checktime'] = 'checked';
}
$array['tpltitle'] = '编辑';
$array['special_starsarr'] = admin_star_arr($array['special_stars']);
//
$rs = D('Topic');
unset($where);
$where['topic_tid'] = $array['special_id'];
$where['topic_sid'] = 1;
$array['countvod'] = $rs->where($where)->count();
//
$where['topic_sid'] = 2;
$array['countnews'] = $rs->where($where)->count();
}else{
$array['special_starsarr'] = admin_star_arr(1);
$array['special_addtime'] = time();
$array['checktime'] = 'checked';
$array['tpltitle'] = '添加';
$array['countvod'] = 0;
$array['countnews'] = 0;
}
$this->assign($array);
$this->display('./Public/system/special_add.html');
}
// 添加专题并写入数据库
public function insert(){
$rs = D("Special");
if ($rs->create()) {
if ( false !== $rs->add() ) {
redirect('?s=Admin-Special-Show');
}else{
$this->error('添加专题失败');
}
}else{
$this->error($rs->getError());
}
}
// 更新专题
public function update(){
$rs = D("Special");
if ($rs->create()) {
if ($rs->save() === false) {
$this->error("更新专题失败!");
}
}else{
$this->error($rs->getError());
}
}
public function _after_update(){
//更新数据缓存
if(C('data_cache_special')){
S('data_cache_special_'.intval($_POST['special_id']),NULL);
}
redirect('?s=Admin-Special-Show');
}
// 隐藏与显示专题
public function status(){
$where['special_id'] = intval($_GET['id']);
$rs = D("Special");
if(intval($_GET['sid'])){
$rs->where($where)->setField('special_status',1);
}else{
$rs->where($where)->setField('special_status',0);
}
redirect($_SERVER['HTTP_REFERER']);
}
// 删除专题
public function del(){
$this->delfile(intval($_GET['id']));
$this->redirect('?s=Admin-Special-Show');
}
// 删除专题all
public function delall(){
if(empty($_POST['ids'])){
$this->error('请选择需要删除的专题!');
}
$array = $_POST['ids'];
foreach($array as $val){
$this->delfile($val);
}
redirect($_SERVER['HTTP_REFERER']);
}
// 删除静态文件与图片
public function delfile($id){
$where['special_id'] = $id;
$rs = D("Special");
$rs->where($where)->delete();
}
// 展示影视列表
public function ajax(){
$data = array(); $where = array();
$did = intval($_GET['did']);
$tid = intval($_GET['tid']);
$sid = !empty($_GET['sid'])?$_GET['sid']:1;
$type = trim($_GET['type']);//AJAX操作模块 add/del/up/down
$lastdid = intval($_GET['lastdid']);//需要处理排序的下一个ID
//执行添加或删除操作
if($did && $tid){
$rs = D("Topic");
if($type == 'add'){
//查询是否已添加
$rsid = $rs->where('topic_sid = '.$sid.' and topic_did = '.$did.' and topic_tid = '.$tid)->getField('topic_did');
if(!$rsid){
$count = $rs->where('topic_sid = '.$sid.' and topic_tid = '.$tid)->max('topic_oid');
$data['topic_did'] = $did;
$data['topic_tid'] = $tid;
$data['topic_sid'] = $sid;
$data['topic_oid'] = $count+1;
$rs->data($data)->add();
}
}elseif($type == 'del'){
$where['topic_did'] = $did;
$where['topic_tid'] = $tid;
$where['topic_sid'] = $sid;
$rs->where($where)->delete();
}elseif($type == 'up'){
$where['topic_did'] = $did;
$where['topic_tid'] = $tid;
$where['topic_sid'] = $sid;
$rs->setInc('topic_oid',$where);
//上一个ID的排序减1
$where['topic_did'] = $lastdid;
$rs->setDec('topic_oid',$where);
}elseif($type == 'down'){
$where['topic_did'] = $did;
$where['topic_tid'] = $tid;
$where['topic_sid'] = $sid;
$rs->setDec('topic_oid',$where);
//上一个ID的排序加1
$where['topic_did'] = $lastdid;
$rs->setInc('topic_oid',$where);
}
}
if($tid && $sid == 1){
$this->showvod($did,$tid);
}elseif($tid && $sid == 2){
$this->shownews($did,$tid);
}else{
echo('请先创建专辑!');
}
}
// 展示该专题已收录的影视列表
public function showvod($did,$tid){
$where = array();
$where['topic_sid'] = 1;
$where['topic_tid'] = $tid;
$rs = D('Topic');
$maxoid = $rs->where($where)->max('topic_oid');
$minoid = $rs->where($where)->min('topic_oid');
//
$rs = D('TopicvodView');
$list = $rs->field('vod_id,vod_name,vod_actor,topic_oid')->where($where)->order('topic_oid desc,topic_did desc')->select();
if(!$list){
echo('该专题暂未收录任何数据!');
}else{
$this->assign('max_oid',$maxoid);
$this->assign('min_oid',$minoid);
$this->assign('list_vod',$list);
$this->assign('count',count($list));
$this->display('./Public/system/special_vod_ids.html');
}
}
// 展示该专题已收录的资讯列表
public function shownews($did,$tid){
$where = array();
$where['topic_sid'] = 2;
$where['topic_tid'] = $tid;
$rs = D('Topic');
$maxoid = $rs->where($where)->max('topic_oid');
$minoid = $rs->where($where)->min('topic_oid');
//
$rs = D('TopicnewsView');
$list = $rs->field('news_id,news_name,topic_oid')->where($where)->order('topic_oid desc,topic_did desc')->select();
if(!$list){
echo('该专题暂未收录任何数据!');
}else{
$this->assign('max_oid',$maxoid);
$this->assign('min_oid',$minoid);
$this->assign('list_news',$list);
$this->assign('count',count($list));
$this->display('./Public/system/special_news_ids.html');
}
}
// Ajax设置星级
public function ajaxstars(){
$where['special_id'] = intval($_GET['id']);
$data['special_stars'] = intval($_GET['stars']);
$rs = D("Special");
$rs->where($where)->save($data);
echo('ok');
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/SpecialAction.class.php | PHP | asf20 | 8,150 |
<?php
class LoginAction extends Action{
//默认操作
public function index(){
if (!$_SESSION['AdminLogin']) {
header("Content-Type:text/html; charset=utf-8");
echo('请从后台管理入口登录。');
exit();
}
if ($_SESSION[C('USER_AUTH_KEY')]) {
redirect("?s=Admin-Index");
}
$this->display('./Public/system/login.html');
}
//登陆检测_前置
public function _before_check(){
if (empty($_POST['user_name'])) {
$this->error(L('login_username_check'));
}
if (empty($_POST['user_pwd'])) {
$this->error(L('login_password_check'));
}
}
//登陆检测
public function check(){
$where = array();
$where['admin_name'] = trim($_POST['user_name']);
$rs = D("Admin.Admin");
$list = $rs->where($where)->find();
if (NULL == $list) {
$this->error(L('login_username_not'));
}
if ($list['admin_pwd'] != md5($_POST['user_pwd'])) {
$this->error(L('login_password_not'));
}
// 缓存访问权限
$_SESSION[C('USER_AUTH_KEY')] = $list['admin_id'];
$_SESSION['admin_name'] = $list['admin_name'];
$_SESSION['admin_ok'] = $list['admin_ok'];
//更新用户登陆信息
$data = array();
$data['admin_id'] = $list['admin_id'];
$data['admin_logintime'] = time();
$data['admin_count'] = array('exp','admin_count+1');
$data['admin_ip'] = get_client_ip();
$rs->save($data);
redirect('?s=Admin-Index');
}
// 用户登出
public function logout(){
if (isset($_SESSION[C('USER_AUTH_KEY')])) {
unset($_SESSION);
session_destroy();
}
header("Content-Type:text/html; charset=utf-8");
echo ('您已经退出网站管理后台,如需操作请重新登录!');
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/LoginAction.class.php | PHP | asf20 | 1,776 |
<?php
class InstallAction extends Action{
public function _initialize() {
if(is_file('./Runtime/Install/install.lock')){
$this->assign("waitSecond",60);
$this->error('Sorry,您已经安装了飞飞PHP影视系统 V'.C('ffvod_version').' 版<br />重新安装请先删除 Runtime/install/install.lock 文件。');
}
}
public function index(){
$this->display('./Public/system/install.html');
}
public function second(){
$this->display('./Public/system/install.html');
}
public function setup(){
$this->display('./Public/system/install.html');
}
public function install(){
$data = $_POST['data'];
$rs = @mysql_connect($data['db_host'].":".intval($data['db_port']),$data['db_user'],$data['db_pwd']);
if(!$rs){
$this->error(L('install_db_connect'));
}
// 数据库不存在,尝试建立
if(!@mysql_select_db($data['db_name'])){
$sql = "CREATE DATABASE `".$data["db_name"]."` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
mysql_query($sql);
}
// 建立不成功
if(!@mysql_select_db($data['db_name'])){
$this->error(L('install_db_select'));
}
// 保存配置文件
$config = array(
'site_path'=>$data['site_path'],
'db_host'=>$data['db_host'],
'db_name'=>$data['db_name'],
'db_user'=>$data['db_user'],
'db_pwd'=>$data['db_pwd'],
'db_port'=>$data['db_port'],
'db_prefix'=>$data['db_prefix'],
);
$config_old = require './Runtime/Conf/config.php';
$config_new = array_merge($config_old,$config);
arr2file('./Runtime/Conf/config.php', $config_new);
// 批量导入安装SQL
$db_config = array(
'dbms'=>'mysql',
'username'=>$data['db_user'],
'password'=>$data['db_pwd'],
'hostname'=>$data['db_host'],
'hostport'=>$data['db_port'],
'database'=>$data['db_name']
);
$sql = read_file('./Runtime/Install/install.sql');
$sql = str_replace('ff_',$data['db_prefix'],$sql);
$this->batQuery($sql,$db_config);
touch('./Runtime/Install/install.lock');
@unlink('./Runtime/~app.php');
@unlink('./Runtime/~runtime.php');
$this->assign("jumpUrl",'Admin/index.php');
$this->success(L('install_success'));
}
public function batQuery($sql,$db_config){
// 连接数据库
require THINK_PATH.'/Lib/Think/Db/Driver/DbMysql.class.php';
$db = new Dbmysql($db_config);
$sql = str_replace("\r\n", "\n", $sql);
$ret = array();
$num = 0;
foreach(explode(";\n", trim($sql)) as $query){
$queries = explode("\n", trim($query));
foreach($queries as $query) {
$ret[$num] .= $query[0] == '#' || $query[0].$query[1] == '--' ? '' : $query;
}
$num++;
}
unset($sql);
foreach($ret as $query) {
if(trim($query)) {
$db->query($query);
}
}
return true;
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/InstallAction.class.php | PHP | asf20 | 2,873 |
<?php
class SlideAction extends BaseAction{
// 显示幻灯
public function show(){
$rs = D("Slide");
//更新前台缓存
$list = $rs->where('slide_status = 1')->order('slide_oid asc')->select();
if($list){
foreach($list as $key=>$val){
$list[$key]['slide_pic'] = ff_img_url($list[$key]['slide_pic']);
}
F('_ppvod/slide',$list);
}
//后台展示
$list = $rs->order('slide_oid asc')->select();
foreach($list as $key=>$val){
$list[$key]['slide_pic'] = ff_img_url($list[$key]['slide_pic']);
}
$this->assign('list_slide',$list);
$this->display('./Public/system/slide_show.html');
}
// 添加与编辑幻灯
public function add(){
$id = intval($_GET['id']);
$rs = D("Slide");
if ($id>0) {
$where['slide_id'] = $id;
$list = $rs->where($where)->find();
$list['tpltitle'] = '编辑';
}else{
$list['slide_oid'] = $rs->max('slide_oid')+1;
$list['slide_status'] = 1;
$list['tpltitle'] = '添加';
}
$this->assign($list);
$this->display('./Public/system/slide_add.html');
}
// 添加幻灯片并写入数据库
public function insert(){
$rs = D("Slide");
if ($rs->create()) {
if ( false !== $rs->add() ) {
redirect('?s=Admin-Slide-Show');
}else{
$this->error('添加幻灯失败');
}
}else{
$this->error($rs->getError());
}
}
// 更新幻灯片
public function update(){
$rs = D("Slide");
if ($rs->create()) {
$list = $rs->save();
if ($list !== false) {
redirect('?s=Admin-Slide-Show');
}else{
$this->error("更新幻灯失败!");
}
}else{
$this->error($rs->getError());
}
}
// 隐藏与显示幻灯
public function status(){
$where['slide_id'] = $_GET['id'];
$rs = D("Slide");
if (intval($_GET['sid'])) {
$rs->where($where)->setField('slide_status',1);
}else{
$rs->where($where)->setField('slide_status',0);
}
$this->redirect('Admin-Slide/Show');
}
// 删除幻灯片
public function del(){
$rs = D("Slide");
$where['slide_id'] = $_GET['id'];
$rs->where($where)->delete();
$this->redirect('Admin-Slide/Show');
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/SlideAction.class.php | PHP | asf20 | 2,230 |
<?php
class CacheAction extends BaseAction{
//缓存管理列表
public function show(){
$this->display('./Public/system/cache_show.html');
}
//清除系统缓存AJAX
public function del(){
import("ORG.Io.Dir");
$dir = new Dir;
$this->ppvod_list();
@unlink('./Runtime/~app.php');
@unlink('./Runtime/~runtime.php');
if(!$dir->isEmpty('./Runtime/Data/_fields')){$dir->del('./Runtime/Data/_fields');}
if(!$dir->isEmpty('./Runtime/Temp')){$dir->delDir('./Runtime/Temp');}
if(!$dir->isEmpty('./Runtime/Cache')){$dir->delDir('./Runtime/Cache');}
if(!$dir->isEmpty('./Runtime/Logs')){$dir->delDir('./Runtime/Logs');}
echo('清除成功');
}
// 删除静态缓存
public function delhtml(){
$id = $_GET['id'];
import("ORG.Io.Dir");
$dir = new Dir;
if('index' == $id){
@unlink(HTML_PATH.'index'.C('html_file_suffix'));
}elseif('vodlist'== $id){
if(is_dir(HTML_PATH.'Vod_show')){$dir->delDir(HTML_PATH.'Vod_show');}
}elseif('vodread' == $id){
if(is_dir(HTML_PATH.'Vod_read')){$dir->delDir(HTML_PATH.'Vod_read');}
}elseif('vodplay' == $id){
if(is_dir(HTML_PATH.'Vod_play')){$dir->delDir(HTML_PATH.'Vod_play');}
}elseif('newslist' == $id){
if(is_dir(HTML_PATH.'News_show')){$dir->delDir(HTML_PATH.'News_show');}
}elseif('newsread' == $id){
if(is_dir(HTML_PATH.'News_read')){$dir->delDir(HTML_PATH.'News_read');}
}elseif('ajax' == $id){
if(is_dir(HTML_PATH.'Ajax_show')){$dir->delDir(HTML_PATH.'Ajax_show');}
}elseif('day' == $id){
$this->delhtml_day();
}else{
@unlink(HTML_PATH.'index'.C('html_file_suffix'));
if(is_dir(HTML_PATH.'Vod_show')){$dir->delDir(HTML_PATH.'Vod_show');}
if(is_dir(HTML_PATH.'Vod_read')){$dir->delDir(HTML_PATH.'Vod_read');}
if(is_dir(HTML_PATH.'Vod_play')){$dir->delDir(HTML_PATH.'Vod_play');}
if(is_dir(HTML_PATH.'News_show')){$dir->delDir(HTML_PATH.'News_show');}
if(is_dir(HTML_PATH.'News_read')){$dir->delDir(HTML_PATH.'News_read');}
if(is_dir(HTML_PATH.'Ajax_show')){$dir->delDir(HTML_PATH.'Ajax_show');}
}
echo('清除成功');
}
//清理当天静态缓存文件
public function delhtml_day(){
$where = array();
$where['vod_addtime']= array('gt',getxtime(1));
$rs = D("Vod");
$array = $rs->field('vod_id')->where($where)->order('vod_id desc')->select();
if($array){
foreach($array as $key=>$val){
$id = md5($array[$key]['vod_id']).C('html_file_suffix');
@unlink('./Html/Vod_read/'.$id);
@unlink('./Html/Vod_play/'.$id);
}
import("ORG.Io.Dir");
$dir = new Dir;
if(!$dir->isEmpty('./Html/Vod_show')){$dir->delDir('./Html/Vod_show');}
if(!$dir->isEmpty('./Html/Ajax_show')){$dir->delDir('./Html/Ajax_show');}
@unlink('./Html/index'.C('html_file_suffix'));
}
echo('清除成功');
}
//清空所有数据缓存
public function dataclear(){
if(C('data_cache_type') == 'memcache'){
$cache = Cache::getInstance();
$cache->clear();
}else{
import("ORG.Io.Dir");
$dir = new Dir;
if(!$dir->isEmpty(TEMP_PATH)){
$dir->delDir(TEMP_PATH);
}
}
echo('清除成功');
}
//循环标签调用
public function dataforeach(){
$config_old = require './Runtime/Conf/config.php';
$config_new = array_merge($config_old, array('data_cache_foreach'=>uniqid()) );
arr2file('./Runtime/Conf/config.php',$config_new);
@unlink('./Runtime/~app.php');
echo('清除成功');
}
//当天视频
public function datadayvod(){
$where = array();
$where['vod_addtime']= array('gt',getxtime(1));
$rs = M("Vod");
$array = $rs->field('vod_id')->where($where)->order('vod_id desc')->select();
foreach($array as $key=>$val){
S('data_cache_vod_'.$val['vod_id'],NULL);
}
echo('清除成功');
}
//当天新闻
public function datadaynews(){
$where = array();
$where['news_addtime']= array('gt',getxtime(1));
$rs = M("News");
$array = $rs->field('news_id')->where($where)->order('news_id desc')->select();
foreach($array as $key=>$val){
S('data_cache_news_'.$val['news_id'],NULL);
}
echo('清除成功');
}
//当天专题
public function datadayspecial(){
$where = array();
$where['special_addtime']= array('gt',getxtime(1));
$rs = M("Special");
$array = $rs->field('special_id')->where($where)->order('special_id desc')->select();
foreach($array as $key=>$val){
S('data_cache_special_'.$val['special_id'],NULL);
}
echo('清除成功');
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/CacheAction.class.php | PHP | asf20 | 4,637 |
<?php
class CjAction extends BaseAction{
public function show(){
dump('预留功能');
}
// 添加编辑采集节点
public function add(){
dump('预留功能');
exit();
$rs = D("Cj");
$cj_id = intval($_GET['id']);
$cj_mod = trim($_GET['mod']);
$where = array();
if($cj_id){
if(!$cj_mod){
$where['cj_id'] = $cj_id;
$where['cj_pid'] = 0;
$array = $rs->where($where)->find();
dump($array);
}else{
$where['cj_pid'] = $cj_id;
$where['cj_oid'] = array('gt',1);
$list = $rs->where($where)->select();
if($list){
dump($list);
}else{
$array['cj_mod'] = $cj_mod;
}
}
$array['cj_tpltitle'] = '编辑';
}else{
$array['cj_coding'] = 'gbk';
$array['cj_savepic'] = 0;
$array['cj_order'] = 0;
$array['cj_pid'] = 0;
$array['cj_oid'] = 1;
$array['cj_mod'] = 'node';
$array['cj_tpltitle'] = '添加';
}
$this->assign($array);
$this->ppvod_play();
$this->assign('listtree',F('_ppvod/listvod'));
$this->display('./Public/system/cj_add.html');
}
// 添加采集节点数据第一步
public function insert() {
$rs = D("Cj");
if (!$rs->create()) {
$this->error($rs->getError());
}
$cj_id = $rs->add();
if(false !== $cj_id){
redirect('?s=Admin-Cj-Add-id-'.$cj_id.'-oid-2-mod-'.$_POST['cj_nextmod']);
}else{
$this->error('添加采集节点添加出错!');
}
}
// 更新数据库信息
public function update(){
if(empty($_POST['collect_savepic'])){
$_POST['collect_savepic'] = 0;
}
if(empty($_POST['collect_order'])){
$_POST['collect_order'] = 0;
}
$rs = D("Collect");
if($rs->create()){
$id = intval($_POST['collect_id']);
if(false !== $rs->save()){
//F('_collects/id_'.$id,NULL);
//F('_collects/id_'.$id.'_rule',NULL);
//$this->f_replace($_POST['collect_replace'],$id);
$this->assign("jumpUrl",'?s=Admin-Collect-Caiji-ids-'.$id.'-tid-2');
$this->success('采集规则更新成功,测试一下是否能正常采集!');
}else{
$this->error("没有更新任何数据!");
}
}else{
$this->error($rs->getError());
}
}
// 栏目分类转换
public function change(){
$change_content = trim(F('_collect/change'));
$this->assign('change_content',$change_content);
$this->display('./Public/system/cj_change.html');
}
// 栏目分类转换保存
public function changeup(){
F('_collect/change',trim($_POST["content"]));
$array_rule = explode(chr(13),trim($_POST["content"]));
foreach($array_rule as $key => $listvalue){
$arrlist = explode('|',trim($listvalue));
$array[$arrlist[0]] = intval($arrlist[1]);
}
F('_collect/change_array',$array);
$this->assign("jumpUrl",'?s=Admin-Cj-Change');
$this->success('栏目转换规则编辑成功!');
}
}
?> | 0321hy | trunk/Lib/Lib/Action/Admin/CjAction.class.php | PHP | asf20 | 2,895 |