branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>
import enum
class PlayerRelative(enum.IntEnum):
"""The values for the `player_relative` feature layers."""
NONE = 0
SELF = 1
ALLY = 2
NEUTRAL = 3
ENEMY = 4
class FeatureUnit(enum.IntEnum):
"""Indices for the `feature_unit` observations."""
unit_type = 0
alliance = 1
health = 2
shield = 3
energy = 4
cargo_space_taken = 5
build_progress = 6
health_ratio = 7
shield_ratio = 8
energy_ratio = 9
display_type = 10
owner = 11
x = 12
y = 13
facing = 14
radius = 15
cloak = 16
is_selected = 17
is_blip = 18
is_powered = 19
mineral_contents = 20
vespene_contents = 21
cargo_space_max = 22
assigned_harvesters = 23
ideal_harvesters = 24
weapon_cooldown = 25
order_length = 26 # If zero, the unit is idle.
tag = 27 # Unique identifier for a unit (only populated for raw units).
class Observer:
def __init__(self):
pass
def print_obs(self,obs):
"""prints the whole observation from this timestep of the sc2 game"""
print(obs)
def get_total_health(self,obs):
"""returns the total health of all allied units"""
total_health = 0
for unit in obs.observation.raw_units:
if(unit.alliance == PlayerRelative.SELF):
total_health += unit[FeatureUnit.health]
return total_health
def get_center_of_mass_allies(self,obs):
"""returns the x,y of the center of mass for allied units"""
def get_center_of_mass_enemies(self,obs):
"""returns the x,y of the center of mass for the enemy units"""
def get_total_shield(self,obs):
"""returns total shield of allied units"""
def list_all_tags(self,obs):
"""return a list of all tags for all units in the current game"""
def get_unit(self,tag):
"""Takes in a units tag number and returns the unit corresponding
that tag"""
|
0c83b5e912e094d1b6d0bd06f4903a06b6411b43
|
[
"Python"
] | 1
|
Python
|
junkilee/pysc2
|
3a4a095f262826c10ffeea6123fc9b4a145b7563
|
6987c442be20dab92249fd2cbab2a81a12e8588c
|
refs/heads/master
|
<repo_name>tjacobs/cycloid<file_sep>/design/ekf/model.py
import numpy as np
import sympy as sp
import codegen
import os
sp.init_printing()
# Define our model's state variables:
(v, # velocity (m/s)
delta, # steering curvature (1/m) - inverse turning radius
y_error, # lateral distance from centerline; + means car is right of line
psi_error, # car's angle w.r.t. centerline; + means car is facing counterclockwise from line
kappa # kappa is the centreline line curvature (1/m)
) = sp.symbols("v, delta, y_error, psi_error, kappa", real=True)
(ml_1, ml_2, ml_3, # log of brushless motor model constants
ml_4, # log of static friction constant
srv_a, srv_b, srv_r, # servo response model; delta -> srv_a * control + srv_b at rate srv_r
srvfb_a, srvfb_b, # servo feedback measurement = srvfb_a * delta + srvfb_b
o_g # gyroscope offset; gyro measures v * delta + o_g
) = sp.symbols("ml_1, ml_2, ml_3, ml_4, srv_a, srv_b, srv_r, srvfb_a, srvfb_b, o_g", real=True)
# dt, steering input, motor input
(Delta_t, # time between prediction updates
u_delta, # control input for steering
u_M # control input for motor (assumed PWM controlled brushless)
) = sp.symbols("Delta_t u_delta u_M", real=True)
# State vector x is all of the above
X = sp.Matrix([v, delta, y_error, psi_error, kappa,
ml_1, ml_2, ml_3, ml_4,
srv_a, srv_b, srv_r, srvfb_a, srvfb_b, o_g])
# Print
print "State variables:"
sp.pprint(X.T)
# Gen
ekfgen = codegen.EKFGen(X)
# Define a default initial state
x0 = np.float32([
# v, delta, y_error, psi_error, kappa
0, 0, 0, 0, 0,
# ml_1 (log m/s^2)
2.7,
# ml_2 (log 1/s)
1.05,
# ml_3, ml_4 (log m/s^2 static frictional deceleration)
2.0, -0.65,
# srv_a, srv_b, srv_r,
-1.4, 0.2, 3.8,
# srvfb_a, srvfb_b
-35, 125,
# o_g
0])
# And covariance
P0 = np.float32([
# v, delta, y_error, psi_error, kappa
# assume we start stationary
0.001, 0.1, 2, 1, 0.4,
# ml_1, ml_2, ml_3, ml_4
0.2, 0.2, 4, 0.5,
# srv_a, srv_b, srv_r
0.5, 0.5, 0.5,
# srvfb_a, srvfb_b
100, 100,
# o_g
1])**2
try:
os.mkdir("out_cc")
except:
pass
try:
os.mkdir("out_py")
except:
pass
ekfgen.open("out_cc", "out_py", sp.Matrix(x0), sp.Matrix(P0))
# The motor model has three components:
# The electronic speed controller is really just a voltage source
# and a PWM-controlled electronic switch which either applies a voltage
# to the motor in pulses (when input control signal is positive),
# or shorts the motor out in pulses (when it is negative).
# The motor is also always slowed down by friction.
# The car's acceleration is proportional to the torque produced by the motor,
# so we fold the inertia into the system constants. The car's acceleration is
# thus:
# k1 * u_V * u_DC - k2 * u_DC * v - k3*(static?) - k4
# where u_V is the control voltage signal (assumed 1 or 0) and u_DC is the
# duty cycle control input (from 0 to 1) and v is the current velocity.
# The ESC takes a positive or negative u_M control input which is transformed
# to u_DC and u_V here first.
# Since k1, k2, k3, and k4 are scale constants, we keep them as logarithms in
# the model. That way they can never go negative, and we avoid huge derivatives
# when the relative scales are very different. This can, however, blow up to
# huge values if we're not carefully managing measurement and process noise.
# units:
# k1: m/s^2 / V (acceleration per volt)
# k2: 1/s (EMF decay time constant)
# k3: m/s^2 (coulomb friction, minimum torque to get moving)
# k4: m/s^2 (dynamic friction)
k1, k2, k3, k4 = sp.exp(ml_1), sp.exp(ml_2), sp.exp(ml_3), sp.exp(ml_4)
# Define user voltage
u_DC = sp.Abs(u_M)
u_V = sp.Heaviside(u_M) # 1 if u_M > 0, else 0
# The static friction coefficient tries to make the velocity exactly 0, up to the friction limit
k3 = k3 * sp.Heaviside(0.2 - v) # k3 applies only when v < 0.2
dv = Delta_t*(u_V * u_DC * k1 - u_DC * v * k2 - k3 - k4)
dv = sp.Max(dv, -v) # velocity cannot go negative
av = v + dv / 2 # average velocity during the timestep
# The servo has its own control loop and position feedback built in, but
# we need to model how it relates to the car's actual rotation, so the
# "servo" constants here also encompass the steering geometry of the car.
# We assume here that the servo linearly moves to the desired position, with
# a certain ratio (srv_a) between control input and turning curvature (1/radius),
# a certain offset (srv_b) when the control signal is 0, and a linear moving rate srv_r.
# The math for this is kind of messy; the code would be simpler as some if
# statements, but this needs to be a differentiable function.
ddelta = sp.Min(Delta_t * srv_r, sp.Abs(srv_a * u_delta + srv_b - delta)) * sp.sign(srv_a * u_delta + srv_b - delta)
# The state transition kinematics equations are based on a curvilinear unicycle model.
f = sp.Matrix([
v + dv,
delta + ddelta,
y_error - Delta_t * av * sp.sin(psi_error),
psi_error + Delta_t * av * (-delta + kappa * sp.cos(psi_error) / (1 - kappa * y_error)),
kappa,
ml_1,
ml_2,
ml_3,
ml_4,
srv_a,
srv_b,
srv_r,
srvfb_a,
srvfb_b,
o_g
])
# Print
print "State transition function: x +="
sp.pprint(f - X)
# Q Process noise needs tuning.
Q = sp.Matrix([
# v, delta, y_error, psi_error, kappa
2, 0.7, 0.1*v + 1e-3, 0.15*v + 1e-3, 0.75*v + 1e-3,
# ml_1, ml_2, ml_3, ml_4
0, 0, 0, 0,
# srv_a, srv_b, srv_r
0, 0, 0,
# srvfb_a, srvfb_b
0, 0,
# o_g gyro
1e-3])
# Generate the prediction code. Motor speed and steering are inputs, along with f, process noise, and delta_t time.
ekfgen.generate_predict(f, sp.Matrix([u_M, u_delta]), Q, Delta_t)
# Now define the measurement models.
# First we measure the road centerline's position, angle, and curvature with
# our camera / image processing pipeline. The result of that is a quadratic
# regression equation ax^2 + bx + c, and a quadratic fit covariance Rk also
# comes from our image processing pipeline.
def centerline_derivation():
# Make the symbols
a, b, c, yc, t = sp.symbols("a b c y_c t", real=True)
# Z is the processed values from camera measurement
z_k = sp.Matrix([a, b, c, yc])
# And yc is the center of the original datapoints, where our regression should
# have the least amount of error. We will measure the centerline curvature
# (kappa) and angle (psi_error) at this point, and then compute y_error as our
# perpendicular distance to that line. Simples.
#
# /
# psi_error /
# & kappa -> |___| <- y_error
# at yc |
# \
# \
# The regression line is x = a*y^2 + b*y^1 + c
xc = a*yc**2 + b*yc + c
dx = sp.diff(xc, yc)
dxx = sp.diff(dx, yc)
kappa_est = dxx / ((dx**2 + 1)**(1.5)) # Curvature at yc
pc = sp.Matrix([xc, yc]) # regression center on curve
N = sp.Matrix([-1, dx]) # N is a vector normal to the curve
Nnorm = sp.sqrt((N.T * N)[0]) # length of normal
# If curvature is low, assume we have a straight line; project our
# regression centerpoint onto the unit normal vector to determine distance
# to centerline, and tan(psi_e) = dx/dy = dx/1
ye_linear_est = (N.T * pc)[0] / Nnorm
tanpsi_linear_est = dx
h_x = sp.Matrix([y_error, psi_error, kappa])
h_z = sp.Matrix([
ye_linear_est,
sp.atan(tanpsi_linear_est),
kappa_est
])
return h_x, h_z, z_k
# Centreline
h_x_centerline, h_z_centerline, z_k_centerline = centerline_derivation()
ekfgen.generate_measurement( "centerline", h_x_centerline, h_z_centerline, z_k_centerline, sp.symbols("R_k"))
# Delta is backwards from yaw rate, so negative here
h_imu = sp.Matrix([-v * delta + o_g])
# Gyro IMU
g_z = sp.symbols("g_z")
h_gyro = sp.Matrix([g_z])
R_gyro = sp.Matrix([0.1])
ekfgen.generate_measurement("IMU", h_imu, h_gyro, h_gyro, R_gyro)
# Generate measurement for encoders
METERS_PER_ENCODER_TICK = np.pi * 0.101 / 20
dsdt, fb_delta = sp.symbols("dsdt fb_delta")
h_z_encoders = sp.Matrix([dsdt, fb_delta])
h_x_encoders = sp.Matrix([v / METERS_PER_ENCODER_TICK, srvfb_b + delta * srvfb_a])
R_encoders = sp.Matrix([120, 7])
ekfgen.generate_measurement("encoders", h_x_encoders, h_z_encoders, h_z_encoders, R_encoders)
# Save
ekfgen.close()
<file_sep>/design/ekf/ekftest.py
import numpy as np
import ekf
def ekf_test():
x, P = ekf.initial_state()
# Slow
for u in np.linspace(0, 0.2, 10):
x, P = ekf.predict(x, P, 0.0625, u, 0) # Delta_t (1/16th second), motor speed, no steering
print("Small acceleration: ", u, x[0])
# GO!
for u in np.linspace(0.8, 1.0, 3):
x, P = ekf.predict(x, P, 0.0625, u, 0) # Delta_t (1/16th second), motor speed, no steering
print("Acceleration: ", u, x[0])
# STOP!
x, P = ekf.predict(x, P, 0.0625, -1, 0)
x, P = ekf.predict(x, P, 0.0625, -1, 0)
print('Full brake 2 frames:', x[0])
# Coast
for i in range(10):
x, P = ekf.predict(x, P, 0.0625, -1, 0)
print(x[0])
print('After 10 frames of coasting: ', x[0])
# x, P = ekf.update_centerline(x, P, 0, 0.01, 0.1, np.eye(3) * 0.1)
print(x)
if __name__ == '__main__':
ekf_test()
<file_sep>/src/drive/CMakeLists.txt
add_executable(drive drive.cc imgproc.cc controller.cc ekf.cc)
target_link_libraries(drive car cam mmal input gpio imu ui lcd)
|
7d65226e109fddf9bddd70bffba7060cb7097b8c
|
[
"Python",
"CMake"
] | 3
|
Python
|
tjacobs/cycloid
|
39be2f2e2f45e2bd25b353ce273df0088b96807e
|
3e8b3d4a4cf8450a92df90088406752a3bc9e18e
|
refs/heads/main
|
<repo_name>putriisnaaaa/projectpengcit<file_sep>/filter.py
import cv2
face = cv2.CascadeClassifier('face_detector.xml')
filename='efekisna.jpeg'
img=cv2.imread(filename)
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
fl=face.detectMultiScale(gray,1.09,7)
ey=face.detectMultiScale(gray,1.09,7)
hat=cv2.imread('crownisna.png')
glass=cv2.imread('glassisna.jpeg')
def put_hat(hat, fc, x, y, w, h):
face_width = w
face_height = h
hat_width = face_width + 1
hat_height = int(0.50 * face_height) + 1
hat = cv2.resize(hat, (hat_width, hat_height))
for i in range(hat_height):
for j in range(hat_width):
for k in range(3):
if hat[i][j][k] < 235:
fc[y + i - int(0.40 * face_height)][x + j][k] = hat[i][j][k]
return fc
def put_glass(glass, fc, x, y, w, h):
face_width = w
face_height = h
hat_width = face_width + 1
hat_height = int(0.50 * face_height) + 1
glass = cv2.resize(glass, (hat_width, hat_height))
for i in range(hat_height):
for j in range(hat_width):
for k in range(3):
if glass[i][j][k] < 235:
fc[y + i - int(-0.20 * face_height)][x + j][k] = glass[i][j][k]
return fc
for (x, y, w, h) in fl:
frame = put_hat(hat, img, x, y, w, h)
for (x, y, w, h) in ey:
frame=put_glass(glass,img, x, y, w, h)
# img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.imshow('image',frame)
cv2.waitKey(8000)& 0xff
cv2.destroyAllWindows()<file_sep>/DeteksiWajah.py
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier("face_detector.xml")
#Untuk memasukkan file
img = cv2.imread("isna.jpeg")
detections = face_cascade.detectMultiScale(img, scaleFactor=1.1, minNeighbors=6)
for face in detections :
x,y,w,h = face
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
cv2.imshow("Hasil Deteksi Wajah", img)
cv2.waitKey(0)
|
8968a2c243cf6646e7882479bdc61694d8f0a98e
|
[
"Python"
] | 2
|
Python
|
putriisnaaaa/projectpengcit
|
31f5ae023a374a4ad28dd1b088cc532f4b4c549c
|
897d7b31c2ee574b26937982c292f9f15d779e3c
|
refs/heads/main
|
<file_sep>var algo = document.querySelector(".algo");
var gameBox = document.querySelector(".game");
var gameBoxRect = gameBox.getBoundingClientRect();
var width = gameBoxRect.width;
var height = gameBoxRect.height;
var algoRect = algo.getBoundingClientRect();
var algoWidth = algo.width;
var algoHeight = algo.height;
console.log(algoWidth, algoHeight);
var algoPosition = [0, 0];
function tick() {
// обновить игровое поле
algoPosition[0] = Math.random() * (width - algoWidth);
algoPosition[1] = Math.random() * (height - algoHeight);
algo.style.transform =
"translate(" + algoPosition[0] + "px, " + algoPosition[1] + "px)";
}
setInterval(tick, 100);
|
f5f15f4e2b173d3063da62f077bfb9ddb72abed1
|
[
"JavaScript"
] | 1
|
JavaScript
|
razdvapoka/Catch-The-Algorithm
|
bf73c92e964a8d6a21afdc66c37be97716c26847
|
a4d84d43550a77b201f83741843bad2ed02a257e
|
refs/heads/master
|
<repo_name>SapirWeissbuch/chatproject<file_sep>/client.py
#============================================================================================== #
# @file : client.py
# @purpose: client class for internet messaging interface.
# @author : <NAME>
# @date : 27/11/2018
# ============================================================================================== #
# == IMPORTS =================================================================================== #
import socket
import datetime
import threading
import select
# == CONSTANTS ================================================================================= #
protocol = "{chat}###{username}###{hour}###{message}"
# == CLASSES =================================================================================== #
class Client(object):
"""
client class for internet messaging
"""
def __init__(self, host, port):
self.username = ""
self.current_chat = ""
self.chat_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# thread for receiving data from server
self.receive_server_thread = threading.Thread(target=self.receive_from_server)
self.receive_server_thread.daemon = True
# lock to protect the socket
self.socket_lock = threading.Lock()
# i want to recieve input one thread at a time
self.input_lock = threading.Lock()
# connecting the socket
self.chat_socket.connect((host, port))
def _input_format(self, command):
"""formatting the input in order to send to server
arg = command
type = str
rtype = str
"""
if command[0] == '@':
return protocol.format(chat="&"+self.current_chat+"&", username=self.username, hour=datetime.datetime.now(), message=command)
else:
return protocol.format(chat="&&", username=self.username, hour=datetime.datetime.now(), message=command)
def run(self):
"""
recieves input from user and sends it to server.
"""
# getting username until entering one that doesn't exist.
self.username = self.enter_name()
# initiating the receving thread
self.receive_server_thread.start()
print("Enter messages or commands: ")
while True:
with self.input_lock:
input1 = raw_input("Input: ")
command = self._input_format(input1)
with self.socket_lock:
self.chat_socket.sendall(command)
def receive_from_server(self):
"""
receiving messages from the server and printing them
"""
while True:
readable, _, _ = select.select([self.chat_socket], [], [])
if self.chat_socket in readable:
with self.socket_lock:
data = self.chat_socket.recv(5000)
print(data)
def enter_name(self):
"""
getting username from user until it doesn't exist.
returns the final name.
:return name
:rtype str
"""
name = raw_input("Enter name: ")
self.chat_socket.sendall(name)
name_check = self.chat_socket.recv(50000)
while name_check == "N":
name = raw_input("Enter name again: ")
self.chat_socket.sendall(name)
name_check = self.chat_socket.recv(50000)
return name
def __del__(self):
"""
closing the listening socket.
"""
self.chat_socket.send("")
self.chat_socket.close()
print('disconnected from server')<file_sep>/README.md
# chatproject
a simple python beginner chat interface
<file_sep>/server_user.py
#============================================================================================== #
# @file : server_classes.py
# @purpose: classes needed for sever code in chat interface project.
# @author : <NAME>
# @date : 28/11/2018
# ============================================================================================== #
# == IMPORTS =================================================================================== #
import server_chat
# == CONSTANTS ================================================================================= #
PROTOCOL = "###[chat]###[username]###[hour]###[message]"
MES_FORMAT = "[time] - [name] - [mes]"
# == CLASSES =================================================================================== #
class User(object):
"""
a class representing the user.
"""
def __init__(self, username, conn):
self.username = username
self.current_chat = None
self.connection_socket = conn
def join(self, chat):
"""
adding the user to a chat.
arg: chat
type: dict object
"""
if self.current_chat is not None:
self.connection_socket.sendall("Can't start a chat while already in a chat.")
else:
# add chat to user
self.current_chat = chat
# add user to chat
chat.users.update({self.username: self})
def contact(self, second_user):
"""
creating a private chat with second_user
:param second_user:
type: user object
:return:
"""
if self.current_chat is not None:
self.connection_socket.sendall("Can't start a chat while already in a chat.")
elif second_user.current_chat is not None:
self.connection_socket.sendall("User not available for chat.")
else:
self.current_chat = server_chat.Chat("&"+second_user.username+"&")
self.current_chat.mode = "private"
second_user.current_chat = self.current_chat
second_user.connection_socket.sendall("Now connected to " + self.username)
self.current_chat.users.update({self.username: self, second_user.username: second_user})
def leave(self):
"""
leaving current chat
:return:
"""
del self.current_chat.users[self.username]
self.current_chat = None
def __del__(self):
"""
closing user sockets when it is deleted
"""
self.connection_socket.close()
print "disconnected from []".format(self.username)<file_sep>/server_chat.py
#============================================================================================== #
# @file : server_classes.py
# @purpose: classes needed for sever code in chat interface project.
# @author : <NAME>
# @date : 28/11/2018
# ============================================================================================== #
# == IMPORTS =================================================================================== #
import server_user
# == CONSTANTS ================================================================================= #
PROTOCOL = "[chat]###[username]###[hour]###[message]"
MES_FORMAT = "[time] - [name] - [mes]"
# == CLASSES =================================================================================== #
class Chat(object):
"""
a class representing a chat.
"""
def __init__(self, chatname):
self.chatname = chatname
self.users = {}
self.mode = "public" # or private
def send(self, message):
"""
receives formatted message and sends it to all members of the chat.
arg: message
type: str
"""
for username in self.users:
self.users[username].connection_socket.sendall(message)
<file_sep>/server.py
#============================================================================================== #
# @file : server_classes.py
# @purpose: classes needed for sever code in chat interface project.
# @author : <NAME>
# @date : 28/11/2018
# ============================================================================================== #
# == IMPORTS =================================================================================== #
import socket
import select
import server_chat
import server_user
# == CONSTANTS ================================================================================= #
PROTOCOL = "###[chat]###[username]###[hour]###[message]"
MES_FORMAT = "[{time}] - [{name}] - [{mes}]"
# == CLASSES =================================================================================== #
class Server(object):
"""
server class for chat interface.
"""
def __init__(self):
# chat name: chat object
self.chats = {}
# user name: user object
self.users = {}
self.listening_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def run(self, host, port):
"""
connecting users and receiving messages from them.
arg: host
type: str
arg: port
type: str
"""
self.listening_socket.bind((host, port))
self.listening_socket.listen(10)
self.sockets_list = [self.listening_socket]
while True:
readable, _, _ = select.select(self.sockets_list, [], [])
for sock in readable:
if self.listening_socket is sock:
conn, _ = self.listening_socket.accept()
self.sockets_list.append(conn)
while True:
name = conn.recv(2 ** 16)
if name in self.users:
conn.sendall("N")
else:
conn.sendall("Y")
self.users.update({name: server_user.User(name, conn)})
break
else:
try:
user_input = sock.recv(2**16)
self.user_input_processor(user_input)
except:
self.user_disconnected(sock)
def user_disconnected(self, sock):
"""
when user disconnected searches for the user and deletes it from server and chat lists.
:param sock:
type: socket object
"""
to_delete_username = ""
for username, userobject in self.users.iteritems():
# checks if this is the disconnected socket:
if userobject.connection_socket == sock:
to_delete_username = username
# deleting user from current chat if exists:
if to_delete_username != "":
if self.users[to_delete_username].current_chat is not None:
del self.users[to_delete_username].current_chat.users[to_delete_username]
# deleting user from server's user list:
del self.users[to_delete_username]
self.sockets_list.remove(sock)
sock.close()
print "disconnected from " + to_delete_username
def user_input_processor(self, user_input):
"""
gets user input from run and calls the required functions
arg: user_input
type: str
"""
input_list = user_input.split("###")
username = input_list[1]
message = input_list[3]
if message[0] == '@':
self.command_processor(input_list)
else:
# it means that this is a message.
if self.users[username].current_chat is None:
self.users[username].connection_socket.sendall("\nNot connected to a chat")
else:
final_message = MES_FORMAT.format(name=username, time=input_list[2], mes=message)
self.users[username].current_chat.send(final_message)
def command_processor(self, input_list):
"""
gets a command (@join/@leave/@contact/@create) from user and excecutes it using funcitons.
arg: input_list
type: list
arg: current_username
type: str
"""
user_name = input_list[1]
message = input_list[3]
command_end_index = message.find(" ")
# extraction of the command itself (join/leave/contact/create)
if command_end_index == -1:
command = message[1:]
else:
command = message[1:command_end_index]
# extraction of the commands details (name of chat or contact or None)
details = message[command_end_index+1:]
# a dictionary with the possible commands and the matching functions:
if command == "join":
self.users[user_name].join(self.chats[details])
elif command == "leave":
self.users[user_name].leave()
self.del_empty_chats
elif command == "contact":
self.users[user_name].contact(self.users[details])
elif command == "create":
self.create_chat(details, self.users[user_name])
elif command == "showusers":
self.show_users(user_name)
elif command == "showchats":
self.show_chats(user_name)
"""
meaning of commands:
@join: joining a public chat
@leave: leaving a chat
@contact: starting a private chat with a user
@create: creating a new public cha
"""
def create_chat(self, chatname, first_user):
"""
creates a chat with the first user in it.
:param chatname: type: str
:param first_user: type: user object
:return:
"""
if first_user.current_chat is not None:
self.connection_socket.sendall("Can't start a chat while already in a chat.")
else:
new_chat = server_chat.Chat(chatname)
self.chats.update({chatname: new_chat})
first_user.join(new_chat)
def del_empty_chats(self):
"""
checks for empty chats and deletes them.
"""
for chatname,chat_object in self.chats.iteritems():
if len(chat_object.users) == 0:
# deleting the chat from the servers chats list
del self.chats[chatname]
def show_users(self, username):
"""
sends the list of people to the user.
:param username:
:type str:
:return:
"""
users_list = ["{"+i+"}" for i in self.users.iterkeys() if i != username and self.users[i].current_chat is None]
output = " ".join(users_list)
if output == "":
self.users[username].connection_socket.sendall("No users")
else:
self.users[username].connection_socket.sendall(output)
def show_chats(self, username):
"""
sends the list of chats to the user.
:param username:
:type str:
:return:
"""
chats_list = ["{"+i+"}" for i in self.chats.iterkeys() if self.chats[i].mode == "public"]
output = " ".join(chats_list)
if output == "":
self.users[username].connection_socket.sendall("No chats")
else:
self.users[username].connection_socket.sendall(output)
def __del__(self):
"""
closing the listening socket.
"""
self.listening_socket.close()
print "server socket disconnected"
|
3466710756fe67afc3c3d5d4fa199be80f8a2023
|
[
"Markdown",
"Python"
] | 5
|
Python
|
SapirWeissbuch/chatproject
|
1701a6b34283698f19afd5c4b33aa6fdd06e298a
|
78686edc7254fb26c558249a13873a0b009a9132
|
refs/heads/main
|
<repo_name>chattyy/PreHandleTweet<file_sep>/PreHandleTweet/__init__.py
from PreHandleTweet.ProcessTweet import process_tweet,build_freqs
|
f9748e2bf27fe7854aa8d7e7146dd36815936e74
|
[
"Python"
] | 1
|
Python
|
chattyy/PreHandleTweet
|
9ba773a5b2c6925df9ee1475e23c9327ef1daf58
|
88ba9717789238f2d3c0b442a876a729633a4a4e
|
refs/heads/master
|
<file_sep>
<?php
// database connection
// localhost user name and password and last parameter is for database name.
$db = mysqli_connect("htl-server.com","martinadodsql1","Marti@133","martinadodsql1");
// data von database bekommen
$q = mysqli_query($db, "SELECT name, value FROM pie_chart");
if($q){
$chart_data[] = ["stunde", "value"];
while($pie_data = mysqli_fetch_assoc($q)){
settype($pie_data["value"], "int");
$chart_data [] = [$pie_data["name"], $pie_data["value"]];
}
echo json_encode($chart_data);
}else{
echo "Fail".mysqli_error();
}
?>
<file_sep>
<?php
// database connection
// localhost user name and password and last parameter is for database name.
$db = mysqli_connect("htl-server.com","martinadodsql1","Marti@133","martinadodsql1");
// data von database bekommen
$q = mysqli_query($db, "SELECT name, value FROM pie_chart");
if($q){
$chart_data[] = ["stunde", "value"];
while($pie_data = mysqli_fetch_assoc($q)){
settype($pie_data["value"], "int");
$chart_data [] = [$pie_data["name"], $pie_data["value"]];
}
echo json_encode($chart_data);
}else{
echo "Fail".mysqli_error();
}
?>
<html>
<head>
<style>
.chart {
width: 100%;
min-height: 450px;
}
</style>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- <script src="https://www.google.com/jsapi"></script>--->
<script type="text/javascript">
//Draw Multiple Charts on One Page
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
//Ich brauche ein wenig Hilfe PHP-Daten in Google-Charts zu setzen.
//Ich habe ein einfaches Array erstellt
var data = google.visualization.arrayToDataTable( <?php echo json_encode($chart_data); ?> );
var options = {
title: 'feuchigkeit',
is3D: true
};
//eine pie chart hinzufuegen
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
// Graph neu zeichnen, wenn die Fenstergrößenänderung abgeschlossen ist
$(window).resize(function(){
drawChart();
});
</script>
</head>
<body>
</body>
</html>
<file_sep># 4ay_test
Repository zum Testen
|
180525a37de866b0a493c4e6b818c875c79cab7f
|
[
"Markdown",
"PHP"
] | 3
|
PHP
|
martinadodmasej/4ay_test
|
8676985a833cb56ba673078009fac52e65c4012c
|
59dee4bb702de8614d874405e2a62436546c5dac
|
refs/heads/master
|
<repo_name>ghigbie/DeveloperHealthPlusVersion2<file_sep>/app/src/main/java/com/geogehigbie/developerhealthplusversion2/fragments/pre_exercsie_fragments/DayChooserFragment.java
package com.geogehigbie.developerhealthplusversion2.fragments.pre_exercsie_fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
import com.geogehigbie.developerhealthplusversion2.R;
import java.util.ArrayList;
public class DayChooserFragment extends Fragment {
private View view;
private int notificationTime;
boolean [] daysActive;
ArrayList<String> daysActiveStringArrayList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_day_chooser, container, false);
Bundle bundle = this.getArguments();
if( bundle != null){
notificationTime = bundle.getInt("notificationTime", notificationTime);
}
return view;
}
public void setOnClickListener(){
boolean isMonday = false;
boolean isTuesday = false;
boolean isWednesday = false;
boolean isThursday = false;
boolean isFriday = false;
boolean isSaturday = false;
boolean isSunday = false;
daysActive = new boolean[]{isMonday, isTuesday, isWednesday, isThursday, isFriday, isSaturday, isSunday};
int numberTrue = 0;
CheckBox checkBoxMonday = (CheckBox) view.findViewById(R.id.monday);
CheckBox checkBoxTuesday = (CheckBox) view.findViewById(R.id.tuesday);
CheckBox checkBoxWednesday = (CheckBox) view.findViewById(R.id.wednesday);
CheckBox checkBoxThursday = (CheckBox) view.findViewById(R.id.thursday);
CheckBox checkBoxFriday = (CheckBox) view.findViewById(R.id.friday);
CheckBox checkBoxSaturday = (CheckBox) view.findViewById(R.id.saturday);
CheckBox checkBoxSunday = (CheckBox) view.findViewById(R.id.sunday);
ArrayList<CheckBox> checkBoxes = new ArrayList<CheckBox>();
checkBoxes.add(checkBoxMonday);
checkBoxes.add(checkBoxTuesday);
checkBoxes.add(checkBoxWednesday);
checkBoxes.add(checkBoxThursday);
checkBoxes.add(checkBoxFriday);
checkBoxes.add(checkBoxSaturday);
checkBoxes.add(checkBoxSunday);
for(int i = 0; i < checkBoxes.size(); i++){
if (checkBoxes.get(i).isChecked()) {
numberTrue++;
daysActive[i] = true; //adds values to boolean array if they are checked
daysActiveStringArrayList.add(checkBoxes.get(i).getText().toString()); //adds strings to array list if checked
}
}
//The idea of the above for loop is that the if the boxes are checked, their respective boolean values
//will be added to an array and their respective String objects will be added to a string arrray list.
//All of the values will then be passed to the next fragment, and then be stored in shared preferences file
Button button = (Button) view.findViewById(R.id.next_button_day_Chooser);
if(numberTrue > 0) {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}else{
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity().getApplicationContext(),
"Are you sure that you do not want to make a selection?", Toast.LENGTH_SHORT).show();
Button buttonInner = (Button) view.findViewById(R.id.next_button_day_Chooser);
buttonInner.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SelectionPageFragment selectionPageFragment = new SelectionPageFragment();
Bundle bundle = new Bundle();
bundle.putInt("notificationTime", notificationTime);
bundle.putBooleanArray("daysActive", daysActive);
bundle.putStringArrayList("daysActiveStringArrayList", daysActiveStringArrayList);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, selectionPageFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
}
});
}
}
}
<file_sep>/app/src/main/java/com/geogehigbie/developerhealthplusversion2/fragments/pre_exercsie_fragments/TimeChooserFragment.java
package com.geogehigbie.developerhealthplusversion2.fragments.pre_exercsie_fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.geogehigbie.developerhealthplusversion2.R;
import java.util.ArrayList;
public class TimeChooserFragment extends Fragment {
private View view;
private int notificationTime; //this is the time that will be used to set the notification time
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_time_chooser, container, false);
setSpinnerContent();
// addOnClickListener();
return view;
}
public void setSpinnerContent() {
notificationTime = 0;
final String pleaseChoose = "Please Select a Time";
final String time30String = "30 minutes";
final String time45String = "45 minutes";
final String time60String = "60 minutes";
final String time75String = "1 hour & 15 minutes";
final String time90String = "1 hour & 30 minutes";
final String time105String = "1 hour & 45 minutes";
final String time120String = "2 hours";
String[] timeArrayString = {pleaseChoose, time30String, time45String, time60String, time75String,
time90String, time105String, time120String};
final int time0Int = 0;
final int time30Int = 30;
final int time45Int = 45;
final int time60Int = 60;
final int time75Int = 75;
final int time90Int = 90;
final int time105Int = 105;
final int time120Int = 120;
int[] timeArrayInt = {time0Int, time30Int, time45Int, time60Int, time75Int, time90Int, time105Int, time120Int};
//creates two array lists
ArrayList<String> timeArrayListString = new ArrayList<String>();
ArrayList<Integer> timeArrayListInt = new ArrayList<Integer>();
//adds values to the array lists
for (int i = 0; i < timeArrayString.length; i++) {
timeArrayListString.add(timeArrayString[i]);
timeArrayListInt.add(timeArrayInt[i]);
}
//declares the spinner and uses the adapter to add items
final Spinner spinner1 = (Spinner) view.findViewById(R.id.spinner_time);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), R.layout.spinner_item, timeArrayListString);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
spinner1.setSelection(0);
//gets te time from the spinner
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String timeChoiceString = spinner1.getSelectedItem().toString();
String TAG = "NOTIFICATION TIME SET TO: ";
System.out.println(TAG + " " + timeChoiceString);
//converts the string time to an int
switch (timeChoiceString) {
case pleaseChoose:
notificationTime = time0Int;
Log.d(TAG, "0");
break;
case time30String:
notificationTime = time30Int;
Log.d(TAG, "30");
break;
case time45String:
notificationTime = time45Int;
Log.d(TAG, "45");
break;
case time60String:
notificationTime = time60Int;
Log.d(TAG, "60");
break;
case time75String:
notificationTime = time75Int;
Log.d(TAG, "75");
break;
case time90String:
notificationTime = time90Int;
Log.d(TAG, "90");
break;
case time105String:
notificationTime = time105Int;
Log.d(TAG, "105");
break;
case time120String:
notificationTime = time120Int;
Log.d(TAG, "120");
break;
default:
notificationTime = 0;
Log.d(TAG, timeChoiceString);
break;
}
if (notificationTime != 0) {
makeButtonVisibleAndStoreTime();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void makeButtonVisibleAndStoreTime() {
Button button = (Button) view.findViewById(R.id.time_selected_button);
button.setVisibility(View.VISIBLE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DayChooserFragment dayChooserFragment = new DayChooserFragment();
Bundle bundle = new Bundle();
bundle.putInt("notificationTime", notificationTime);
dayChooserFragment.setArguments(bundle);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, dayChooserFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
// int notificationTimeSetterInt;
//
//
// SharedPreferences notificationTimeSetter = getActivity().getApplicationContext().getSharedPreferences("timeNotificationFile", 0);
// notificationTimeSetterInt = notificationTimeSetter.getInt("notificationTime", notificationTime); //I may not need this
//
// SharedPreferences.Editor editor = notificationTimeSetter.edit();
// editor.putInt("notificationTime", notificationTime);
// editor.putBoolean("isFirstTime", isFirstTime);
// editor.commit();
}
}
<file_sep>/app/src/main/java/com/geogehigbie/developerhealthplusversion2/activities/SplashActivity.java
package com.geogehigbie.developerhealthplusversion2.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
/**
* Created by georgehigbie on 1/30/17.
*/
public class SplashActivity extends Activity {
private boolean firstTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
firstTime = true;
Intent intent;
if(firstTime) {
intent = new Intent(this, MainActivity.class);
}else{
intent = new Intent(this, ExerciseActivity.class);
}
startActivity(intent);
finish();
}
}
<file_sep>/app/src/main/java/com/geogehigbie/developerhealthplusversion2/fragments/exercise_fragments/ExerciseChooserFragment.java
package com.geogehigbie.developerhealthplusversion2.fragments.exercise_fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.geogehigbie.developerhealthplusversion2.R;
public class ExerciseChooserFragment extends Fragment {
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_exercise_chooser, container, false);
setOnClickListeners();
return view;
}
public void setOnClickListeners(){
Button buttonUpper = (Button) view.findViewById(R.id.upper);
Button buttonLower = (Button) view.findViewById(R.id.lower);
Button buttonBoth = (Button) view.findViewById(R.id.both);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
buttonUpper.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container_exercises, new UpperExercisesFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
buttonLower.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container_exercises, new LowerExercisesFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
buttonBoth.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container_exercises, new BothExercisesFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
// fragmentTransaction.addToBackStack(null);
// fragmentTransaction.commit();
}
}
|
6e024306091419f758988ec00825cf22ee5108b6
|
[
"Java"
] | 4
|
Java
|
ghigbie/DeveloperHealthPlusVersion2
|
b559cf69e175f221335f9c8ba74bd4b12ff80e5a
|
073dafa2819227b4630fbd2e3d4a9532d14d7c26
|
refs/heads/master
|
<repo_name>sdavi38/pontoloc-api<file_sep>/__tests__/integration/Contract.spec.ts
import request from 'supertest';
import { Connection, getRepository, getConnection } from 'typeorm';
import { runSeeder } from 'typeorm-seeding';
import Material from '../../src/models/Material';
import ContractItem from '../../src/models/ContractItem';
import Contract from '../../src/models/Contract';
import Client from '../../src/models/Client';
import UserAdminSeed from '../../src/database/seeds/UserAdmin.seed';
import createConnection from '../../src/database';
import getToken from '../utils/getTokenJWT';
import app from '../../src/app';
let connection: Connection;
describe('Contract', () => {
beforeAll(async () => {
connection = await createConnection('test-connection');
await connection.runMigrations();
await runSeeder(UserAdminSeed);
});
afterEach(async () => {
await connection.query('DELETE FROM contracts');
await connection.query('DELETE FROM clients');
await connection.query('DELETE FROM materials');
await connection.query('DELETE FROM contract_items');
});
afterAll(async () => {
await connection.query('DELETE FROM users');
const mainConnection = getConnection();
await connection.close();
await mainConnection.close();
});
describe('Create', () => {
it('should be able to create a new contract', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
const contractsRepository = getRepository(Contract);
const materialsRepository = getRepository(Material);
const material = materialsRepository.create({
name: 'Estronca',
daily_price: 1.4,
});
const client = clientsRepository.create({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
});
const [{ id: material_id }, { id: client_id }] = await Promise.all([
materialsRepository.save(material),
clientsRepository.save(client),
]);
const response = await request(app)
.post('/contracts')
.send({
client_id,
materials: [{ id: material_id, quantity: 2 }],
})
.set('Authorization', `Bearer ${token}`);
const contract = await contractsRepository.findOne({
where: { client_id },
});
expect(contract).toBeTruthy();
expect(response.status).toBe(201);
expect(response.body).toMatchObject(
expect.objectContaining({
id: contract?.id,
daily_total_price: expect.any(Number),
}),
);
});
it('should not be able to craete a new contract for a client does not exists', async () => {
const token = await getToken();
const materialsRepository = getRepository(Material);
const material = materialsRepository.create({
name: 'Estronca',
daily_price: 1.4,
});
const { id: material_id } = await materialsRepository.save(material);
const response = await request(app)
.post('/contracts')
.send({
client_id: 'a820031c-ecaf-4e55-b8f7-11e5a2664f74',
materials: [{ id: material_id, quantity: 2 }],
})
.set('Authorization', `Bearer ${token}`);
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: 'error',
message: 'Client does not exists',
}),
);
});
it('should not be able to create a new contract without materais', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
const client = clientsRepository.create({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
});
await clientsRepository.save(client);
const response = await request(app)
.post('/contracts')
.send({
client_id: client.id,
})
.set('Authorization', `Bearer ${token}`);
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: 'error',
message: 'Materials array is required',
}),
);
});
});
describe('List', () => {
it('should be able to list all contracts', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
const contractsRepository = getRepository(Contract);
const materialsRepository = getRepository(Material);
const contractItemsRepository = getRepository(ContractItem);
const material = materialsRepository.create({
name: 'Estronca',
daily_price: 1.4,
});
const client = clientsRepository.create({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
});
const [{ id: material_id }, { id: client_id }] = await Promise.all([
materialsRepository.save(material),
clientsRepository.save(client),
]);
const contract = contractsRepository.create({
client_id,
delivery_price: 50,
daily_total_price: 5,
});
const newContract = await contractsRepository.save([contract, contract]);
const contractItem = contractItemsRepository.create({
contract_id: newContract[0].id,
material_id,
quantity: 2,
price_quantity_daily: 2.8,
});
await contractItemsRepository.save(contractItem);
const response = await request(app)
.get('/contracts')
.set('Authorization', `Bearer ${token}`);
expect(response.body).toHaveLength(2);
});
it('should be able to list one contract', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
const contractsRepository = getRepository(Contract);
const materialsRepository = getRepository(Material);
const contractItemsRepository = getRepository(ContractItem);
const material = materialsRepository.create({
name: 'Estronca',
daily_price: 1.4,
});
const client = clientsRepository.create({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
});
const [{ id: material_id }, { id: client_id }] = await Promise.all([
materialsRepository.save(material),
clientsRepository.save(client),
]);
const contract = contractsRepository.create({
client_id,
delivery_price: 50,
daily_total_price: 5,
});
const newContract = await contractsRepository.save([contract, contract]);
const contractItem = contractItemsRepository.create({
contract_id: newContract[0].id,
material_id,
quantity: 2,
price_quantity_daily: 2.8,
});
await contractItemsRepository.save(contractItem);
const response = await request(app)
.get(`/contracts/${newContract[0].id}`)
.set('Authorization', `Bearer ${token}`);
expect(response.status).toBe(200);
expect(response.body).toHaveProperty('client');
expect(response.body).toHaveProperty('contract_items');
expect(response.body.contract_items).toBeInstanceOf(Array);
expect(response.body.contract_items[0]).toHaveProperty('material');
});
it('should not be able to list a contract that does not exists', async () => {
const token = await getToken();
const response = await request(app)
.get('/contracts/39b0f3cf-4c83-4bd9-b752-4b22b4d38054')
.set('Authorization', `Bearer ${token}`);
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: 'error',
message: 'Contract does not exists',
}),
);
});
});
describe('Finish', () => {
it('should be able to finish one contract', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
const contractsRepository = getRepository(Contract);
const materialsRepository = getRepository(Material);
const contractItemsRepository = getRepository(ContractItem);
const material = materialsRepository.create({
name: 'Estronca',
daily_price: 1.4,
});
const client = clientsRepository.create({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
});
const [{ id: material_id }, { id: client_id }] = await Promise.all([
materialsRepository.save(material),
clientsRepository.save(client),
]);
const contract = contractsRepository.create({
client_id,
delivery_price: 25,
daily_total_price: 2.8,
});
const newContract = await contractsRepository.save(contract);
const contractItem = contractItemsRepository.create({
contract_id: newContract.id,
material_id,
quantity: 2,
price_quantity_daily: 2.8,
});
await contractItemsRepository.save(contractItem);
const response = await request(app)
.put(`/contracts/${newContract.id}/finish`)
.send({
collect_price: 15,
})
.set('Authorization', `Bearer ${token}`);
const finishedContract = await contractsRepository.findOne(
newContract.id,
);
expect(response.status).toBe(204);
expect(finishedContract?.collect_price).toBe(15);
expect(finishedContract?.collect_at).toBeTruthy();
});
it('should not be able to finish one contract that does not exists', async () => {
const token = await getToken();
const response = await request(app)
.put('/contracts/2ec127f2-23b1-47fc-b6ec-cda50cb3a8ce/finish')
.send({
collect_price: 15,
})
.set('Authorization', `Bearer ${token}`);
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: 'error',
message: 'Contract does not exists',
}),
);
});
});
});
<file_sep>/src/modules/clients/services/SoftDeleteClientService.ts
import { injectable, inject } from 'tsyringe';
import AppError from '@shared/errors/AppError';
import IClientsRepository from '@modules/clients/repositories/IClientsRepository';
interface IRequest {
id: string;
}
@injectable()
class SoftDeleteClientService {
constructor(
@inject('ClientsRepository')
private clientsRepository: IClientsRepository,
) {}
public async execute({ id }: IRequest): Promise<void> {
const client = await this.clientsRepository.findById(id);
if (!client) {
throw new AppError('Client does not exists');
}
await this.clientsRepository.softDeleteById(id);
}
}
export default SoftDeleteClientService;
<file_sep>/src/modules/clients/infra/http/validators/ClientUpdate.ts
import { celebrate, Segments, Joi } from 'celebrate';
export default celebrate({
[Segments.BODY]: Joi.object().keys({
name: Joi.string().required(),
cpf: Joi.string().length(14).required(),
phone_number: Joi.string().min(11).max(16).required(),
address: Joi.string().required(),
}),
});
<file_sep>/src/modules/clients/services/ListClientsService.ts
import { injectable, inject } from 'tsyringe';
import IClientsRepository from '@modules/clients/repositories/IClientsRepository';
import Client from '@modules/clients/infra/typeorm/entities/Client';
interface IRequest {
deleted: boolean;
page: number;
name: string;
}
interface IResponse {
clients: Client[];
count: number;
}
@injectable()
class ListClientsService {
constructor(
@inject('ClientsRepository')
private clientsRepository: IClientsRepository,
) {}
public async execute({ deleted, name, page }: IRequest): Promise<IResponse> {
const {
clients,
count,
} = await this.clientsRepository.findAllWithPaginationAndSearch({
deleted,
page,
name,
});
return { clients, count };
}
}
export default ListClientsService;
<file_sep>/src/shared/infra/http/app.ts
import 'reflect-metadata';
import 'dotenv/config';
import { errors as celebrateErrors } from 'celebrate';
import express, { Request, Response, NextFunction, Express } from 'express';
import cors from 'cors';
import 'express-async-errors';
import AppError from '@shared/errors/AppError';
import '@shared/container';
import createConnection from '@shared/infra/typeorm';
import routes from './routes';
createConnection();
class App {
public server: Express;
constructor() {
this.server = express();
this.middlewares();
this.routes();
this.errors();
}
middlewares(): void {
this.server.use(cors());
this.server.use(express.json());
}
routes(): void {
this.server.use(routes);
}
errors(): void {
this.server.use(celebrateErrors());
this.server.use(
(err: Error, req: Request, res: Response, _: NextFunction) => {
if (err instanceof AppError) {
return res.status(err.statusCode).json({
status: 'error',
message: err.message,
});
}
// eslint-disable-next-line
console.log(err);
return res.status(500).json({
status: 'error',
message: 'Internal server error',
});
},
);
}
}
export default new App().server;
<file_sep>/src/shared/container/index.ts
import { container } from 'tsyringe';
import '@modules/users/providers';
// import './providers';
import IClientsRepository from '@modules/clients/repositories/IClientsRepository';
import ClientsRepository from '@modules/clients/infra/typeorm/repositories/ClientsRepository';
// import IContractItemsRepository from '@modules/contractItems/repositories/IContractItemsRepository';
// import ContractItemsRepository from '@modules/contractItems/infra/typeorm/repositories/ContractItemsRepository';
import IContractsRepository from '@modules/contracts/repositories/IContractsRepository';
import ContractsRepository from '@modules/contracts/infra/typeorm/repositories/ContractsRepository';
import IMaterialsRepository from '@modules/materials/repositories/IMaterialsRepository';
import MaterialsRepository from '@modules/materials/infra/typeorm/repositories/MaterialsRepository';
import IUsersRepository from '@modules/users/repositories/IUsersRepository';
import UsersRepository from '@modules/users/infra/typeorm/repositories/UsersRepository';
container.registerSingleton<IClientsRepository>(
'ClientsRepository',
ClientsRepository,
);
// container.registerSingleton<IContractItemsRepository>(
// 'ContractItemsRepository',
// ContractItemsRepository,
// );
container.registerSingleton<IContractsRepository>(
'ContractsRepository',
ContractsRepository,
);
container.registerSingleton<IMaterialsRepository>(
'MaterialsRepository',
MaterialsRepository,
);
container.registerSingleton<IUsersRepository>(
'UsersRepository',
UsersRepository,
);
<file_sep>/src/modules/contracts/services/ListAllContractWithFilterOptionsService.ts
import { injectable, inject } from 'tsyringe';
import IContractsRepository from '@modules/contracts/repositories/IContractsRepository';
import Contract from '@modules/contracts/infra/typeorm/entities/Contract';
interface IRequest {
page: number;
name: string;
finished: boolean;
}
interface IResponse {
contracts: Contract[];
count: number;
}
@injectable()
class ListAllContractWithFilterOptionsService {
constructor(
@inject('ContractsRepository')
private contractsRepository: IContractsRepository,
) {}
public async execute({ page, name, finished }: IRequest): Promise<IResponse> {
const {
contracts,
count,
} = await this.contractsRepository.findAllWithFilterOptions({
page,
name,
finished,
});
return { contracts, count };
}
}
export default ListAllContractWithFilterOptionsService;
<file_sep>/src/modules/materials/services/ListMaterialsService.ts
import { injectable, inject } from 'tsyringe';
import Material from '@modules/materials/infra/typeorm/entities/Material';
import IMaterialsRepository from '@modules/materials/repositories/IMaterialsRepository';
interface IRequest {
page: number;
name: string;
}
interface IResponse {
materials: Material[];
count: number;
}
@injectable()
class ListMaterialsService {
constructor(
@inject('MaterialsRepository')
private materialsRepository: IMaterialsRepository,
) {}
public async execute({ page, name }: IRequest): Promise<IResponse> {
const {
materials,
count,
} = await this.materialsRepository.findAllWithPaginationAndSearch({
name,
page,
});
return { materials, count };
}
}
export default ListMaterialsService;
<file_sep>/src/modules/clients/infra/typeorm/repositories/ClientsRepository.ts
import { getRepository, Repository, Not } from 'typeorm';
import IClientsRepository from '@modules/clients/repositories/IClientsRepository';
import ICreateClientDTO from '@modules/clients/dtos/ICreateClientDTO';
import IFindByCPFWithDeletedDTO from '@modules/clients/dtos/IFindByCPFWithDeletedDTO';
import IFindAllDTO from '@modules/clients/dtos/IFindAllDTO';
import Client from '@modules/clients/infra/typeorm/entities/Client';
import IFindAllWithPaginationAndSearchDTO from '@modules/clients/dtos/IFindAllWithPaginationAndSearchDTO';
interface IResponseFindAllWithPaginationAndSearch {
clients: Client[];
count: number;
}
export default class ClientsRepository implements IClientsRepository {
private ormRepository: Repository<Client>;
constructor() {
this.ormRepository = getRepository(Client);
}
public async create({
name,
cpf,
phone_number,
address,
}: ICreateClientDTO): Promise<Client> {
const client = this.ormRepository.create({
name,
cpf,
phone_number,
address,
});
await this.ormRepository.save(client);
return client;
}
public async save(client: Client): Promise<Client> {
return this.ormRepository.save(client);
}
public async findByCPFWithDeleted(
cpf: string,
options?: IFindByCPFWithDeletedDTO,
): Promise<Client | undefined> {
let client: Client | undefined;
if (options?.execept_client_id) {
client = await this.ormRepository.findOne({
where: { cpf, id: Not(options.execept_client_id) },
withDeleted: true,
});
} else {
client = await this.ormRepository.findOne({
where: { cpf },
withDeleted: true,
});
}
return client;
}
public async findById(id: string): Promise<Client | undefined> {
const client = await this.ormRepository.findOne(id, {
relations: [
'contracts',
'contracts.contract_items',
'contracts.contract_items.material',
],
select: ['id', 'name', 'cpf', 'phone_number', 'address', 'deleted_at'],
withDeleted: true,
});
return client;
}
public async findAll({ deleted }: IFindAllDTO): Promise<Client[]> {
const clients = await this.ormRepository.find({ withDeleted: deleted });
return clients;
}
public async findAllWithPaginationAndSearch(
data: IFindAllWithPaginationAndSearchDTO,
): Promise<IResponseFindAllWithPaginationAndSearch> {
const { deleted, name, page } = data;
const query = this.ormRepository
.createQueryBuilder('clients')
.take(7)
.skip((page - 1) * 7)
.orderBy('clients.created_at', 'DESC');
if (name) {
query.where('name ILIKE :name', { name: `%${name}%` });
}
if (deleted) {
query.withDeleted().andWhere('deleted_at IS NOT NULL');
}
const [clients, count] = await query.getManyAndCount();
return {
clients,
count,
};
}
public async softDeleteById(id: string): Promise<void> {
await this.ormRepository.softDelete(id);
}
}
<file_sep>/src/modules/materials/dtos/ICreateMaterialDTO.ts
export default interface ICreateMaterialDTO {
name: string;
daily_price: number;
}
<file_sep>/src/modules/materials/repositories/IMaterialsRepository.ts
import Material from '@modules/materials/infra/typeorm/entities/Material';
import ICreateMaterialDTO from '@modules/materials/dtos/ICreateMaterialDTO';
import IFindAllWithPaginationAndSearchDTO from '@modules/materials/dtos/IFindAllWithPaginationAndSearchDTO';
interface IFindMaterials {
id: string;
}
interface IResponseFindAllWithPaginationAndSearch {
materials: Material[];
count: number;
}
export default interface IMaterialsRepository {
findAllWithPaginationAndSearch(
data: IFindAllWithPaginationAndSearchDTO,
): Promise<IResponseFindAllWithPaginationAndSearch>;
findAllById(materials: IFindMaterials[]): Promise<Material[]>;
findById(id: string): Promise<Material | undefined>;
findByName(name: string): Promise<Material | undefined>;
create(data: ICreateMaterialDTO): Promise<Material>;
save(material: Material): Promise<Material>;
}
<file_sep>/src/modules/contracts/repositories/IContractsRepository.ts
import Contract from '@modules/contracts/infra/typeorm/entities/Contract';
import ICreateContractDTO from '@modules/contracts/dtos/ICreateContractDTO';
import IFilterOptionsDTO from '@modules/contracts/dtos/IFilterOptionsDTO';
interface IFindAllAndCountResponse {
contracts: Contract[];
count: number;
}
export default interface IContractsRepository {
findAllWithFilterOptions(
data: IFilterOptionsDTO,
): Promise<IFindAllAndCountResponse>;
findByIdWithAllRelations(id: string): Promise<Contract | undefined>;
findById(id: string): Promise<Contract | undefined>;
create(data: ICreateContractDTO): Promise<Contract>;
save(contract: Contract): Promise<Contract>;
}
<file_sep>/src/modules/contracts/services/ListContractWithAllRelationsService.ts
import { injectable, inject } from 'tsyringe';
import AppError from '@shared/errors/AppError';
import IContractsRepository from '@modules/contracts/repositories/IContractsRepository';
import Contract from '@modules/contracts/infra/typeorm/entities/Contract';
interface IRequest {
contract_id: string;
}
@injectable()
class ListContractWithAllRelationsService {
constructor(
@inject('ContractsRepository')
private contractsRepository: IContractsRepository,
) {}
public async execute({ contract_id }: IRequest): Promise<Contract> {
const contract = await this.contractsRepository.findByIdWithAllRelations(
contract_id,
);
if (!contract) {
throw new AppError('Contract does not exists.');
}
return contract;
}
}
export default ListContractWithAllRelationsService;
<file_sep>/src/modules/clients/dtos/IFindAllWithPaginationAndSearchDTO.ts
export default interface IFindAllWithPaginationAndSearchDTO {
page: number;
name: string;
deleted: boolean;
}
<file_sep>/__tests__/integration/Session.spec.ts
import 'dotenv/config';
import request from 'supertest';
import { runSeeder } from 'typeorm-seeding';
import { Connection, getConnection } from 'typeorm';
import { verify } from 'jsonwebtoken';
import authConfig from '../../src/config/auth';
import createConnection from '../../src/database';
import UserAdminSeed from '../../src/database/seeds/UserAdmin.seed';
import app from '../../src/app';
let connection: Connection;
describe('Session', () => {
beforeAll(async () => {
connection = await createConnection('test-connection');
await connection.runMigrations();
await runSeeder(UserAdminSeed);
});
afterAll(async () => {
await connection.query('DELETE FROM users');
const mainConnection = getConnection();
await connection.close();
await mainConnection.close();
});
it('should be able to create a new session and receive a token JWT', async () => {
const response = await request(app).post('/sessions').send({
email: '<EMAIL>',
password: '<PASSWORD>',
});
const tokenVerified = verify(response.body.token, authConfig.jwt.secret);
expect(response.status).toBe(200);
expect(tokenVerified).toBeTruthy();
});
it('should not be able to create a new ssession with invalid data', async () => {
const response = await request(app).post('/sessions').send({
email: '<EMAIL>',
password: '<PASSWORD>',
});
expect(response.status).toBe(401);
expect(response.body).toMatchObject(
expect.objectContaining({
status: 'error',
message: 'Incorrect email/password combination.',
}),
);
});
});
<file_sep>/__tests__/utils/getTokenJWT.ts
import request from 'supertest';
import app from '../../src/app';
export default async function getToken(): Promise<string> {
const response = await request(app).post('/sessions').send({
email: '<EMAIL>',
password: '<PASSWORD>',
});
return response.body.token;
}
<file_sep>/todo.md
# Rest API to-do
## Material
**Requisitos Funcionais**
- O usuário deve poder criar um novo material
- O usuário deve poder listar todos os materais
- O usuário deve poder editar a diária de um material
**Requisitos não Funcionais**
**Regras de negocio**
- Não deve ser possivel ter materiais com nomes iguais
- Não deve ser possivel alterar o nome de um material
## Cliente
## Contrato
<file_sep>/src/modules/contracts/infra/http/validators/ContractCreate.ts
import { celebrate, Segments, Joi } from 'celebrate';
export default celebrate({
[Segments.BODY]: Joi.object().keys({
client_id: Joi.string().uuid({ version: 'uuidv4' }).required(),
delivery_price: Joi.number().min(0),
materials: Joi.array()
.items(
Joi.object().keys({
id: Joi.string().uuid({ version: 'uuidv4' }).required(),
quantity: Joi.number().min(1).required(),
}),
)
.required(),
}),
});
<file_sep>/src/modules/materials/infra/http/routes/materials.routes.ts
import { Router } from 'express';
import MaterialsController from '@modules/materials/infra/http/controllers/MaterialsController';
import validateMaterialCraete from '@modules/materials/infra/http/validators/MaterialCraete';
import validateMaterialUpdate from '@modules/materials/infra/http/validators/MaterialUpdate';
import validateMaterialList from '@modules/materials/infra/http/validators/MaterialList';
import IDParamsMustBeUUID from '@shared/infra/http/validators/IDParamsMustBeUUID';
const materialsRouter = Router();
const materialsController = new MaterialsController();
materialsRouter.use('/:id', IDParamsMustBeUUID);
materialsRouter.post('/', validateMaterialCraete, materialsController.create);
materialsRouter.get('/', validateMaterialList, materialsController.index);
materialsRouter.get('/:id', materialsController.show);
materialsRouter.put('/:id', validateMaterialUpdate, materialsController.update);
export default materialsRouter;
<file_sep>/__tests__/integration/Client.spec.ts
import request from 'supertest';
import { Connection, getRepository, getConnection } from 'typeorm';
import { runSeeder } from 'typeorm-seeding';
import Client from '../../src/models/Client';
import UserAdminSeed from '../../src/database/seeds/UserAdmin.seed';
import createConnection from '../../src/database';
import getToken from '../utils/getTokenJWT';
import app from '../../src/app';
let connection: Connection;
describe('Client', () => {
beforeAll(async () => {
connection = await createConnection('test-connection');
await connection.runMigrations();
await runSeeder(UserAdminSeed);
});
afterEach(async () => {
// await connection.query('DELETE FROM contract_items');
// await connection.query('DELETE FROM contracts');
// await connection.query('DELETE FROM materials');
await connection.query('DELETE FROM clients');
});
afterAll(async () => {
await connection.query('DELETE FROM users');
const mainConnection = getConnection();
await connection.close();
await mainConnection.close();
});
describe('Create', () => {
it('should be able to create a new client', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
const response = await request(app)
.post('/clients')
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const client = await clientsRepository.findOne({
where: { cpf: '761.436.350-72' },
});
expect(client).toBeTruthy();
expect(response.status).toBe(201);
expect(response.body).toMatchObject(
expect.objectContaining({
id: expect.any(String),
}),
);
});
it('should not be able to create a new client with CPF duplicated', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
await request(app)
.post('/clients')
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const response = await request(app)
.post('/clients')
.send({
name: 'Patricia',
cpf: '761.436.350-72',
phone_number: '71982723661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const client = await clientsRepository.find({
where: { cpf: '761.436.350-72' },
});
expect(client).toHaveLength(1);
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: expect.stringMatching('error'),
message: expect.stringMatching('Client already exists'),
}),
);
});
it('should not be able to create a new client when exists another client with the same CPF in soft delete', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
const { body: client } = await request(app)
.post('/clients')
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
await clientsRepository.softDelete(client.id);
const response = await request(app)
.post('/clients')
.send({
name: 'Patricia',
cpf: '761.436.350-72',
phone_number: '71982723661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const dbClient = await clientsRepository.find({
where: { cpf: '761.436.350-72' },
withDeleted: true,
});
expect(dbClient).toHaveLength(1);
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: expect.stringMatching('error'),
message: expect.stringMatching('Client already exists'),
}),
);
});
});
describe('List', () => {
it('should be able to list all clients', async () => {
const token = await getToken();
await request(app)
.post('/clients')
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
await request(app)
.post('/clients')
.send({
name: 'Patricia',
cpf: '892.357.545-34',
phone_number: '92992979776',
address: 'Rua Pancrácio Nobre, Planalto, 867',
})
.set('Authorization', `Bearer ${token}`);
const response = await request(app)
.get('/clients')
.set('Authorization', `Bearer ${token}`);
expect(response.body).toHaveLength(2);
});
it('should be able to list all clients in soft delete', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
await request(app)
.post('/clients')
.send({
name: 'Gustavo',
cpf: '761.426.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const { body: client1 } = await request(app)
.post('/clients')
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const { body: client2 } = await request(app)
.post('/clients')
.send({
name: 'Patricia',
cpf: '892.357.545-34',
phone_number: '92992979776',
address: 'Rua Pancrácio Nobre, Planalto, 867',
})
.set('Authorization', `Bearer ${token}`);
client1.deleted_at = new Date();
client2.deleted_at = new Date();
await clientsRepository.save([client1, client2]);
const response = await request(app)
.get('/clients')
.query({ deleted: true })
.set('Authorization', `Bearer ${token}`);
expect(response.body).toHaveLength(2);
});
it('should be abtle to list one client', async () => {
const token = await getToken();
const { body: client } = await request(app)
.post('/clients')
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const response = await request(app)
.get(`/clients/${client.id}`)
.set('Authorization', `Bearer ${token}`);
expect(response.body).toMatchObject({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
});
});
it('should not be able to list one client that does not exists', async () => {
const token = await getToken();
const response = await request(app)
.get(`/clients/12e5c331-1091-405f-b4e1-949000125129`)
.set('Authorization', `Bearer ${token}`);
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: 'error',
message: 'Client does not exists',
}),
);
});
});
describe('Update', () => {
it('should be able to update a client by an id', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
const { body: client } = await request(app)
.post('/clients')
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const response = await request(app)
.put(`/clients/${client.id}`)
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '75982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const dbClient = await clientsRepository.findOne(client.id);
expect(response.status).toBe(204);
expect(dbClient).toMatchObject({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '75982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
});
});
it('should not be able to update a client that does not exists', async () => {
const token = await getToken();
const response = await request(app)
.put(`/clients/12e5c331-1091-405f-b4e1-949000125129`)
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '75982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: 'error',
message: 'Client does not exists',
}),
);
});
it('should not be able to update a client with an CPF existed', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
const { body: client } = await request(app)
.post('/clients')
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
await request(app)
.post('/clients')
.send({
name: '<NAME>',
cpf: '959.178.070-27',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const response = await request(app)
.put(`/clients/${client.id}`)
.send({
name: '<NAME> <NAME>',
cpf: '959.178.070-27',
phone_number: '75982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const dbClient = await clientsRepository.findOne(client.id);
expect(dbClient?.cpf).toBe('761.436.350-72');
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: 'error',
message: 'Client already exists',
}),
);
});
it('should not be able to update a client when exists another client with the same CPF in soft delete', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
const { body: client } = await request(app)
.post('/clients')
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const { body: softDeleteClient } = await request(app)
.post('/clients')
.send({
name: '<NAME>',
cpf: '959.178.070-27',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
await clientsRepository.softDelete(softDeleteClient.id);
const response = await request(app)
.put(`/clients/${client.id}`)
.send({
name: '<NAME>',
cpf: '959.178.070-27',
phone_number: '75982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const dbClient = await clientsRepository.findOne(client.id);
expect(dbClient?.cpf).toBe('761.436.350-72');
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: 'error',
message: 'Client already exists',
}),
);
});
it('should not be able to update a client in soft delete', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
const { body: client } = await request(app)
.post('/clients')
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
await clientsRepository.softDelete(client.id);
const response = await request(app)
.put(`/clients/${client.id}`)
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '75982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: 'error',
message: 'Client does not exists',
}),
);
});
it('should not be able to update deleted_at field directly', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
const { body: client } = await request(app)
.post('/clients')
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const response = await request(app)
.put(`/clients/${client.id}`)
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '75982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
deleted_at: new Date(),
})
.set('Authorization', `Bearer ${token}`);
const dbClient = await clientsRepository.findOne(client.id);
expect(response.status).toBe(204);
expect(dbClient).toMatchObject(
expect.objectContaining({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '75982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
deleted_at: null,
}),
);
});
});
describe('Delete', () => {
it('should be able to delete a client and set deleted_at', async () => {
const token = await getToken();
const clientsRepository = getRepository(Client);
const { body: client } = await request(app)
.post('/clients')
.send({
name: '<NAME>',
cpf: '761.436.350-72',
phone_number: '71982740661',
address: 'Rua Manoel Camillo de Almeida, Alto Sobradinho, 108',
})
.set('Authorization', `Bearer ${token}`);
const response = await request(app)
.delete(`/clients/${client.id}`)
.set('Authorization', `Bearer ${token}`);
const dbClient = await clientsRepository.findOne({
where: {
id: client.id,
},
withDeleted: true,
});
expect(response.status).toBe(200);
expect(dbClient?.deleted_at).toBeTruthy();
});
it('should not be able to delete a client that does not exists', async () => {
const token = await getToken();
const response = await request(app)
.delete(`/clients/12e5c331-1091-405f-b4e1-949000125129`)
.set('Authorization', `Bearer ${token}`);
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: 'error',
message: 'Client does not exists',
}),
);
});
});
});
<file_sep>/src/shared/infra/http/validators/IDParamsMustBeUUID.ts
import { celebrate, Segments, Joi } from 'celebrate';
export default celebrate({
[Segments.PARAMS]: Joi.object().keys({
id: Joi.string().uuid({ version: 'uuidv4' }).required(),
}),
});
<file_sep>/src/modules/clients/infra/http/controllers/ClientsController.ts
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import CreateClientService from '@modules/clients/services/CreateClientService';
import UpdateClientService from '@modules/clients/services/UpdateClientService';
import ListClientsService from '@modules/clients/services/ListClientsService';
import ShowClientService from '@modules/clients/services/ShowClientService';
export default class ClientsController {
public async create(req: Request, res: Response): Promise<Response> {
const { name, cpf, phone_number, address } = req.body;
const createClient = container.resolve(CreateClientService);
const client = await createClient.execute({
name,
cpf,
phone_number,
address,
});
return res.json(client);
}
public async index(req: Request, res: Response): Promise<Response> {
const { deleted, name, page } = req.query;
const listClients = container.resolve(ListClientsService);
const { clients, count } = await listClients.execute({
deleted: !!deleted,
name: String(name),
page: Number(page),
});
res.header('X-Total-Count', `${count}`);
res.header('Access-Control-Expose-Headers', 'X-Total-Count');
return res.json(clients);
}
public async show(req: Request, res: Response): Promise<Response> {
const { id } = req.params;
const showClient = container.resolve(ShowClientService);
const client = await showClient.execute({ id });
return res.json(client);
}
public async update(req: Request, res: Response): Promise<Response> {
const { name, cpf, phone_number, address } = req.body;
const updateClient = container.resolve(UpdateClientService);
await updateClient.execute({
name,
cpf,
phone_number,
address,
client_id: req.params.id,
});
return res.status(204).json();
}
}
<file_sep>/src/modules/contracts/infra/http/controllers/ContractsController.ts
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import CreateContractService from '@modules/contracts/services/CreateContractService';
import FinishContractService from '@modules/contracts/services/FinishContractService';
import ListAllContractWithFilterOptionsService from '@modules/contracts/services/ListAllContractWithFilterOptionsService';
import ListContractWithAllRelationsService from '@modules/contracts/services/ListContractWithAllRelationsService';
export default class ContractsController {
public async create(req: Request, res: Response): Promise<Response> {
const { client_id, materials, delivery_price } = req.body;
const createContract = container.resolve(CreateContractService);
const contract = await createContract.execute({
client_id,
delivery_price,
materials,
});
return res.json(contract);
}
public async index(req: Request, res: Response): Promise<Response> {
const { page, name, finished } = req.query;
const listAllContractWithFilterOptions = container.resolve(
ListAllContractWithFilterOptionsService,
);
const { contracts, count } = await listAllContractWithFilterOptions.execute(
{
page: Number(page),
name: String(name),
finished: Boolean(finished),
},
);
res.header('X-Total-Count', `${count}`);
res.header('Access-Control-Expose-Headers', 'X-Total-Count');
return res.json(contracts);
}
public async show(req: Request, res: Response): Promise<Response> {
const contract_id = req.params.id;
const listContractWithAllRelations = container.resolve(
ListContractWithAllRelationsService,
);
const contract = await listContractWithAllRelations.execute({
contract_id,
});
return res.json(contract);
}
public async update(req: Request, res: Response): Promise<Response> {
const { collect_price } = req.body;
const contract_id = req.params.id;
const finishContract = container.resolve(FinishContractService);
const contract = await finishContract.execute({
contract_id,
collect_price,
});
return res.json(contract);
}
}
<file_sep>/src/modules/materials/dtos/IFindAllWithPaginationAndSearchDTO.ts
export default interface IFindAllWithPaginationAndSearchDTO {
page: number;
name: string;
}
<file_sep>/src/shared/infra/typeorm/seeds/UserAdmin.seed.ts
import { Seeder, Factory } from 'typeorm-seeding';
import { Connection } from 'typeorm';
import bcrypt from 'bcryptjs';
const UserAdminValue = {
name: 'Admin',
email: '<EMAIL>',
password_hash: bcrypt.hashSync('<PASSWORD>', 8),
created_at: new Date(),
updated_at: new Date(),
};
export default class UserAdmin implements Seeder {
public async run(factory: Factory, connection: Connection): Promise<void> {
await connection
.createQueryBuilder()
.insert()
.into('users')
.values(UserAdminValue)
.execute();
}
}
<file_sep>/src/modules/clients/infra/http/routes/clients.routes.ts
import { Router } from 'express';
import ClientsController from '@modules/clients/infra/http/controllers/ClientsController';
import SoftDeleteController from '@modules/clients/infra/http/controllers/SoftDeleteClientsController';
import validateClientCreate from '@modules/clients/infra/http/validators/ClientCreate';
import validateClientUpdate from '@modules/clients/infra/http/validators/ClientUpdate';
import validateClientList from '@modules/clients/infra/http/validators/ClientList';
import IDParamsMustBeUUID from '@shared/infra/http/validators/IDParamsMustBeUUID';
const clientsRouter = Router();
const clientsController = new ClientsController();
const softDeleteController = new SoftDeleteController();
clientsRouter.use('/:id', IDParamsMustBeUUID);
clientsRouter.post('/', validateClientCreate, clientsController.create);
clientsRouter.get('/', validateClientList, clientsController.index);
// clientsRouter.get('/:id', async (req, res) => {
// const clientsRepository = getRepository(Client);
// const client = await clientsRepository.findOne(req.params.id, {
// relations: [
// 'contracts',
// 'contracts.contract_items',
// 'contracts.contract_items.material',
// ],
// select: ['id', 'name', 'cpf', 'phone_number', 'address', 'deleted_at'],
// withDeleted: true,
// });
// if (!client) {
// throw new AppError('Client does not exists');
// }
// return res.json(client);
// });
clientsRouter.get('/:id', clientsController.show);
clientsRouter.put('/:id', validateClientUpdate, clientsController.update);
clientsRouter.delete('/soft/:id', softDeleteController.delete);
export default clientsRouter;
<file_sep>/src/modules/contracts/services/CreateContractService.ts
import { injectable, inject } from 'tsyringe';
import AppError from '@shared/errors/AppError';
import IContractsRepository from '@modules/contracts/repositories/IContractsRepository';
import IClientsRepository from '@modules/clients/repositories/IClientsRepository';
import IMaterialsRepository from '@modules/materials/repositories/IMaterialsRepository';
// import ContractItem from '@models/ContractItem';
// import Client from '@models/Client';
import Contract from '@modules/contracts/infra/typeorm/entities/Contract';
// import Material from '@models/Material';
interface IMaterialDTO {
id: string;
quantity: number;
}
interface IRequest {
client_id: string;
materials: IMaterialDTO[];
delivery_price: number;
}
@injectable()
class CreateContractService {
constructor(
@inject('ContractsRepository')
private contractsRepository: IContractsRepository,
@inject('ClientsRepository')
private clientsRepository: IClientsRepository,
@inject('MaterialsRepository')
private materialsRepository: IMaterialsRepository,
) {}
public async execute({
client_id,
materials,
delivery_price = 0,
}: IRequest): Promise<Contract> {
const client = await this.clientsRepository.findById(client_id);
if (!client) {
throw new AppError('Client does not exists');
}
const databaseMaterials = await this.materialsRepository.findAllById(
materials.map(material => ({ id: material.id })),
);
if (materials.length !== databaseMaterials.length) {
throw new AppError('Invalid materials list');
}
const contractItems = materials.map(material => {
const materialPrice = databaseMaterials.find(
findMaterial => findMaterial.id === material.id,
)?.daily_price;
if (!materialPrice) {
throw new AppError('Material price not found');
}
return {
material_id: material.id,
quantity: material.quantity,
price_quantity_daily: material.quantity * materialPrice,
};
});
const daily_total_price = contractItems.reduce(
(increment, contractItem) => {
return increment + contractItem.price_quantity_daily;
},
0,
);
const contract = await this.contractsRepository.create({
client,
daily_total_price,
delivery_price,
materials: contractItems,
});
return contract;
}
}
export default CreateContractService;
<file_sep>/docker-compose.yml
version: '3.6'
networks:
pontoloc-network:
driver: bridge
services:
pontoloc-api:
build: .
volumes:
- .:/home/node/api
environment:
- DB_HOST=pontoloc-postgres
depends_on:
- pontoloc-postgres
networks:
- pontoloc-network
container_name: pontoloc-api
command: yarn dev:server
ports:
- '3333:3333'
pontoloc-postgres:
image: postgres
container_name: pontoloc-postgres
environment:
- POSTGRES_USER=${DB_USER}
- POSTGRES_PASSWORD=${DB_PASS}
- POSTGRES_DB=${DB_NAME}
ports:
- '5432:5432'
networks:
- pontoloc-network
<file_sep>/src/modules/contracts/services/FinishContractService.ts
import { injectable, inject } from 'tsyringe';
import { differenceInCalendarDays } from 'date-fns';
import IContractsRepository from '@modules/contracts/repositories/IContractsRepository';
import AppError from '@shared/errors/AppError';
import Contract from '@modules/contracts/infra/typeorm/entities/Contract';
interface IRequest {
contract_id: string;
collect_price: number;
}
@injectable()
class FinishContractService {
constructor(
@inject('ContractsRepository')
private contractsRepository: IContractsRepository,
) {}
public async execute({
contract_id,
collect_price = 0,
}: IRequest): Promise<Contract> {
const contract = await this.contractsRepository.findById(contract_id);
if (!contract) {
throw new AppError('Contract does not exists');
}
const timeOffRent = differenceInCalendarDays(
new Date(),
contract.created_at,
);
const final_price =
contract.daily_total_price * timeOffRent +
contract.delivery_price +
collect_price;
Object.assign(contract, {
collect_price,
final_price,
collect_at: new Date(),
});
await this.contractsRepository.save(contract);
return contract;
}
}
export default FinishContractService;
<file_sep>/src/modules/materials/infra/typeorm/repositories/MaterialsRepository.ts
import { getRepository, Repository } from 'typeorm';
import IMaterialsRepository from '@modules/materials/repositories/IMaterialsRepository';
import ICreateMaterialDTO from '@modules/materials/dtos/ICreateMaterialDTO';
import IFindAllWithPaginationAndSearchDTO from '@modules/materials/dtos/IFindAllWithPaginationAndSearchDTO';
import Material from '@modules/materials/infra/typeorm/entities/Material';
interface IFindMaterials {
id: string;
}
interface IResponseFindAllWithPaginationAndSearch {
materials: Material[];
count: number;
}
export default class MaterialsRepository implements IMaterialsRepository {
private ormRepository: Repository<Material>;
constructor() {
this.ormRepository = getRepository(Material);
}
public async findByName(name: string): Promise<Material | undefined> {
const material = await this.ormRepository.findOne({ where: { name } });
return material;
}
public async findById(id: string): Promise<Material | undefined> {
const material = await this.ormRepository.findOne(id);
return material;
}
public async findAllWithPaginationAndSearch(
data: IFindAllWithPaginationAndSearchDTO,
): Promise<IResponseFindAllWithPaginationAndSearch> {
const { name, page } = data;
const query = this.ormRepository
.createQueryBuilder('materials')
.take(7)
.skip((page - 1) * 7)
.orderBy('created_at', 'DESC');
if (name) {
query.where('name ILIKE :name', { name: `%${name}%` });
}
const [materials, count] = await query.getManyAndCount();
return { materials, count };
}
public async findAllById(materials: IFindMaterials[]): Promise<Material[]> {
const FindMaterials = await this.ormRepository.findByIds(materials);
return FindMaterials;
}
public async create({
name,
daily_price,
}: ICreateMaterialDTO): Promise<Material> {
const material = this.ormRepository.create({ name, daily_price });
await this.ormRepository.save(material);
return material;
}
public async save(material: Material): Promise<Material> {
return this.ormRepository.save(material);
}
}
<file_sep>/src/modules/contracts/dtos/ICreateContractDTO.ts
import Client from '@modules/clients/infra/typeorm/entities/Client';
interface IMaterail {
material_id: string;
quantity: number;
price_quantity_daily: number;
}
export default interface ICreateContractDTO {
client: Client;
delivery_price: number;
daily_total_price: number;
materials: IMaterail[];
}
<file_sep>/src/modules/contracts/infra/typeorm/entities/Contract.ts
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
OneToMany,
JoinColumn,
} from 'typeorm';
import Client from '@modules/clients/infra/typeorm/entities/Client';
import ContractItem from '@modules/contracts/infra/typeorm/entities/ContractItem';
@Entity('contracts')
class Contract {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({
generated: 'increment',
type: 'int',
readonly: true,
})
number: number;
@Column()
client_id: string;
@ManyToOne(() => Client, client => client.contracts)
@JoinColumn({ name: 'client_id' })
client: Client;
@OneToMany(() => ContractItem, contractItem => contractItem.contract, {
cascade: true,
})
contract_items: ContractItem[];
@Column()
daily_total_price: number;
@Column()
delivery_price: number;
@Column()
collect_price: number;
@Column()
final_price: number;
@Column()
collect_at: Date;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
export default Contract;
<file_sep>/src/modules/contracts/infra/http/routes/contracts.routes.ts
import { Router } from 'express';
import ContractsController from '@modules/contracts/infra/http/controllers/ContractsController';
import validateContractCreate from '@modules/contracts/infra/http/validators/ContractCreate';
import validateContractFinish from '@modules/contracts/infra/http/validators/ContractFinish';
import validateContractList from '@modules/contracts/infra/http/validators/ContractList';
import IDParamsMustBeUUID from '@shared/infra/http/validators/IDParamsMustBeUUID';
const contractsRouter = Router();
const contractsController = new ContractsController();
contractsRouter.use('/:id', IDParamsMustBeUUID);
contractsRouter.post('/', validateContractCreate, contractsController.create);
contractsRouter.get('/', validateContractList, contractsController.index);
contractsRouter.get('/:id', contractsController.show);
contractsRouter.put(
'/:id/finish',
validateContractFinish,
contractsController.update,
);
export default contractsRouter;
<file_sep>/src/modules/clients/dtos/ICreateClientDTO.ts
export default interface ICreateClientDTO {
name: string;
cpf: string;
phone_number: string;
address: string;
}
<file_sep>/src/modules/contracts/infra/typeorm/repositories/ContractsRepository.ts
import { getRepository, Repository } from 'typeorm';
import ICreateContractDTO from '@modules/contracts/dtos/ICreateContractDTO';
import IFilterOptionsDTO from '@modules/contracts/dtos/IFilterOptionsDTO';
import IContractsRepository from '@modules/contracts/repositories/IContractsRepository';
import Contract from '@modules/contracts/infra/typeorm/entities/Contract';
interface IFindAllAndCountResponse {
contracts: Contract[];
count: number;
}
export default class ContarctsRepository implements IContractsRepository {
private ormRepository: Repository<Contract>;
constructor() {
this.ormRepository = getRepository(Contract);
}
public async create({
client,
materials,
delivery_price,
daily_total_price,
}: ICreateContractDTO): Promise<Contract> {
const contract = this.ormRepository.create({
client,
contract_items: materials,
delivery_price,
daily_total_price,
});
await this.ormRepository.save(contract);
return contract;
}
public async save(contract: Contract): Promise<Contract> {
return this.ormRepository.save(contract);
}
public async findById(id: string): Promise<Contract | undefined> {
const contract = await this.ormRepository.findOne(id);
return contract;
}
public async findAllWithFilterOptions({
page,
name,
finished,
}: IFilterOptionsDTO): Promise<IFindAllAndCountResponse> {
// const [contracts, count] = await this.ormRepository.findAndCount({
// relations: ['client'],
// order: { number: 'DESC' },
// take: 7,
// skip: (page - 1) * 7,
// });
const query = this.ormRepository
.createQueryBuilder('contracts')
.innerJoinAndSelect('contracts.client', 'client')
.where(`contracts.collect_at ${finished ? 'IS NOT' : 'IS'} NULL`)
.take(7)
.skip((page - 1) * 7)
.orderBy('contracts.number', 'DESC');
if (name) {
query.andWhere('client.name ILIKE :name', { name: `%${name}%` });
}
const [contracts, count] = await query.getManyAndCount();
return { contracts, count };
}
public async findByIdWithAllRelations(
id: string,
): Promise<Contract | undefined> {
const contract = await this.ormRepository.findOne(id, {
relations: ['client', 'contract_items', 'contract_items.material'],
});
return contract;
}
}
<file_sep>/src/modules/contracts/infra/typeorm/entities/ContractItem.ts
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
ManyToOne,
JoinColumn,
} from 'typeorm';
import Material from '@modules/materials/infra/typeorm/entities/Material';
import Contract from '@modules/contracts/infra/typeorm/entities/Contract';
@Entity('contract_items')
class ContractItem {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column()
contract_id: string;
@ManyToOne(() => Contract, contract => contract.contract_items)
@JoinColumn({ name: 'contract_id' })
contract: Contract;
@Column()
material_id: string;
@ManyToOne(() => Material)
@JoinColumn({ name: 'material_id' })
material: Material;
@Column({ type: 'int' })
quantity: number;
@Column()
price_quantity_daily: number;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
}
export default ContractItem;
<file_sep>/.env.example
APP_URL=http://localhost:3333
NODE_ENV=development
# Auth
APP_SECRET=
# Database
# se for usar docker-compose, retirar a variavel DB_HOST
DB_HOST=
DB_USER=
DB_PASS=
DB_NAME=
<file_sep>/src/modules/materials/services/UpdateMaterialService.ts
import { injectable, inject } from 'tsyringe';
import AppError from '@shared/errors/AppError';
import IMaterialsRepository from '@modules/materials/repositories/IMaterialsRepository';
interface IRequest {
material_id: string;
daily_price: number;
}
@injectable()
class UpdateMaterialService {
constructor(
@inject('MaterialsRepository')
private materialsRepository: IMaterialsRepository,
) {}
public async execute({ material_id, daily_price }: IRequest): Promise<void> {
const material = await this.materialsRepository.findById(material_id);
if (!material) {
throw new AppError('Material does not exists');
}
Object.assign(material, { daily_price });
await this.materialsRepository.save(material);
}
}
export default UpdateMaterialService;
<file_sep>/src/modules/clients/services/UpdateClientService.ts
import { injectable, inject } from 'tsyringe';
import IClientsRepository from '@modules/clients/repositories/IClientsRepository';
import AppError from '@shared/errors/AppError';
interface IRequest {
name: string;
cpf: string;
phone_number: string;
address: string;
client_id: string;
}
@injectable()
class UpdateClientService {
constructor(
@inject('ClientsRepository')
private clientsRepository: IClientsRepository,
) {}
public async execute({
name,
cpf,
phone_number,
address,
client_id,
}: IRequest): Promise<void> {
const client = await this.clientsRepository.findById(client_id);
if (!client) {
throw new AppError('Client does not exists');
}
const clientWithSameCPF = await this.clientsRepository.findByCPFWithDeleted(
cpf,
{ execept_client_id: client_id },
);
if (clientWithSameCPF) {
throw new AppError('Client already exists');
}
Object.assign(client, { name, cpf, phone_number, address });
await this.clientsRepository.save(client);
}
}
export default UpdateClientService;
<file_sep>/src/modules/users/repositories/IUsersRepository.ts
import User from '@modules/users/infra/typeorm/entities/User';
export default interface IUsersRepository {
findByEmail(email: string): Promise<User | undefined>;
}
<file_sep>/src/modules/materials/infra/http/controllers/MaterialsController.ts
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import CreateMaterialService from '@modules/materials/services/CreateMaterialService';
import UpdateMaterialService from '@modules/materials/services/UpdateMaterialService';
import ListMaterialsService from '@modules/materials/services/ListMaterialsService';
import ShowMaterialService from '@modules/materials/services/ShowMaterialService';
export default class MaterialsController {
public async create(req: Request, res: Response): Promise<Response> {
const { name, daily_price } = req.body;
const craeteMaterial = container.resolve(CreateMaterialService);
const material = await craeteMaterial.execute({ name, daily_price });
return res.status(201).json(material);
}
public async index(req: Request, res: Response): Promise<Response> {
const { page, name } = req.query;
const listMaterials = container.resolve(ListMaterialsService);
const { materials, count } = await listMaterials.execute({
name: String(name),
page: Number(page),
});
res.header('X-Total-Count', `${count}`);
res.header('Access-Control-Expose-Headers', 'X-Total-Count');
return res.json(materials);
}
public async show(req: Request, res: Response): Promise<Response> {
const { id } = req.params;
const showMaterial = container.resolve(ShowMaterialService);
const material = await showMaterial.execute({ id });
return res.json(material);
}
public async update(req: Request, res: Response): Promise<Response> {
const { daily_price } = req.body;
const material_id = req.params.id;
const updateMaterial = container.resolve(UpdateMaterialService);
await updateMaterial.execute({ material_id, daily_price });
return res.status(204).json();
}
}
<file_sep>/README.md
<h1 align="center">
<img
alt="Logo"
src="https://res.cloudinary.com/eliasgcf/image/upload/v1588529377/pontoloc/logo_hmpbwn.png" width="300px"
/>
</h1>
<h3 align="center">
Express Application for a PontoLoc Web App
</h3>
<p align="center">
<img alt="GitHub top language" src="https://img.shields.io/github/languages/top/EliasGcf/pontoloc-api?color=%23fbc131">
<a href="https://www.linkedin.com/in/eliasgcf/" target="_blank" rel="noopener noreferrer">
<img alt="Made by" src="https://img.shields.io/badge/made%20by-elias%20gabriel-%23fbc131">
</a>
<img alt="Repository size" src="https://img.shields.io/github/repo-size/EliasGcf/pontoloc-api?color=%23fbc131">
<a href="https://github.com/EliasGcf/pontoloc-api/commits/master">
<img alt="GitHub last commit" src="https://img.shields.io/github/last-commit/EliasGcf/pontoloc-api?color=%23fbc131">
</a>
<a href="https://github.com/EliasGcf/pontoloc-api/issues">
<img alt="Repository issues" src="https://img.shields.io/github/issues/EliasGcf/pontoloc-api?color=%23fbc131">
</a>
<img alt="GitHub" src="https://img.shields.io/github/license/EliasGcf/pontoloc-api?color=%23fbc131">
</p>
<p align="center">
<a href="#-about-the-project">About the project</a> |
<a href="#-technologies">Technologies</a> |
<a href="#-getting-started">Getting started</a> |
<a href="#-how-to-contribute">How to contribute</a> |
<a href="#-license">License</a>
</p>
<p id="insomniaButton" align="center">
<a href="https://insomnia.rest/run/?label=PontoLoc&uri=https%3A%2F%2Fraw.githubusercontent.com%2FEliasGcf%2Fpontoloc-api%2Fmaster%2FInsomnia.json" target="_blank">
<img src="https://insomnia.rest/images/run.svg" alt="Run in Insomnia">
</a>
</p>
## 👨🏻💻 About the project
PontoLoc is a micro enterprise that rents construction materials. Thinking about helping them, I developed this API so the company can have a simple and easy way to control and visualize the rent of its materials.
The company can create lists and contracts of clients, lists of materials with their respective quantities, delivery and collection fee and calculate the final price when the rental period is end.
To see the **web client**, click here: [PontoLoc Web](https://github.com/EliasGcf/pontoloc-web)<br />
## 🚀 Technologies
Technologies that I used to develop this api
- [Node.js](https://nodejs.org/en/)
- [TypeScript](https://www.typescriptlang.org/)
- [Express](https://expressjs.com/pt-br/)
- [TypeORM](https://typeorm.io/#/)
- [JWT-token](https://jwt.io/)
- [Celebrate](https://github.com/arb/celebrate)
- [PostgreSQL](https://www.postgresql.org/)
- [Date-fns](https://date-fns.org/)
- [Jest](https://jestjs.io/)
- [SuperTest](https://github.com/visionmedia/supertest)
- [Husky](https://github.com/typicode/husky)
- [Commitlint](https://github.com/conventional-changelog/commitlint)
- [Commitizen](https://github.com/commitizen/cz-cli)
- [Eslint](https://eslint.org/)
- [Prettier](https://prettier.io/)
- [EditorConfig](https://editorconfig.org/)
## 💻 Getting started
Import the `Insomnia.json` on Insomnia App or click on [Run in Insomnia](#insomniaButton) button
### Requirements
- [Docker](https://www.docker.com/)
- [Docker Compose](https://docs.docker.com/compose/)
**Clone the project and access the folder**
```bash
$ git clone https://github.com/EliasGcf/pontoloc-api.git && cd pontoloc-api
```
**Follow the steps below**
```bash
# Install the dependencies
$ yarn
# Make a copy of '.env.example' to '.env'
# and set with YOUR environment variables
$ cp .env.example .env
# Run the services
$ docker-compose up -d
# Once the services are running, run the migrations
$ yarn typeorm migration:run
# For make requests you must use JWT Token
# So, run the seeds to create admin user
$ yarn seed:run
# Credentials:
# email: <EMAIL>
# password: <PASSWORD>
# Well done, project is started!
```
## 🤔 How to contribute
- **Make a fork of this repository**
```bash
# Fork using GitHub official command line
# If you don't have the GitHub CLI, use the web site to do that.
$ gh repo fork EliasGcf/pontoloc-api
```
```bash
# Clone your fork
$ git clone your-fork-url && cd pontoloc-api
# Create a branch with your feature
$ git checkout -b my-feature
# Make the commit with your changes
$ git commit -m 'feat: My new feature'
# Send the code to your remote branch
$ git push origin my-feature
```
After your pull request is merged, you can delete your branch
## 📝 License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
---
Made with 💜 by <NAME> 👋 [See my linkedin](https://www.linkedin.com/in/eliasgcf/)
<file_sep>/src/modules/materials/services/CreateMaterialService.ts
import { injectable, inject } from 'tsyringe';
import IMaterialsRepository from '@modules/materials/repositories/IMaterialsRepository';
import Material from '@modules/materials/infra/typeorm/entities/Material';
import AppError from '@shared/errors/AppError';
interface IRequest {
name: string;
daily_price: number;
}
@injectable()
class CreateMaterialService {
constructor(
@inject('MaterialsRepository')
private materialsRepository: IMaterialsRepository,
) {}
public async execute({ name, daily_price }: IRequest): Promise<Material> {
const materialExists = await this.materialsRepository.findByName(
name.toLowerCase(),
);
if (materialExists) {
throw new AppError('Material already exists');
}
const material = await this.materialsRepository.create({
name,
daily_price,
});
return material;
}
}
export default CreateMaterialService;
<file_sep>/src/shared/infra/http/routes/index.ts
import { Router } from 'express';
import ensureAuthenticade from '@modules/users/infra/http/middlewares/ensureAuthenticated';
import clientsRouter from '@modules/clients/infra/http/routes/clients.routes';
import sessionsRouter from '@modules/users/infra/http/routes/sessions.routes';
import materialsRouter from '@modules/materials/infra/http/routes/materials.routes';
import contractsRouter from '@modules/contracts/infra/http/routes/contracts.routes';
const routes = Router();
routes.use('/sessions', sessionsRouter);
routes.use(ensureAuthenticade);
routes.use('/clients', clientsRouter);
routes.use('/materials', materialsRouter);
routes.use('/contracts', contractsRouter);
export default routes;
<file_sep>/__tests__/integration/Material.spec.ts
import request from 'supertest';
import { Connection, getRepository, getConnection } from 'typeorm';
import { runSeeder } from 'typeorm-seeding';
import Material from '../../src/models/Material';
import UserAdminSeed from '../../src/database/seeds/UserAdmin.seed';
import createConnection from '../../src/database';
import getToken from '../utils/getTokenJWT';
import app from '../../src/app';
let connection: Connection;
describe('Material', () => {
beforeAll(async () => {
connection = await createConnection('test-connection');
await connection.runMigrations();
await runSeeder(UserAdminSeed);
});
afterEach(async () => {
// await connection.query('DELETE FROM contract_items');
// await connection.query('DELETE FROM contracts');
await connection.query('DELETE FROM materials');
// await connection.query('DELETE FROM clients');
});
afterAll(async () => {
await connection.query('DELETE FROM users');
const mainConnection = getConnection();
await connection.close();
await mainConnection.close();
});
describe('Create', () => {
it('should be able to create a new material', async () => {
const token = await getToken();
const materialsRepository = getRepository(Material);
const response = await request(app)
.post('/materials')
.send({
name: 'Andaime',
daily_price: 1.2,
})
.set('Authorization', `Bearer ${token}`);
const material = await materialsRepository.findOne({
where: { name: 'andaime' },
});
expect(material).toBeTruthy();
expect(response.status).toBe(201);
expect(response.body).toMatchObject(
expect.objectContaining({
id: expect.any(String),
name: 'andaime',
daily_price: 1.2,
}),
);
});
it('should not be able to create a new material with duplicated name', async () => {
const token = await getToken();
const materialsRepository = getRepository(Material);
await request(app)
.post('/materials')
.send({
name: 'Andaime',
daily_price: 1.2,
})
.set('Authorization', `Bearer ${token}`);
const response = await request(app)
.post('/materials')
.send({
name: 'Andaime',
daily_price: 1.2,
})
.set('Authorization', `Bearer ${token}`);
const materials = await materialsRepository.find({
where: { name: 'andaime' },
});
expect(materials).toHaveLength(1);
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: expect.stringMatching('error'),
message: expect.stringMatching('Material already exists'),
}),
);
});
});
describe('List', () => {
it('should be able to list all materials', async () => {
const token = await getToken();
await request(app)
.post('/materials')
.send({
name: 'Andaime',
daily_price: 1.2,
})
.set('Authorization', `Bearer ${token}`);
await request(app)
.post('/materials')
.send({
name: 'Estronca',
daily_price: 1.2,
})
.set('Authorization', `Bearer ${token}`);
const response = await request(app)
.get('/materials')
.set('Authorization', `Bearer ${token}`);
expect(response.body).toHaveLength(2);
});
it('should be able to list one material', async () => {
const token = await getToken();
const { body: material } = await request(app)
.post('/materials')
.send({
name: 'Andaime',
daily_price: 1.2,
})
.set('Authorization', `Bearer ${token}`);
const response = await request(app)
.get(`/materials/${material.id}`)
.set('Authorization', `Bearer ${token}`);
expect(response.body).toMatchObject({
name: 'andaime',
daily_price: 1.2,
});
});
it('should not be able to list one material that does not exists', async () => {
const token = await getToken();
const response = await request(app)
.get('/materials/12e5c331-1091-405f-b4e1-949000125129')
.set('Authorization', `Bearer ${token}`);
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: 'error',
message: 'Material does not exists',
}),
);
});
});
describe('Update', () => {
it('should be able to update daily_price field for one material by an id', async () => {
const token = await getToken();
const materialsRepository = getRepository(Material);
const { body: material } = await request(app)
.post('/materials')
.send({
name: 'Andaime',
daily_price: 1.2,
})
.set('Authorization', `Bearer ${token}`);
const response = await request(app)
.put(`/materials/${material.id}`)
.send({
name: '<NAME>',
daily_price: 1.5,
})
.set('Authorization', `Bearer ${token}`);
const dbMaterial = await materialsRepository.findOne(material.id);
expect(response.status).toBe(204);
expect(dbMaterial).toMatchObject({
name: 'andaime',
daily_price: 1.5,
});
});
it('should not be able to update a material that does not exists', async () => {
const token = await getToken();
const response = await request(app)
.put('/materials/12e5c331-1091-405f-b4e1-949000125129')
.send({
name: '<NAME>',
daily_price: 1.5,
})
.set('Authorization', `Bearer ${token}`);
expect(response.status).toBe(400);
expect(response.body).toMatchObject(
expect.objectContaining({
status: 'error',
message: 'Material does not exists',
}),
);
});
});
});
<file_sep>/src/modules/materials/infra/http/validators/MaterialList.ts
import { celebrate, Segments, Joi } from 'celebrate';
export default celebrate({
[Segments.QUERY]: Joi.object().keys({
page: Joi.number().default(1),
name: Joi.string().default(''),
}),
});
<file_sep>/src/modules/clients/infra/http/controllers/SoftDeleteClientsController.ts
import { Request, Response } from 'express';
import { container } from 'tsyringe';
import SoftDeleteClientService from '@modules/clients/services/SoftDeleteClientService';
export default class SoftDeleteClientsController {
public async delete(req: Request, res: Response): Promise<Response> {
const { id } = req.params;
const softDeleteClient = container.resolve(SoftDeleteClientService);
await softDeleteClient.execute({ id });
return res.status(204).json();
}
}
<file_sep>/src/@types/express.d.ts
interface Material {
id: string;
name: string;
daily_price: number;
created_at: Date;
updated_at: Date;
}
declare namespace Express {
export interface Request {
client: {
id: string;
};
user: {
id: string;
};
material: Material;
}
}
<file_sep>/src/modules/clients/dtos/IFindAllDTO.ts
export default interface IFindAllDTO {
deleted: boolean;
}
<file_sep>/__tests__/integration/Authentication.spec.ts
import request from 'supertest';
import { Connection, getConnection } from 'typeorm';
import { runSeeder } from 'typeorm-seeding';
import createConnection from '../../src/database';
import UserAdminSeed from '../../src/database/seeds/UserAdmin.seed';
import app from '../../src/app';
let connection: Connection;
describe('Authentication', () => {
beforeAll(async () => {
connection = await createConnection('test-connection');
await connection.runMigrations();
await runSeeder(UserAdminSeed);
});
afterAll(async () => {
await connection.query('DELETE FROM users');
const mainConnection = getConnection();
await connection.close();
await mainConnection.close();
});
it('All routes must be authenticated', async () => {
const clientsResponse = await request(app).get('/clients');
expect(clientsResponse.status).toBe(401);
expect(clientsResponse.body).toMatchObject(
expect.objectContaining({
status: 'error',
message: 'JWT token is missing' || 'Invalid JWT token',
}),
);
});
});
<file_sep>/src/modules/contracts/dtos/IFilterOptionsDTO.ts
export default interface IFilterOptionsDTO {
page: number;
name?: string | undefined;
finished: boolean;
}
<file_sep>/__tests__/todo.md
- [x] Não deve ser possivel realizar uma requisição sem estar autenticado, exceto rota de login
- [ ] Todas as listagens devem ser ordenadas pelo nome ou algo similar
- [ ] Todas as listagens não deve retorar os campos `created_at` e `updated_at`
- Cliente
- [x] Deve ser possivel criar um registro
- [x] Não deve ser possivel ter registros duplicados pelo CPF, incluindo os inativos
---
- [x] Deve ser possivel listar todos os registros
- [x] Deve ser possivel listar todos os registros em soft delete
- [x] Deve ser possivel listar apenas um registro
- [x] Não deve ser possivel listar um cliente que não existe
---
- [x] Deve ser possivel atualizar um registro
- [x] Não deve ser possivel atualizar um client que não existe
- [x] Não deve ser possivel atualizar um registro e por um CPF ja existente, incluindo os inativos
- [x] Não deve ser possivel atualizar um registro em soft delete
- [x] Não deve ser possivel atualizar o campo `deleted_at`
---
- [x] Deve ser possivel inativar um registro
- [x] Não deve ser possivel inativar um cliente que não existe
<br />
- Session
- [x] Deve ser possivel criar uma sessão
- [x] Não deve ser possivel criar uma sessão com dados invalidos
<br />
- Material
- [x] Deve ser possivel criar um registro
- [x] Não deve ser possivel ter registros duplicados pelo nome
---
- [x] Deve ser possivel listar todos os registros
- [x] Não deve ser possivel listar um materail que não existe
---
- [x] Deve ser possivel atualizar um registro - Apenas o daily_price
- [x] Não deve ser possivel atualizar um registro que não existe
- Contratos
- [x] Deve ser possivel criar um registro
- [x] Durante a criação de um contrato, deve ser criado seus respectivos contract_items
- [x] Não deve ser possivel criar um registro para um cliente inexistente
- [x] Não deve ser possivel criar um registro sem as informações de materiais
---
- [x] Deve ser possivel listar todos os contracts
- [x] Deve ser possivel listar um unico contract
- [x] Não deve ser possivel listar um contract inexistente
---
- [x] Deve ser possivel finalizar um contrato
- Gerar a data de coleta e preencher o campo na database
- Receber o valor de coleta, caso exista, e preencher na database
- Calcular o total de dias
- Calcular o valor final e preencher na database
- [x] Não deve ser possivel finalizar um contrato inexistente
<file_sep>/src/modules/materials/services/ShowMaterialService.ts
import { inject, injectable } from 'tsyringe';
import Material from '@modules/materials/infra/typeorm/entities/Material';
import IMaterialsRepository from '@modules/materials/repositories/IMaterialsRepository';
interface IRequest {
id: string;
}
@injectable()
class ShowMaterialService {
constructor(
@inject('MaterialsRepository')
private materialsRepository: IMaterialsRepository,
) {}
public async execute({ id }: IRequest): Promise<Material | undefined> {
const material = await this.materialsRepository.findById(id);
return material;
}
}
export default ShowMaterialService;
<file_sep>/src/modules/clients/repositories/IClientsRepository.ts
import Client from '@modules/clients/infra/typeorm/entities/Client';
import ICreateClientDTO from '@modules/clients/dtos/ICreateClientDTO';
import IFindByCPFWithDeletedDTO from '@modules/clients/dtos/IFindByCPFWithDeletedDTO';
import IFindAllDTO from '@modules/clients/dtos/IFindAllDTO';
import IFindAllWithPaginationAndSearchDTO from '../dtos/IFindAllWithPaginationAndSearchDTO';
interface IResponseFindAllWithPaginationAndSearch {
clients: Client[];
count: number;
}
export default interface IClientsRepository {
findAll(options: IFindAllDTO): Promise<Client[]>;
findById(id: string): Promise<Client | undefined>;
findAllWithPaginationAndSearch(
data: IFindAllWithPaginationAndSearchDTO,
): Promise<IResponseFindAllWithPaginationAndSearch>;
findByCPFWithDeleted(
cpf: string,
options?: IFindByCPFWithDeletedDTO,
): Promise<Client | undefined>;
create(data: ICreateClientDTO): Promise<Client>;
softDeleteById(id: string): Promise<void>;
save(client: Client): Promise<Client>;
}
<file_sep>/src/modules/clients/infra/typeorm/entities/Client.ts
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
DeleteDateColumn,
OneToMany,
} from 'typeorm';
import Contract from '@modules/contracts/infra/typeorm/entities/Contract';
@Entity('clients')
class Client {
@PrimaryGeneratedColumn('uuid')
id: string;
@OneToMany(() => Contract, contract => contract.client)
contracts: Contract[];
@Column()
name: string;
@Column()
cpf: string;
@Column()
phone_number: string;
@Column()
address: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@DeleteDateColumn()
deleted_at: Date;
}
export default Client;
<file_sep>/src/modules/clients/services/CreateClientService.ts
import { injectable, inject } from 'tsyringe';
import AppError from '@shared/errors/AppError';
import IClientsRepository from '@modules/clients/repositories/IClientsRepository';
import Client from '@modules/clients/infra/typeorm/entities/Client';
interface IRequest {
name: string;
cpf: string;
phone_number: string;
address: string;
}
@injectable()
class CreateClientService {
constructor(
@inject('ClientsRepository')
private clientsRepository: IClientsRepository,
) {}
public async execute({
name,
cpf,
phone_number,
address,
}: IRequest): Promise<Client> {
const clientExists = await this.clientsRepository.findByCPFWithDeleted(cpf);
if (clientExists) {
throw new AppError('Client already exists');
}
const client = await this.clientsRepository.create({
name,
cpf,
phone_number,
address,
});
return client;
}
}
export default CreateClientService;
<file_sep>/src/modules/clients/dtos/IFindByCPFWithDeletedDTO.ts
export default interface IFindByCPFWithDeletedDTO {
execept_client_id?: string;
}
|
a3b4d26d3831f93fae9ae706d258e73716913a83
|
[
"Markdown",
"TypeScript",
"YAML",
"Shell"
] | 57
|
TypeScript
|
sdavi38/pontoloc-api
|
619ab88c1ec901ab48dca447463364946538ee27
|
5fc24e81978160f8e5389d3926dcf1434522caa7
|
refs/heads/main
|
<repo_name>shailen4020/Test2P<file_sep>/src/main/java/com/company/AddController.java
package com.company;
//import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AddController {
@RequestMapping("add")
public String hello(@RequestParam("t1") int i,@RequestParam("t2") int j )
{
return (i+j)+"";
}
}
|
277b64785fdf1719279bee5fd94af1803905e184
|
[
"Java"
] | 1
|
Java
|
shailen4020/Test2P
|
8fc16068ba808ae64219d07b7c13648fe5f58e1f
|
dc41b9b3852c03e3b7bd8f95860b2608d4a0972f
|
refs/heads/main
|
<repo_name>african-marketplace-tt7/frontend<file_sep>/african-marketplace/src/components/Dashboard.js
import "../assets/css/main.css";
import React, { useEffect } from "react";
import { connect } from "react-redux";
import { NavLink } from "react-router-dom";
//Actions
import { fetchCurrentUser } from "../store/actions/currentUserActions";
import { fetchAllMarkets } from "../store/actions/marketActions";
// Components
import HeaderNav from "./HeaderNav";
import { Button } from "./Button";
import BannerTabs from "./BannerTabs";
const Dashboard = ({ fetchCurrentUser, fetchAllMarkets }) => {
useEffect(() => {
fetchCurrentUser();
fetchAllMarkets();
}, []);
return (
<div id="page-wrapper">
<HeaderNav />
<BannerTabs />
{/* <Button title="Click me" type="primary" onClick={() => {
console.log("Click")
}} size="large"/>
<Button title="Click me" type="primary" onClick={() => {
console.log("Click")
}}/>
<Button title="Click me" type="primary" onClick={() => {
console.log("Click")
}} size="small"/> */}
</div>
);
};
const mapStateToProps = (state) => {
return {
currentUser: state.userReducer,
markets: state.marketsReducer,
};
};
export default connect(mapStateToProps, {
fetchCurrentUser,
fetchAllMarkets,
})(Dashboard);
<file_sep>/african-marketplace/src/components/AddItem.js
import React, { useState, useEffect } from "react";
import { connect } from "react-redux";
//Actions
import { addSaleItem } from "../store/actions/currentUserActions";
const AddItem = ({ addSaleItem, userState }) => {
const initalFormValues = {
commodityCat: "",
subCat: "",
commodityProduct: "",
description: "",
salePrice: 0,
quantity: 0,
marketsSold: [],
};
const catArr = [
"-Select Category-",
"Animal Products",
"Beans",
"Cereals - Maize",
"Cereals - Other",
"Cereals - Rice",
"Fruits",
"Other",
"Peas",
"Roots & Tubers",
"Seeds & Nuts",
"Vegetables",
];
const animalProductsSub = ["Animal Products", "Livestock", "Poultry"];
const cerealsOtherSub = ["Barley", "Millet", "Sorghum", "Wheat"];
const fruitsSub = [
"Avocado",
"Bananas",
"Fruits",
"Lemons",
"Limes",
"Mangoes",
"Oranges",
"Pawpaw",
"Pineapples",
];
const otherSub = ["Coffee", "Tea", "Tobacco", "Vanilla"];
const rootsAndTubersSub = ["Cassava", "Potatoes"];
const seedsAndNutsSub = ["Nuts", "Simsim", "Sunflowers"];
const vegetablesSub = [
"Brinjals",
"Cabbages",
"Capsicums",
"Carrots",
"Cauliflower",
"Chillies",
"Cucumber",
"Ginger",
"Kales",
"Lettuce",
"Onions",
"Tomatoes",
];
const [formValues, setForumValues] = useState(initalFormValues);
const getSubCat = (category) => {
switch (category) {
case "Animal Products":
return animalProductsSub.map((animalProduct) => (
<option value={animalProduct}>{animalProduct}</option>
));
case "Beans":
return <option>Beans</option>;
case "Cereals - Maize":
return <option>Cereals - Maize</option>;
case "Cereals - Other":
return cerealsOtherSub.map((cereal) => (
<option value={cereal}>{cereal}</option>
));
case "Cereals - Rice":
return <option>Cereals - Rice</option>;
case "Fruits":
return fruitsSub.map((fruit) => <option value={fruit}>{fruit}</option>);
case "Other":
return otherSub.map((other) => <option value={other}>{other}</option>);
case "Peas":
return <option>Peas</option>;
case "Roots & Tubers":
return rootsAndTubersSub.map((root) => (
<option value={root}>{root}</option>
));
case "Seeds & Nuts":
return seedsAndNutsSub.map((seed) => (
<option value={seed}>{seed}</option>
));
case "Vegetables":
return vegetablesSub.map((vegetable) => (
<option value={vegetable}>{vegetable}</option>
));
default:
return <option></option>;
}
};
const handleChange = (e) => {
setForumValues({ ...formValues, [e.target.name]: e.target.value });
};
const submitItemHandler = (e) => {
e.preventDefault();
addSaleItem(formValues);
setForumValues(initalFormValues);
};
return (
<div>
<form onSubmit={submitItemHandler}>
<div>
<label>
Category:
<select
name="commodityCat"
value={formValues.commodityCat}
onChange={handleChange}
>
{catArr.map((cat) => (
<option value={cat}>{cat}</option>
))}
</select>
</label>
</div>
<div>
<label>
Sub Category:
<select
name="subCat"
value={formValues.subCat}
onChange={handleChange}
>
{getSubCat(formValues.commodityCat)}
</select>
</label>
</div>
<div>
<label>
Product:
<input
name="commodityProduct"
type="text"
value={formValues.commodityProduct}
onChange={handleChange}
/>
</label>
</div>
<div>
<label>
Description:
<input
name="description"
type="text"
value={formValues.description}
onChange={handleChange}
/>
</label>
</div>
<div>
<label>
Quantity (kgs):
<input
name="quantity"
type="number"
value={formValues.quantity}
onChange={handleChange}
/>
</label>
</div>
<div>
<label>
Sale Price:
<input
name="salePrice"
type="number"
value={formValues.salePrice}
onChange={handleChange}
/>
</label>
</div>
<button>Add Item</button>
</form>
</div>
);
};
const mapStateToProps = (state) => ({
userState: state.userReducer,
});
export default connect(mapStateToProps, {
addSaleItem,
})(AddItem);
<file_sep>/african-marketplace/src/components/MarketplaceTab.js
import React, { useState } from "react";
import { connect } from "react-redux";
import MarketLocationCard from "./MarketLocationCard";
const MarketplaceTab = (props) => {
const { marketLocations } = props.allMarkets;
const { userMarkets } = props;
const [filterView, setFilterView] = useState();
const onChangeFilterView = (e) => {};
return (
<div className="tab-section">
<section className="sidebar">
<label>View Editor</label>
<select value={filterView} type="select">
<option value="">All Markets</option>
<option value="">Your Markets</option>
</select>
</section>
{props.allMarkets.isLoading && <p>loading Marketplaces...</p>}
<div className="marketplace" datatype>
{marketLocations &&
marketLocations.map((market) => (
<MarketLocationCard market={market} key={market.marketlocationid} />
))}
</div>
</div>
);
};
const mapStateToProps = (state) => {
return {
allMarkets: state.marketsReducer,
userMarkets: state.userReducer.userData.marketLocations,
};
};
export default connect(mapStateToProps)(MarketplaceTab);
<file_sep>/african-marketplace/src/components/Sign-in.js
import React, { useState, useEffect } from "react";
import { Link, useHistory } from "react-router-dom";
import * as yup from "yup";
import axios from "axios";
import StyledSignIn from "./styles/StyledSignIn";
function SignIn(props) {
const { push } = useHistory();
//manage state for the form inputs
const [formState, setFormSate] = useState({
username: "",
password: "",
});
//managing error state
const [errors, setErrors] = useState({
username: "",
password: "",
});
//submit state checks whether the form can be submited
const [buttonDisabled, setButtonDisabled] = useState(true);
//inline validation on one key/value pair at a time
const validateChange = (event) => {
//.reach is in the yup library
//returns a promise
yup
.reach(formSchema, event.target.name)
.validate(event.target.value)
.then((valid) => {
//value from valid comes from .validate
//if the input is passing formSchema
setErrors({ ...errors, [event.target.name]: "" });
})
.catch((error) => {
//if the input is breakign formSchema
//capture the error message
setErrors({ ...errors, [event.target.name]: error.errors[0] });
});
//need to call this function the onChange function = inputChnage
};
//onChange function
const inputChange = (event) => {
//allows us to pass around synthertic events
event.persist();
const newFormState = {
...formState,
[event.target.name]: event.target.value,
};
//event is being passed in to the validateChange function i created
validateChange(event);
setFormSate(newFormState);
};
//form schema set of rules
//object is coming from yup library
//shape function takes in an object {}
const formSchema = yup.object().shape({
username: yup.string().required("Username is required"),
password: yup.string().required("<PASSWORD>"),
});
useEffect(() => {
//isValid comes from the yup library
//checking formSchema against formState
//comparing the keys and the values
//returns a promise
formSchema.isValid(formState).then((valid) => {
//we can check the process has been completed
setButtonDisabled(!valid);
});
}, [formSchema, formState]);
//do something every time formState changes
//onSubmit function
const formSubmit = (event) => {
event.preventDefault();
axios
.post(
"https://african-marketplace-tt7.herokuapp.com/login",
`grant_type=password&username=${formState.username}&password=${<PASSWORD>}`,
{
headers: {
// btoa is converting our client id/client secret into base64
Authorization: `Basic ${btoa("lambda-client:lambda-secret")}`,
"Content-Type": "application/x-www-form-urlencoded",
},
}
)
.then((res) => {
localStorage.setItem("token", res.data.access_token);
push("/dashboard");
})
.catch((err) => {
console.log(err);
});
};
return (
<StyledSignIn>
<p className="loginTitle">Log In</p>
<form className="signIn" onSubmit={formSubmit}>
<div className="loginForm">
<label htmlFor="username">
Username
<input
id="username"
type="text"
name="username"
value={formState.username}
placeholder="USERNAME"
onChange={inputChange}
/>
{errors.username.length > 0 ? <p>{errors.username}</p> : null}
</label>
</div>
<div className="loginForm">
<label htmlFor="password">
Password
<input
id="<PASSWORD>"
type="<PASSWORD>"
name="password"
value={formState.password}
placeholder="<PASSWORD>"
onChange={inputChange}
/>
{errors.password.length > 0 ? <p>{errors.password}</p> : null}
</label>
</div>
<button type="submit" disabled={buttonDisabled}>
Log In
</button>
<p>
<Link className="" to="/signup">
Not a member?
</Link>
</p>
<p>
<Link className="" to="/">
Home Page
</Link>
</p>
</form>
</StyledSignIn>
);
}
export default SignIn;
<file_sep>/african-marketplace/src/components/MyStoreTab.js
import React from "react";
import { connect } from "react-redux";
import AddItem from "./AddItem";
//Actions
import {
fetchCurrentUser,
deleteSaleItem,
} from "../store/actions/currentUserActions";
const MyStoreTab = (props) => {
const { itemsForSale } = props.userState.userData;
const handleDelete = (e) => {
props.deleteSaleItem(e.target.dataset.key);
};
return (
<div className="tab-section">
<section className="sidebar">
<label>View Editor</label>
<AddItem />
</section>
<div className="product-list">
<h3>Your Products</h3>
{itemsForSale.map((item) => {
return (
<>
<p>{item.commodityProduct}</p>
<button data-key={item.itemid} onClick={handleDelete}>
Delete
</button>
</>
);
})}
</div>
</div>
);
};
const mapStateToProps = (state) => {
return {
userState: state.userReducer,
};
};
export default connect(mapStateToProps, {
fetchCurrentUser,
deleteSaleItem,
})(MyStoreTab);
<file_sep>/README.md
# frontend
Front End for African Marketplace
API Docs: https://african-marketplace-tt7.herokuapp.com/swagger-ui.html#/item-controller
Proof of COncept: http://sautiafrica.org/
Example: https://african-marketplace-one.vercel.app/mystore
Things to explore:
https://redux-saga.js.org/
https://github.com/reduxjs/reselect
https://recoiljs.org/
https://formik.org/
<file_sep>/african-marketplace/src/components/SignupForm/StyledSignupForm.js
import styled from "styled-components";
const StyledSignupForm = styled.div`
color: rgb(17, 63, 114);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #f5de76;
height: 100vh;
* {
// border: 1px solid gold;
}
form {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
button {
width: 50%;
margin: 10px;
padding: 5px;
outline: none;
border: none;
border-radius: 5px;
color: rgb(209, 205, 193);
background-color: rgb(17, 63, 114);
border: 2px solid transparent; //keeps the box from resizing on hover.
}
button:hover {
box-sizing: border-box;
background-color: white;
color: tomato;
// font-weight: bold;
border: 2px solid purple;
}
.textInputClass,
.selectInputClass {
display: flex;
flex-direction: column;
align-items: flex-start;
}
label {
display: flex;
align-items: center;
margin: 0;
color: rgb(17, 63, 114);
input {
// height: 3px;
}
p {
color: tomato;
margin: 0;
font-weight: bold;
}
}
}
select option,
select {
color: tomato;
}
input {
color: purple;
}
`;
export default StyledSignupForm;
<file_sep>/african-marketplace/src/store/actions/marketActions.js
import { axiosWithAuth } from "../../utils/axiosWithAuth";
export const fetchAllMarkets = () => {
return (dispatch) => {
dispatch({ type: "FETCH_ALLMARKETS_START" });
axiosWithAuth()
.get("/marketlocations/marketlocations")
.then((res) => {
dispatch({ type: "FETCH_ALLMARKETS_SUCCESS", payload: res.data });
})
.catch((err) => {
dispatch({ type: "SET_ERROR", payload: err.message });
});
};
};
<file_sep>/african-marketplace/src/components/Inputs/SelectInput/Option/Option.js
import React from 'react';
const Option = ({details}) => {
return (
<option value={details}>{details}</option>
)
}
export default Option;<file_sep>/african-marketplace/src/components/Inputs/TextInput/TextInput.js
import React from 'react';
const TextInput = ({name, onChange, value, displayName, register, requirements, errorMessage}) => {
const inputType = name === 'email' ? 'email' : 'text'
return (
<label htmlFor={name}> {displayName}:
<input type={inputType} id={name} name={name} value={value} onChange={onChange} ref={register(requirements)} placeholder={displayName}/>
{errorMessage[name] && <p>{requirements.errorMessage}</p>}
</label>
)
}
export default TextInput;<file_sep>/african-marketplace/src/components/MarketLocationCard.js
import React from "react";
export default function MarketLocationCard({ market }) {
const { name, street, city, country } = market;
return (
<div className="market-card">
<div className="info-container">
<h2>{name}</h2>
<p>{street}</p>
<p>{city}</p>
<p>{country}</p>
<button className="primary small">Add Market</button>
</div>
</div>
);
}
<file_sep>/african-marketplace/src/store/reducers/userReducer.js
export const initialState = {
isLoading: false,
error: "",
userData: {
username: "",
photoURL: "",
email: "",
firstName: "",
lastName: "",
city: "",
country: "",
primaryLanguage: "",
preferredCurrency: "",
marketLocations: [
{
name: "east",
street: "",
city: "",
country: "",
},
],
itemsForSale: [
{
commodityCat: "",
subCat: "",
commodityProduct: "",
description: "",
salePrice: 0,
quantity: 50,
marketsSold: [
{
marketlocationid: 5,
name: "",
street: "",
city: "",
country: "",
},
],
},
],
},
};
export const userReducer = (state = initialState, action) => {
switch (action.type) {
case "FETCH_CURRENTUSER_START":
return {
...state,
isLoading: true,
error: "",
};
case "FETCH_CURRENTUSER_SUCCESS":
return {
...state,
isLoading: false,
userData: action.payload,
};
case "UPDATE_SALEITEMS_START":
return {
...state,
isLoading: true,
};
case "UPDATE_SALEITEMS_SUCCESS":
return {
...state,
isLoading: false,
userData: { ...state.userData, itemsForSale: action.payload },
};
case "DELETE_SALEITEM_START":
return {
...state,
isLoading: true,
};
case "DELETE_SALEITEM_SUCCESS":
return {
...state,
isLoading: false,
userData: {
...state.userData,
itemsForSale: state.userData.itemsForSale.filter(
(item) => item.itemid !== Number(action.payload)
),
},
};
case "SET_ERROR":
return {
...state,
isLoading: false,
error: action.payload,
};
default:
return state;
}
};
<file_sep>/african-marketplace/src/store/reducers/marketsReducer.js
export const initialState = {
isLoading: false,
error: "",
marketLocations: [],
};
export const marketsReducer = (state = initialState, action) => {
switch (action.type) {
case "FETCH_ALLMARKETS_START":
return {
...state,
isLoading: true,
error: "",
};
case "FETCH_ALLMARKETS_SUCCESS":
return {
...state,
isLoading: false,
marketLocations: action.payload,
};
case "SET_ERROR":
return {
...state,
isLoading: false,
error: action.payload,
};
default:
return state;
}
};
<file_sep>/african-marketplace/src/components/Button.js
import React from 'react'
export const Button = ({title, type, onClick, size, disabled}) => {
return (
<button onClick={onClick} className={["button", type, size].join(" ")} disabled={disabled}>
{title}
</button>
)
}
<file_sep>/african-marketplace/src/store/actions/currentUserActions.js
import { axiosWithAuth } from "../../utils/axiosWithAuth";
export const fetchCurrentUser = () => {
return (dispatch) => {
dispatch({ type: "FETCH_CURRENTUSER_START" });
axiosWithAuth()
.get("/users/getuserinfo")
.then((res) => {
dispatch({ type: "FETCH_CURRENTUSER_SUCCESS", payload: res.data });
})
.catch((err) => {
dispatch({ type: "SET_ERROR", payload: err.message });
});
};
};
export const addSaleItem = (newItem) => {
return (dispatch) => {
dispatch({ type: "UPDATE_SALEITEMS_START" });
axiosWithAuth()
.post("/items/item", newItem)
.then((res) => {
console.log("response", res);
dispatch({
type: "UPDATE_SALEITEMS_SUCCESS",
payload: res.data.user.itemsForSale,
});
})
.catch((err) => {
dispatch({ type: "SET_ERROR", payload: err.message });
});
};
};
export const deleteSaleItem = (id) => {
return (dispatch) => {
dispatch({ type: "DELETE_SALEITEM_START" });
axiosWithAuth()
.delete(`/items/item/${id}`)
.then((res) => {
console.log("response", res);
dispatch({
type: "DELETE_SALEITEM_SUCCESS",
payload: id,
});
})
.catch((err) => {
dispatch({ type: "SET_ERROR", payload: err.message });
});
};
};
<file_sep>/african-marketplace/src/components/ItemCard.js
import React from "react";
export default function ItemCard(props) {
const {
commodityCat,
subCat,
commodityProduct,
description,
salePrice,
quantity,
marketsSold,
} = props.item;
return (
<div>
<h2>{commodityProduct}</h2>
<p>Category: {commodityCat}</p>
<p>Sub Category: {subCat}</p>
<p>Description: {description}</p>
<p>Price: {salePrice}</p>
<p>Quantity: {quantity}kgs</p>
<div>
Markets Sold:{" "}
{marketsSold.map((market) => (
<p>{market.name}</p>
))}
</div>
</div>
);
}
<file_sep>/african-marketplace/src/components/Inputs/SelectInput/SelectInput.js
import React from 'react';
import Option from './Option/Option';
const SelectInput = ({ name, languages, currencies, value, onChange, displayName, register}) => {
let options = [];
if (name === 'preferredCurrency') {
options = currencies;
} else if (name === 'primaryLanguage') {
options = languages;
}
let optionsToRender = options.map((option, i) => {
return <Option details={option} key={i} />
})
return (
<div>
<label name={name}> {displayName}:
<select type="select" name={name} value={value} onChange={onChange} ref={register({required: true})}>
<option value=''>---Please select your preference---</option>
{optionsToRender}
</select>
</label>
</div>
)
}
export default SelectInput;<file_sep>/african-marketplace/src/components/styles/StyledSignIn.js
import styled from "styled-components";
import img from "../../assets/images/banner.jpg";
const StyledSignIn = styled.div`
background: url(${img});
background-repeat: no-repeat;
background-size: cover;
height: 100vh;
text-align: center;
padding-top: 25%;
color: #fdfdfd;
font-weight: bold;
form .loginForm {
margin: 2%;
label input {
background: rgba(0, 0, 0, 0.6);
width: 50%;
margin: 0 auto;
text-align: center;
}
}
.signIn button {
margin: 1rem 0;
font-weight: bold;
border: none;
background-color: #eb4933;
color: #fdfdfd;
}
.signIn a {
color: #fdfdfd;
}
`;
export default StyledSignIn;
<file_sep>/african-marketplace/src/store/reducers/index.js
import { combineReducers } from "redux";
import { userReducer } from "./userReducer";
import { marketsReducer } from "./marketsReducer";
export default combineReducers({
userReducer,
marketsReducer,
});
<file_sep>/african-marketplace/src/components/styles/StyledBannerTabs.js
import styled from "styled-components";
import img from "../../assets/images/banner.jpg";
const StyledBannerTabs = styled.div`
* {
/* border: 1px solid green; */
}
.hero-image-container {
background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),
url(${img});
height: 10rem;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
position: relative;
display: flex;
padding: 0 10px;
padding-bottom: 4px;
align-items: flex-end;
justify-content: space-between;
border-bottom: solid 10px black;
h3 {
margin-bottom: 0;
}
}
`;
export default StyledBannerTabs;
<file_sep>/african-marketplace/src/App.js
import { Route, Switch } from "react-router-dom";
import React from "react";
import "./App.css";
import Dashboard from "./components/Dashboard";
import PrivateRoute from "./components/PrivateRoute";
import SignIn from "./components/Sign-in";
import SignupForm from "./components/SignupForm/SignupForm";
function App() {
return (
<div className="App">
<Switch>
{/* App Front End */}
<PrivateRoute exact path="/dashboard" component={Dashboard} />
<Route exact path="/login" component={SignIn} />
<Route exact path="/" component={SignIn} />
<Route exact path="/signup" component={SignupForm} />
</Switch>
</div>
);
}
export default App;
|
a7453ca03deb2049d44d741dfe31db90b07e32cc
|
[
"JavaScript",
"Markdown"
] | 21
|
JavaScript
|
african-marketplace-tt7/frontend
|
85c5f68c7c5c5284675ece7de99856ca10f034f0
|
942538f88e9060d8c232b212829a7f07fd345200
|
refs/heads/master
|
<repo_name>AaguoTeam/aaguo<file_sep>/core/modules/party/install/install.php
<?php
$CFG =& $_G['loader']->model('config');
@$CFG->write_js();
unset($CFG);
?><file_sep>/core/modules/tuan/model/cjdata_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_tuan_tgsite extends ms_model {
var $table = 'dbpre_tuan_cjdata';
var $key = 'id';
var $model_flag = 'tuan';
function __construct() {
parent::__construct();
$this->model_flag = 'tuan';
$this->init_field();
$this->modcfg = $this->variable('config');
}
function msm_tuan_tgsite() {
$this->__construct();
}
function init_field() {
$this->add_field('subject,shortsubject,siteid,groupsite,url,thumb,oldprice,nowprice,discount,lasttime,starttime,sortorder,cityid,hits,ispassed,userid,keyword,updatetime,cityname,citysname,recommend,nowpeople,commentcount,favcount,bizgroup,bizname,big_catelist,small_catelist,big_catelist_catename,small_catelist_catename,groupkey,temporder,shopname');
//$this->add_field_fun('content,reply', '_T');
//$this->add_field_fun('tid,sort', 'intval');
}
function save($post, $id=null) {
$edit = $id > 0;
if($edit) {
if(!$detail = $this->read($id)) redirect('tuan_tgsite_empty');
}
$id = parent::save($post,$id);
return $id;
}
//数据提交检测函数,实现父类的方法
function check_post($post, $edit = false) {
}
//团购数据采集
function spider($ids) {
}
}
?><file_sep>/templates/item/vip/album.php
<?exit?>
<!--{eval
$_HEAD['title'] = $subject[name] . $subject[subname] . 的商家相册;
}-->
<!--{template 'header', 'item', $subject[templateid]}-->
<link href="{URLROOT}/img/vipfiles/css/shopEx_$subject[c_vipstyle].css" rel="stylesheet" type="text/css" />
<body>
<div class="wrap">
<div id="header">
<div id="crumb">
<p id="crumbL"><a href="{url modoer/index}">首页</a> » {print implode(' » ', $urlpath)} » $subject[name] $subject[subname]
<p id="crumbR"><a href="javascript:post_log($subject[sid]);">补充信息</a> | <a href="{url item/member/ac/subject_add/subbranch_sid/$subject[sid]}">增加分店</a> | <a href="{url member/index}">管理本店</a></p>
</div>
<div id="shopBanner">
<h1>$subject[name] $subject[subname]</h1>
<p>
<!--{if $subject[c_add]}-->
<B>地址:</B></LABEL>$subject[c_add]
<!--{/if}-->
<!--{if $subject[c_tel]}-->
<B>电话:</B></LABEL>$subject[c_tel]</p>
<!--{/if}-->
<div class="headerPic">
<img src="{if $subject[c_vipbanner]}$subject[c_vipbanner]{else}{URLROOT}img/haibao/nonbanner.png{/if}" alt="$subject[name] $subject[subname]店铺海报" width="950" height="150"/>
</div>
</div>
<div id="nav">
<ul>
<!--
<li><a href="#"><span>Array</span></a></li>
<li><a href="#"><span></span></a></li>
<li class="special"><a href="#"><span>导航栏介绍</span></a></li>
-->
<li><a href="{url item/detail/id/$subject[sid]}"><span>首页</span></a></li>
<li><a href="{url article/list/sid/$sid}"><span>店铺资讯</span></a> </li>
<li><a href="{url fenlei/list/sid/$sid}"><span>诚聘英才</span></a> </li>
<li><a href="{url product/list/sid/$sid}"><span>产品展厅</span></a> </li>
<li><a href="{url coupon/list/sid/$sid}"><span>优惠打折</span></a> </li>
<li class="current" ><a href="{url item/pic/sid/$subject[sid]}"><span>商家相册</span></a> </li>
<li><a href="{url item/vipabout/id/$subject[sid]}"><span>关于我们</span></a></li>
<li><a href="{url item/vipreview/id/$subject[sid]}"><span>会员点评</span></a></li>
<li><a href="{url item/vipguestbook/id/$subject[sid]}"><span>留言板</span></a></li>
</ul>
</div>
</div>
<div id="smartAd"><img src="{if $subject[c_vipbanner2]}$subject[c_vipbanner2]{else}{URLROOT}img/haibao/non.png{/if}" alt="$subject[name] $subject[subname]店铺海报"/></a><br />
</div>
<div id="mainBody">
<div id="mainBodyL">
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>【$subject[name] $subject[subname]】</h2>
<p class="deafBoxTitMore"><a href="{url item/vipabout/id/$subject[sid]}">更多</a></p>
</div>
<div class="deafBoxCon">
<dl>
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td align="center" valign="middle">
<a href="{url item/pic/sid/$subject[sid]}"><img src="{URLROOT}/{if $subject[thumb]}$subject[thumb]{else}static/images/noimg.gif{/if}" alt="$subject[name]" width="270" height="200" /></a>
</td>
</tr>
</table>
<div class="leftnr">
<!--{if $subject[finer]}-->
店铺级别:<img src="{URLROOT}/img/vipfiles/img/vip$subject[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<div class="subject">
<h2><a href="{url item/detail/id/$sid}" src="$subject[thumb]" onMouseOver="tip_start(this,1);">$subject[name] $subject[subname]</a></h2>
<!--{eval $reviewcfg = $_G['loader']->variable('config','review');}-->
<p class="start start{print get_star($subject[avgsort],$reviewcfg[scoretype])}"></p>
<table class="subject_field_list" border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2"><span class="font_2">$subject[reviews]</span>点评,
<span class="font_2">$subject[guestbooks]</span>留言,
<span class="font_2">$subject[pageviews]</span>浏览</td>
</tr>
$subject_field_table_tr
</table>
<a class="abtn1" href="{url review/member/ac/add/type/item_subject/id/$subject[sid]}"><span>我要点评</span></a>
<a class="abtn2" href="javascript:add_favorite($sid);"><span>收藏</span></a>
<a class="abtn2" href="{url item/detail/id/$sid/view/guestbook}#guestbook"><span>留言</span></a>
<div class="clear"></div>
</dl>
</div>
</div>
<div id="position" class="deafBox">
<div class="deafBoxTit">
<h2>商户所在位置</h2>
</div>
<div class="deafBoxCon">
<!--{eval $mapparam = array(
'width' => '270',
'height' => '265',
'title' => $subject[name] . $subject[subname],
'show' => $subject[mappoint]?1:0,
);}-->
<iframe id="item_map" src="{url index/map/width/270/height/150/title/$mapparam[title]/p/$subject[mappoint]/show/$mapparam[show]}" frameborder="0" scrolling="no"></iframe>
<div align="center"> <span><!--{if !$subject['mappoint']}--><a href="javascript:post_map($subject[sid], $subject[pid]);">地图未标注,我来标注</a><!--{else}--><a href="javascript:show_bigmap();">查看大图</a> <a href="javascript:post_map($subject[sid], $subject[pid]);">报错</a><!--{/if}--></span></div>
<script type="text/javascript">
function show_bigmap() {
var src = "{url index/map/width/600/height/400/title/$mapparam[title]/p/$subject[mappoint]/show/$mapparam[show]}";
var html = '<iframe src="' + src + '" frameborder="0" scrolling="no" width="100%" height="400" id="ifupmap_map"></iframe>';
dlgOpen('查看大图', html, 600, 450);
}
</script>
</div>
</div>
</div>
<div id="chaBodyR">
<div id="chaBodyRTit">
<h2>全部相册列表</h2>
</div>
<div class="listCon">
<ul id="roll">
{dbres $list $val}
<div class="photoOne">
<div class="photoOnePic"><a href="{url item/album/id/$val[albumid]}" src="$val[thumb]" target="_blank" onmouseover="tip_start(this,732);">
{if $val[thumb]}<img src="{URLROOT}/$val[thumb]" alt="$val[name]" width="120" height="90" />{else}<img src="{URLROOT}/static/images/noimg.gif" width="120" height="90"/>{/if}</a></div>
<h3>{sublen $val[name],9}
<p>{date $val[lastupdate],'Y-m-d'}</p></h3>
<p></p>
</div>
{/dbres}
</ul>
<!--{if !$total}--><div class="messageborder">暂时没有相册数据。</div><!--{/if}-->
<div class="clear"></div>
<div class="multipage">$multipage</div>
</div>
</div>
<div class="clear"></div>
</div>
<!--{template 'footer', 'item', $subject[templateid]}--><file_sep>/core/modules/tuan/admin/config.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$C =& $_G['loader']->model('config');
$op = _input('op');
if($_POST['dosubmit']) {
foreach($_POST['modcfg'] as $k=>$v) {
if($v=='******') unset($_POST['modcfg'][$k]);
}
$C->save($_POST['modcfg'], MOD_FLAG);
$LK =& $_G['loader']->model('link:mylink');
$LK->write_cache();
redirect('global_op_succeed', cpurl($module, 'config'));
} else {
$modcfg = $C->read_all(MOD_FLAG);
if($op == 'sms_config') {
$sms_api = _input('sms_api','powereasy','trim');
$file = MOD_ROOT . 'model' . DS . 'sms' . DS . 'sms_' . $sms_api . '_config.php';
include $file;
output();
}
$apis = array();
$apis = load_tuan_apis();
$_G['loader']->helper('form','member');
$admin->tplname = cptpl('config', MOD_FLAG);
}
function load_tuan_apis() {
$dir = MOD_ROOT . 'model' . DS . 'api' . DS;
$files = glob($dir . '*.php');
$result = array();
foreach($files as $f) {
$result[] = basename(strtolower($f),'.php');
}
return $result;
}
?><file_sep>/img/shop/js/jquery-topsearch.js
$(document).ready(function() {
// search
$(".isearch .select input").click(function() {
$(".isearch .select ul").toggle();
$(".isearch .select ul").focus();
});
$(".isearch .select ul li a").each(function(i) {
$(this).click(function() {
$(".isearch .select input").val($(this).text());
$("input#searchType").val($(this).attr("title"));
$(".isearch .select ul").toggle();
return false;
})
});
});<file_sep>/core/modules/article/admin/menus.inc.php
<?php
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$modmenus = array(
array(
'title' => '功能设置',
'article|模块配置|config',
),
array(
'title' => '分享管理',
'article|分类管理|category',
'article|分享审核|article|checklist',
'article|分享管理|article',
'article|下载远程图片|article|down_image',
'article|发布分享|article|add',
),
);
?><file_sep>/core/modules/modoer/item/model/threads_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
$_G ['loader']->model ( 'item:itembase', FALSE );
class msm_item_threads extends ms_model {
var $table = 'dz_forum_thread';
var $key = 'tid';
function __construct() {
parent::__construct ();
}
function msm_item_threads() {
$this->__construct ();
}
function init_field() {
$this->add_field ( 'tid,fid,subject,dateline,sortid' );
$this->add_field_fun ( 'dateline', 'intval' );
$this->add_field_fun ( 'subject', '_T' );
}
function getcount($where) {
$this->db->from($this->table,'t');
$this->db->where ('fid',$where );
return $this->db->count();
}
// 列表页查询
function getlist($select, $where, $orderby, $start, $offset, $total = TRUE) {
$result = array (0,'');
if ($total) {
$result [0] = $this->getcount ( $where );
}
//$this->db->join ( $this->table, 's.sid', $table, 'sf.sid', 'LEFT JOIN' );
$this->db->from ($this->table,'t');
$this->db->where ('fid',$where);
$this->db->select ( $select ? $select : '*' );
$this->db->order_by ( $orderby );
if ($offset > 0)
$this->db->limit ( $start, $offset );
$result [1] = $this->db->get ();
return $result;
}
}
?><file_sep>/core/modules/tuan/model/undertake_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_tuan_undertake extends ms_model {
var $table = 'dbpre_tuan_undertake';
var $key = 'id';
var $model_flag = 'tuan';
function __construct() {
parent::__construct();
$this->model_flag = 'tuan';
$this->init_field();
$this->modcfg = $this->variable('config');
}
function init_field() {
$this->add_field('twid,uid,username,linkman,price,goods_num,content,contact');
$this->add_field_fun('title,linkman,username,price,goods_num,contact', '_T');
$this->add_field_fun('uid,twid', 'intval');
$this->add_field_fun('content', '_TA');
}
//保存
function save($post, $id=null) {
$post['uid'] = $this->global['user']->uid;
$post['username'] = $this->global['user']->username;
$post['dateline'] = $this->global['timestamp'];
$id = parent::save($post);
if($id > 0) {
$TW =& $this->loader->model('tuan:wish');
$TW->undertake($post['twid'],1);
}
}
//提交检测
function check_post(& $post, $edit = false) {
if(!$post['linkman']) redirect('tuan_undertake_linkman_empty');
if(!$post['contact']) redirect('tuan_undertake_contact_empty');
if(!$post['price']) redirect('tuan_undertake_price_empty');
if(!$post['goods_num']) redirect('tuan_undertake_goods_num_empty');
if(!$post['content']) redirect('tuan_undertake_content_empty');
}
//判断是否已经提交申请
function exists($twid) {
$this->db->from($this->table);
$this->db->where('twid', $twid);
$this->db->where('uid', $this->global['user']->uid);
return $this->db->count();
}
//删除
function delete($ids) {
$ids = parent::get_keyids($ids);
$this->db->from($this->table);
$this->db->where('id', $ids);
$q = $this->db->get();
if(empty($q)) return;
$delids = array();
$twids = array();
while($v=$q->fetch_array()) {
$delids[$v['twid']][] = $v['id'];
}
$q->free_result();
$TW=& $this->loader->model('tuan:wish');
foreach($delids as $twid => $ls) {
$TW->undertake($twid,-count($ls));
}
parent::delete($ids);
}
}
?><file_sep>/core/modules/album/admin/templates/category.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/jquery.js"></script>
<script type="text/javascript" src="./static/javascript/autocomplete/jquery.autocomplete.min.js"></script>
<link rel="Stylesheet" href="./static/javascript/autocomplete/jquery.autocomplete.css" />
<div id="body">
<div class="space">
<div class="subtitle">分类查询</div>
<form method="get" action="<?=SELF?>">
<input type="hidden" name="module" value="<?=$module?>" />
<input type="hidden" name="act" value="<?=$act?>" />
<input type="hidden" name="op" value="<?=$op?>" />
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="50" class="altbg1">商户名称</td>
<td width="100">
<input type="text" id="sname" name="sname" class="txtbox3" />
</td>
<td width="50" class="altbg1" align="left">
<button type="submit" value="yes" name="dosubmit" class="btn2">查 询</button>
</td>
<td align="center" style="display:none" id="sidTips"></td>
</tr>
</table>
</form>
</div>
<form method="post" action="<?=cpurl($module,$act)?>" name="myform">
<div class="space">
<div class="subtitle">分类列表</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr class="altbg1">
<td width="60">ID</td>
<td width="80">排序</td>
<td width="100">分类名称</td>
<td width="300">所属商家</td>
</tr>
<?if($total):?>
<?while($val=$list->fetch_array()) {?>
<tr>
<td><input type="checkbox" name="catids[]" value="<?=$val['catid']?>" /></td>
<td><input type="text" name="category[<?=$val['catid']?>][listorder]" value="<?=$val['listorder']?>" class="txtbox5 width" /></td>
<td><input type="text" name="category[<?=$val['catid']?>][name]" value="<?=$val['name']?>" class="txtbox2" /></td>
<td><?=$val['subjectname']?></td>
</tr>
<?}?>
<?else:?>
<tr>
<td colspan="7">暂无信息</td>
</tr>
<?endif;?>
</table>
</div>
<div><?=$multipage?></div>
<center>
<input type="hidden" name="op" value="update" />
<input type="hidden" name="dosubmit" value="yes" />
<?if($total):?>
<a href="admin.php?module=album&act=category&op=new" class="btn">增加分类</a>
<a href="#" class="btn" onclick="easy_submit('myform','update',null);">更新操作</a>
<a href="#" class="btn" onclick="easy_submit('myform','delete','catids[]');">删除所选</a>
<?endif;?>
</center>
</form>
</div>
<script type="text/javascript">
var url="index.php?m=item&act=ajax&do=subject&op=search1";
$().ready(function() {
$("#sname").autocomplete(url, {
max: 12,
minChars: 1,
width: 400,
scrollHeight: 300,
matchContains: true,
autoFill: false,
formatItem: function(row, i, max, value) {
return value.split('-')[1];
},
formatResult: function(row, value) {
return value.split('-')[1];
}
});
$("#sname").result(function(event, data, formatted) {
$("#hsid").val(data[0].split('-')[0] );
});
});
</script><file_sep>/core/modules/about/helper/query.php
<?php
/**
* @author 轩<<EMAIL>>
* @copyright (c)2009-2011 风格店铺
* @copyright 风格店铺(www.cmsky.org)
*/
!defined('IN_MUDDER') && exit('Access Denied');
class query_about {
function getlist($params) {
extract($params);
$loader =& _G('loader');
$db=&_G('db');
if(!$orderby) $orderby = 'listorder';
$db->from('dbpre_about_page');
if($city_id) $db->where('city_id', explode(',',trim($city_id)));
$db->where('enabled', 'Y');
$orderby && $db->order_by($orderby);
$db->limit($start, $rows);
if(!$r=$db->get()) { return null; }
$result = array();
while($v = $r->fetch_array()) {
$result[] = $v;
}
$r->free_result();
return $result;
}
}
?><file_sep>/core/modules/mobile/category.php
<?php
$page = _get('p');
switch ($page) {
case 'top':
$nextpag = 'mobile/top';
break;
default:
$nextpag = 'mobile/list';
break;
}
include mobile_template('category');
?><file_sep>/core/modules/tuan/admin/templates/undertake_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="post" action="<?=cpurl($module,$act)?>" name="myform">
<div class="space">
<div class="subtitle">承接团购申请管理(<?=$wish['title']?>)</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y">
<tr class="altbg1">
<td width="25">选</td>
<td width="100">申请会员</td>
<td width="90">联系人</td>
<td width="100">联系方式</td>
<td width="100">意向价格/数量</td>
<td width="100">提交时间</td>
<td width="*">内容</td>
<td width="100">操作</td>
</tr>
<?if($total && $list):?>
<?while($val=$list->fetch_array()):?>
<tr>
<td><input type="checkbox" name="ids[]" value="<?=$val['id']?>"></td>
<td><a href="<?=url("space/index/uid/$val[uid]")?>" target="_blank"><?=$val['username']?></a></td>
<td><?=$val['linkman']?></td>
<td><?=$val['contact']?></td>
<td><?=$val['price']?>/<?=$val['goods_num']?></td>
<td><?=date('Y-m-d H:i',$val['dateline'])?></td>
<td><?=$val['content']?></td>
<td>
<a href="<?=cpurl($module,$act,'set_undertaker',array('twid'=>$twid,'id'=>$val['id']))?>">设置为承接用户</a>
</td>
</tr>
<?endwhile;?>
<?else:?>
<tr><td colspan="10">暂无信息!</td></tr>
<?endif;?>
</table>
</div>
<div><?=$multipage?></div>
<center>
<input type="hidden" name="op" value="update" />
<input type="hidden" name="dosubmit" value="yes" />
<input type="hidden" name="forward" value="<?=get_forward()?>" />
<?if($total):?>
<button type="button" class="btn" onclick="easy_submit('myform','delete','ids[]')">删除所选</button>
<?endif;?>
<button type="button" class="btn" onclick="document.location='<?=cpurl($module,'wish')?>';">返回</button>
</center>
</form>
</div><file_sep>/core/modules/fenlei/assistant/owner.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
$F =& $_G['loader']->model(':fenlei');
$S =& $_G['loader']->model('item:subject');
$subtitle = lang('fenlei_title_owner');
$role = $_G['role'] = 'owner';
$mysubjects = $S->mysubject($user->uid);
$status_name = array();
for($i=0;$i<=1;$i++) {
$status_name[$i] = strip_tags(lang('global_status_'.$i));
}
$status = _get('status',0,'intval');
$where = array();
$where['sid'] = $mysubjects;
$where['status'] = $status;
$offset = 20;
$start = get_start($_GET['page'], $offset);
list($total,$list) = $F->find('fid,subject,city_id,catid,aid,linkman,status,dateline',$where,array('dateline'=>'DESC'),$start,$offset);
if($total) {
$multipage = multi($total, $offset, $_GET['page'], url("fenlei/member/ac/$ac/status/$status/page/_PAGE_"));
}
//$status_group = $A->status_total($user->uid);
$access_add = count($mysubjects)>0;
$access_del = $access_add;
$tplname = 'fenlei_list';
?><file_sep>/core/modules/tuan/model/sms/sms_chanyoo_config.php
<?php !defined('IN_MUDDER') && exit('Access Denied');?>
<tr>
<td class="altbg2" colspan="2">开源软件增值服务平台整合移动、联通、电信和网通四网于一体,四大运营商短信全部覆盖,全国各地短信通行无阻;全面支持中国移动、中国联通和中国电信天翼用户。访问和注册开源软件增值服务平台:<a href="http://s1.chanyoo.cn/" target="_blank">s1.chanyoo.cn</a></td>
</tr>
<tr>
<td class="altbg1"><strong>开源软件增值服务平台帐号:</strong></td>
<td><input type="text" name="modcfg[sms_chanyoo_username]" id="sms_chanyoo_username" value="<?=$modcfg['sms_chanyoo_username']?>" class="txtbox3" /></td>
</tr>
<tr>
<td class="altbg1"><strong>开源软件增值服务平台密码:</strong></td>
<td><input type="text" name="modcfg[sms_chanyoo_password]" id="sms_chanyoo_password" value="<?=$modcfg['sms_chanyoo_password']?'******':''?>" class="txtbox3" /></td>
</tr><file_sep>/core/modules/modoer/item/admin/menus.inc.php
<?php
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$modmenus = array(
array(
'title' => '功能设置',
'item|模块设置|config',
'item|分类管理|category_list',
'item|模型管理|model_list',
'item|属性组管理|att_cat',
'item|标签组管理|taggroup',
'item|风格管理|template',
),
array(
'title' => '内容管理',
'item|商户管理|subject_list',
'item|审核商户|subject_check',
'item|审核图片|picture_check',
'item|添加商户|subject_add',
'item|商户补充|subject_log',
'item|商户认领|subject_apply',
'item|相册管理|album',
'item|印象管理|impress',
'item|标签管理|tag_list',
),
);
?><file_sep>/core/modules/fenlei/install/module_install.sql
DROP TABLE IF EXISTS modoer_fenlei_category;
CREATE TABLE modoer_fenlei_category (
catid smallint(5) NOT NULL AUTO_INCREMENT,
pid smallint(5) NOT NULL DEFAULT '0',
name varchar(60) NOT NULL DEFAULT '',
post_tpl varchar(60) NOT NULL DEFAULT '',
list_tpl varchar(60) NOT NULL DEFAULT '',
detail_tpl varchar(60) NOT NULL DEFAULT '',
listorder smallint(5) NOT NULL DEFAULT '0',
num int(10) NOT NULL DEFAULT '0',
fieldids varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (catid)
) TYPE=MyISAM;
DROP TABLE IF EXISTS modoer_fenlei;
CREATE TABLE modoer_fenlei (
fid mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
catid smallint(5) NOT NULL DEFAULT '0',
finer tinyint(3) unsigned NOT NULL DEFAULT '0',
city_id smallint(5) unsigned NOT NULL DEFAULT '0',
aid smallint(5) NOT NULL DEFAULT '0',
sid mediumint(8) NOT NULL DEFAULT '0',
subject varchar(60) NOT NULL DEFAULT '',
thumb varchar(255) NOT NULL DEFAULT '',
uid mediumint(8) unsigned NOT NULL DEFAULT '0',
username varchar(20) NOT NULL DEFAULT '',
status tinyint(1) unsigned NOT NULL DEFAULT '1',
linkman varchar(20) NOT NULL DEFAULT '',
contact varchar(100) NOT NULL DEFAULT '',
email varchar(100) NOT NULL DEFAULT '',
im varchar(60) NOT NULL DEFAULT '',
address varchar(255) NOT NULL DEFAULT '',
content text NOT NULL,
dateline int(10) unsigned NOT NULL DEFAULT '0',
endtime int(10) unsigned NOT NULL DEFAULT '0',
pageview int(10) NOT NULL DEFAULT '0',
comments mediumint(8) unsigned NOT NULL DEFAULT '0',
map_lng decimal(8,5) NOT NULL DEFAULT '0.00000',
map_lat decimal(8,5) NOT NULL DEFAULT '0.00000',
color VARCHAR( 30 ) NOT NULL DEFAULT '',
color_endtime INT( 10 ) UNSIGNED NOT NULL DEFAULT '0',
top TINYINT( 1 ) NOT NULL DEFAULT '0',
top_endtime INT( 10 ) UNSIGNED DEFAULT '0',
PRIMARY KEY (fid),
KEY catid (aid,catid),
KEY uid (uid,username),
KEY subject (subject)
) TYPE=MyISAM;<file_sep>/core/modules/party/admin/templates/hook_usergroup_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<tr>
<td class="altbg1"><strong>允许本组会员发起活动:</strong>开启本功能后,本组会员便可以在前台发布的发起活动</td>
<td><?=form_bool('access[party_post]', $access['party_post'])?></td>
</tr><file_sep>/core/modules/tuan/admin/discuss.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$TD =& $_G['loader']->model('tuan:discuss');
$op = _input('op');
switch($op) {
case 'delete':
$TD->delete(_post('ids'));
redirect('global_op_succeed_delete', get_forward(cpurl($module,$act)));
break;
case 'edit':
$id = (int)_get('id');
if(!$detail = $TD->read($id)) redirect('tuan_discuss_empty');
$admin->tplname = cptpl('discuss_save', MOD_FLAG);
break;
case 'save':
if(!$id = (int)_post('id')) redirect(lang('global_sql_keyid_invalid','id'));
$TD->save($TD->get_post($_POST), $id);
redirect('global_op_succeed', get_forward(cpurl($module,$act),1));
break;
default:
$op = 'list';
$where = array();
if(!$admin->is_founder) $where['city_id'] = $_CITY['aid'];
list($total,$list,$multipage) = $TD->cplist($where);
$admin->tplname = cptpl('discuss_list', MOD_FLAG);
}
?><file_sep>/core/modules/tuan/discuss.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'tuan');
$tid = (int)_input('id');
$T =& $_G['loader']->model(':tuan');
if(!$detail = $T->read($tid)) redirect('tuan_empty');
$DIS = $_G['loader']->model('tuan:discuss');
if(check_submit('dosubmit')) {
$_POST['tid'] = $tid;
$post = $DIS->get_post($_POST);
$DIS->save($post);
redirect('tuan_discuss_discuss', url("tuan/discuss/id/$tid"));
}
list($total, $list, $multipage) = $DIS->getlist($MOD['discuss_all'] ? 0 : $tid);
$_HEAD['keywords'] = $MOD['meta_keywords'];
$_HEAD['description'] = $MOD['meta_description'];
include template('tuan_discuss');
?><file_sep>/core/modules/about/install/module_uninstall.sql
DROP TABLE IF EXISTS modoer_about_page;<file_sep>/core/modules/party/admin/templates/party_content.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="post" action="<?=cpurl($module,$act,'content')?>">
<div class="space">
<div class="subtitle">活动精彩回顾</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1" width="100"><span class="font_1">*</span>活动主题:</td>
<td width="*"><a href="<?=url("party/detail/partyid/$party[partyid]")?>" target="_blank"><?=$party['subject']?></a></td>
</tr>
<tr>
<td class="altbg1" valign="top">详细内容:</td>
<td><?=$edit_html?></td>
</tr>
</table>
</table>
<center>
<input type="hidden" name="forward" value="<?=get_forward()?>" />
<input type="hidden" name="partyid" value="<?=$partyid?>" />
<button type="submit" class="btn" name="dosubmit" value="yes">提交</button>
<button type="button" class="btn" onclick="history.go(-1);">返回</button>
</center>
</div>
</form>
</div><file_sep>/core/modules/tuan/install/module_uninstall.sql
DROP TABLE IF EXISTS modoer_tuan;
DROP TABLE IF EXISTS modoer_tuan_category;
DROP TABLE IF EXISTS modoer_tuan_coupon;
DROP TABLE IF EXISTS modoer_tuan_discuss;
DROP TABLE IF EXISTS modoer_tuan_order;
DROP TABLE IF EXISTS modoer_tuan_undertake;
DROP TABLE IF EXISTS modoer_tuan_wish;<file_sep>/core/modules/mobile/search.php
<?php
$urlpath[] = '搜索';
$q = _input('keyword', '', MF_TEXT);
if(($_GET['Pathinfo'] || $_GET['Rewrite']) && $q && $_G['charset'] != 'utf-8' && $_G['cfg']['utf8url']) {
$q = charset_convert($q,'utf-8',$_G['charset']);
} elseif(!$_GET['Pathinfo'] && !$_GET['Rewrite'] && $_G['charset'] != 'utf-8') {
$q = charset_convert($q,'utf-8',$_G['charset']);
}
$q = str_replace(array("\r\n","\r","\n") ,'', _T($q));
//if(!$q) location('mobile/index');
$urlpath[] = "关键字:$q";
$_G['db']->from('dbpre_subject');
$_G['db']->select('*');
$_G['db']->where('city_id', array(0,$_CITY['aid']));
$_G['db']->where_concat_like('name,subname', "%{$q}%");
$_G['db']->where('status', 1);
$multipage = '';
if($total = $_G['db']->count()) {
$_G['db']->sql_roll_back('from,select,where');
$orderby = array($post['ordersort']=>$post['ordertype']);
$offset = 1;
$start = get_start($_GET['page'], $offset);
$_G['db']->order_by($orderby);
$_G['db']->limit($start, $offset);
$list = $_G['db']->get();
if($total) {
$multipage = mobile_page($total, $offset, $_GET['page'], url("mobile/search/keyword/$q/page/_PAGE_"));
}
}
//显示模版
if($_G['in_ajax']) {
$tplname = 'list_li';
} else {
$tplname = 'list';
}
include mobile_template($tplname);
?><file_sep>/core/modules/tuan/assistant/pay.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
$O =& $_G['loader']->model('tuan:order');
if(check_submit('dosubmit')) {
$oid = _post('oid', null, 'intval');
if($_POST['payment'] == 'online') {
$O->pay_online($oid, _post('payment_name',null,MF_TEXT));
} elseif($_POST['payment'] == 'offline') {
redirect("订单已保存,请您在汇款完成后,及时联系本站客服完成订单付款。", url('tuan/member/ac/order'));
} else {
$O->pay($oid);
redirect('tuan_pay_succeed', url('tuan/member/ac/order'));
}
} else {
if(!$oid = (int)_get('id')) redirect(lang('global_sql_keyid_invalid','id'));
if(!$order = $O->read($oid)) redirect('tuan_order_empty');
if($order['status']!='new') location(url('tuan/member/ac/order/op/detail/oid/'.$oid));
if(!$detail = $O->check_buy($order['tid'])) redirect('tuan_empty');
$PAY =& $_G['loader']->model(':pay');
$tplname = 'pay';
}
?><file_sep>/core/modules/item/detail.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
$I = & $_G ['loader']->model ( MOD_FLAG . ':subject' );
// 随便看看
$random = _get ( 'random', null, MF_INT );
if ($random) {
$where = array ();
$where ['city_id'] = array (
0,
$_CITY ['aid']
);
if (! $detail = $I->read_random ( $where ))
redirect ( 'item_random_empty' );
location ( url ( "city:$detail[city_id]/item/detail/id/$detail[sid]" ) );
}
if ($sid = ( int ) $_GET ['sid']) {
unset ( $_GET ['id'], $_GET ['name'] );
} elseif ($sid = ( int ) $_GET ['id']) {
unset ( $_GET ['id'], $_GET ['name'] );
$_GET ['sid'] = $sid;
} elseif ($domain = _T ( $_GET ['name'] )) {
// 如果来路domain是act行为列表里的,则跳转到对应act页面
if (in_array ( $domain, $acts ))
location ( url ( "item/$domain", '', 1, 1 ) );
unset ( $_GET ['id'], $_GET ['name'] );
}
if (! $sid && ! $domain)
redirect ( lang ( 'global_sql_keyid_invalid', 'id' ) );
$id = $sid;
// 取得主题信息
if ($sid) {
$detail = $I->read ( $sid );
} else {
$_G ['fullalways'] = TRUE;
// 域名合法性检测
if (! $I->domain_check ( $domain ))
redirect ( lang ( 'global_sql_keyid_invalid', 'id' ) );
if ($detail = $I->read ( $domain, '*', TRUE, TRUE )) {
$_GET ['sid'] = $id = $sid = ( int ) $detail ['sid'];
} else {
http_404 ();
// location($_G['cfg']['siteurl']);
}
}
if (! $detail || ! $detail ['status'])
redirect ( 'item_empty' );
// 判断是否当前内容所属当前城市,不是则跳转
if (check_jump_city ( $detail ['city_id'] ))
location ( url ( "city:$detail[city_id]/item/detail/id/$id" ) );
define ( 'SCRIPTNAV', 'item_' . $detail ['pid'] );
// 主题管理员标记
$is_owner = $detail ['owner'] == $user->username;
$category = $I->get_category ( $detail ['catid'] );
if (! $pid = $category ['catid']) {
redirect ( 'item_cat_empty' );
}
$modelid = $I->category ['modelid'];
$rogid = $I->category ['review_opt_gid'];
// 取得分类、模型、点评项以及地区信息
$catcfg = & $category ['config'];
if (! $model = $I->get_model ( $modelid ))
redirect ( 'item_model_empty' );
if ($model ['usearea'])
$area = $I->loader->variable ( 'area' );
$R = & $_G ['loader']->model ( ':review' );
$reviewpot = $R->variable ( 'opt_' . $rogid );
$urlpath = array ();
$pcat = $I->variable ( 'category' );
$urlpath [] = url_path ( $I->category ['name'], url ( "item/list/catid/$pid" ) );
$category = $_G ['loader']->variable ( 'category_' . $I->category ['catid'], 'item' );
if ($category [$detail ['catid']] ['level'] > 2) {
$urlpath [] = url_path ( $category [$category [$detail ['catid']] ['pid']] ['name'], url ( "item/list/catid/{$detail['pid']}" ) );
}
if ($detail ['catid'] != $detail ['pid'])
$urlpath [] = url_path ( $category [$detail [catid]] ['name'], url ( "item/list/catid/$detail[catid]" ) );
define ( 'SUBJECT_CATID', $detail ['pid'] );
// 生成表格内容
$detail_custom_field = $I->display_detailfield ( $detail );
// 获取关联主题字段
$relate_subject_field = $I->get_relate_subject_field ( $modelid );
// 获取淘宝客字段
$taoke_product_field = $I->get_taoke_product_field ( $modelid );
// 获取多行文本字段
$textarea_field = $I->get_textarea_field ( $modelid );
// 前台不显示字段去除
$fields = $I->variable ( 'field_' . $modelid );
foreach ( $fields as $fd ) {
if (! $fd ['show_detail'] && $fd ['fieldname'] == 'content')
unset ( $detail [$fd ['fieldname']] );
}
// 餐厅氛围
$detail ['c_fenwei'] = $I->get_myatt ( $detail ['c_fenwei'] );
// 餐厅特色
$detail ['c_tese'] = $I->get_myatt ( $detail ['c_tese'] );
// 商家标签
$detail ['c_tags'] = $I->get_mytag ( $detail ['c_tags'] );
// 载入标签
$taggroups = $_G ['loader']->variable ( 'taggroup', 'item' );
// 增加浏览量
if (! $detail ['owner'] || $detail ['owner'] && $detail ['owner'] != $user->username)
$I->pageview ( $sid );
// 加入COOKIE
$I->write_cookie ( $detail );
// 显示点评或留言
$views = array (
'review',
'guestbook',
'forum'
);
$view = $_GET ['view'] = in_array ( $_GET ['view'], $views ) ? $_GET ['view'] : 'review';
if ($view == 'forum' && $detail ['forumid'] > 0) {
$_G ['loader']->helper ( 'modcenter' );
$forums = modcenter::get_threads ( $detail ['forumid'] );
} elseif ($view == 'guestbook' && $detail ['guestbooks'] > 0) {
// 取得留言数据
$GB = & $_G ['loader']->model ( MOD_FLAG . ':guestbook' );
$where = array ();
$where ['sid'] = $sid;
$where ['status'] = 1;
$orderby = array (
'dateline' => 'DESC'
);
$offset = $MOD ['guestbook_num'] > 0 ? $MOD ['guestbook_num'] : 10;
$start = get_start ( $_GET ['page'], $offset );
list ( , $guestbooks ) = $GB->find ( $select, $where, $orderby, $start, $offset, FALSE );
$onclick = "get_guestbook($sid,{PAGE})";
$multipage = multi ( $detail ['guestbooks'], $offset, $_GET ['page'], SELF . '?sid=' . $sid . '&view=guestbook', '#guestbook', $onclick );
} else {
if ($detail ['reviews'] > 0) {
$review_filter = 'all';
$review_orderby = 'posttime';
// 取得点评数据
$where = array ();
$where ['idtype'] = 'item_subject';
$where ['id'] = $sid;
$where ['status'] = 1;
$orderby = array (
'posttime' => 'DESC'
);
$offset = $MOD ['review_num'] > 0 ? $MOD ['review_num'] : 10;
$start = get_start ( $_GET ['page'], $offset );
$select = 'r.*,m.point,m.point1,m.groupid';
list ( , $reviews ) = $R->find ( $select, $where, $orderby, $start, $offset, FALSE, FALSE, TRUE );
$onclick = "get_review('item_subject',$sid,'all','$review_orderby',{PAGE})";
$multipage = multi ( $detail ['reviews'], $offset, $_GET ['page'], url ( "item/detail/id/$sid/view/review/page/_PAGE_" ), '#review', $onclick );
}
// 点评行为检测
$review_access = $I->review_access ( $detail );
$review_enable = $review_access ['code'] == 1;
}
// 其他模块和功能的链接
$links = $_G ['hook']->hook ( 'subject_detail_link', $detail, TRUE );
// 分类设置默认风格
if ($catcfg ['templateid'] && ! $detail ['templateid']) {
$detail ['templateid'] = $catcfg ['templateid'];
}
$seo_tags = get_seo_tags ();
$seo_tags ['root_category_name'] = display ( 'item:category', "catid/$detail[pid]" );
$seo_tags ['current_category_name'] = display ( 'item:category', "catid/$detail[catid]" );
$seo_tags ['name'] = $detail ['name'] . ($detail ['subname'] ? "($detail[subname])" : '');
$seo_tags ['description'] = $detail ['description'];
$seo_tags ['content'] = trimmed_title ( strip_tags ( str_replace ( "\r\n", '', $detail ['content'] ) ), 100 );
! $MOD ['seo_detail_title'] && $MOD ['seo_detail_title'] = '{name}' . $_G ['cfg'] ['titlesplit'] . '{site_name}';
! $MOD ['seo_detail_keywords'] && $MOD ['seo_detail_keywords'] = '{root_category_name},{current_category_name},' . $catcfg ['meta_keywords'];
! $MOD ['seo_detail_description'] && $MOD ['seo_detail_description'] = '{content},' . $catcfg ['meta_description'];
$_HEAD ['title'] = parse_seo_tags ( $MOD ['seo_detail_title'], $seo_tags );
$_HEAD ['keywords'] = parse_seo_tags ( $MOD ['seo_detail_keywords'], $seo_tags );
$_HEAD ['description'] = parse_seo_tags ( $MOD ['seo_detail_description'], $seo_tags );
$_G ['show_sitename'] = FALSE;
$subject = & $detail; // 用于主题风格
define ( 'SUB_NAVSCRIPT', 'item/detail' );
// 预览模式
if (! $vtid = _get ( 'preview', null, MF_INT_KEY )) {
$vtid = _cookie ( 'item_style_preview_' . $sid, null, MF_INT_KEY );
}
if ($vtid > 0 && is_template ( $vtid, 'item' )) {
$subject ['templateid'] = $vtid;
$is_preview = true;
set_cookie ( 'item_style_preview_' . $sid, $vtid );
} else {
// 检测模板过期
if (! $I->get_style ()->check_style_endtime ( $sid, $detail ['templateid'], $detail ['catid'] )) {
$detail ['templateid'] = 0;
}
}
if (! $detail ['templateid'] && $catcfg ['templateid'] > 0)
$detail ['templateid'] = $catcfg ['templateid'];
if ($detail ['templateid']) {
include template ( 'index', 'item', $detail ['templateid'] );
} else {
// 载入模型的内容页模板
include template ( $I->model ['tplname_detail'] );
}<file_sep>/core/modules/modoer/item/inc/hook.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
class hook_item extends ms_base {
function __construct() {
parent::__construct ();
}
function admincp_subject_edit_link($sid) {
$result = array ();
$result [] = array (
'flag' => 'item:picture_list',
'url' => cpurl ( 'item', 'picture_list', '', array (
'sid' => $sid
) ),
'title' => '图片管理'
);
/*
* $result [] = array ( 'flag' => 'item:subject_guestbook', 'url' =>
* cpurl ( 'item', 'guestbook_list', '', array ( 'sid' => $sid ) ),
* 'title' => '留言管理' ); $setting =
* $this->loader->model('item:subjectsetting')->read($sid);
* if($setting['banner']) { $result[] = array ( 'flag' =>
* 'item:subject_setting_banner', 'url' =>
* cpurl('item','setting','banner',array('sid'=>$sid)), 'title'=>
* '横幅管理', ); } if($setting['bcastr']) { $result[] = array ( 'flag' =>
* 'item:subject_setting_bcastr', 'url' =>
* cpurl('item','setting','bcastr',array('sid'=>$sid)), 'title'=>
* '橱窗管理', ); }
*/
return $result;
}
function subject_detail_link(&$params) {
extract ( $params );
$result = array ();
$IB = & $this->loader->model ( 'item:itembase' );
$model = $IB->get_model ( $pid, true );
$result [0] = array (
'flag' => 'item/detail',
'url' => url ( 'item/detail/id/' . $sid ),
'title' => '首页'
);
$result [1] = array (
'flag' => 'item/album',
'url' => url ( 'item/album/sid/' . $sid ),
'title' => '相册'
);
return $result;
}
function mobile_index_link() {
$result [] = array (
'flag' => 'item/category',
'url' => url ( 'item/mobile/do/category' ),
'title' => '商家',
'icon' => 'categorys'
);
$result [] = array (
'flag' => 'item/top',
'url' => url ( 'item/mobile/do/top' ),
'title' => '排行',
'icon' => 'tops'
);
$result [] = array (
'flag' => 'item/album',
'url' => url ( 'item/mobile/do/album' ),
'title' => '图库',
'icon' => 'album'
);
$result [] = array (
'flag' => 'item/album',
'url' => url ( 'item/mobile/do/album' ),
'title' => '团购 ',
'icon' => 'album'
);
$result [] = array (
'flag' => 'item/rand',
'url' => url ( 'item/mobile/do/rand' ),
'title' => '排队',
'icon' => 'rand'
);
$result [] = array (
'flag' => 'item/rand',
'url' => url ( 'item/mobile/do/rand' ),
'title' => '闲逛',
'icon' => 'rand'
);
$result [] = array (
'flag' => 'item/rand',
'url' => url ( 'item/mobile/do/rand' ),
'title' => '美食APP',
'icon' => 'rand'
);
return $result;
}
function mobile_member_link() {
$result [] = array (
'flag' => 'item/member/follow',
'url' => url ( 'item/mobile/do/follow' ),
'title' => '我的关注'
);
return $result;
}
function subject_manage_link($sid, $catid) {
}
function footer() {
}
}
?><file_sep>/core/modules/party/admin/templates/apply_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="get" action="<?=SELF?>">
<input type="hidden" name="module" value="<?=$module?>" />
<input type="hidden" name="act" value="<?=$act?>" />
<input type="hidden" name="op" value="<?=$op?>" />
<div class="space">
<div class="subtitle">活动筛选</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100" class="altbg1">会员</td>
<td width="350"><input type="text" name="username" class="txtbox3" value="<?=$_GET['username']?>" /></td>
<td width="100" class="altbg1">活动ID(partyid)</td>
<td width="*"><input type="text" name="partyid" class="txtbox3" value="<?=$_GET['partyid']?>" /></td>
</tr>
<tr>
<td class="altbg1">报名时间</td>
<td colspan="3"><input type="text" name="starttime" class="txtbox3" value="<?=$_GET['starttime']?>" /> ~ <input type="text" name="endtime" class="txtbox3" value="<?=$_GET['endtime']?>" /> (YYYY-MM-DD)</td>
</tr>
<tr>
<td class="altbg1">结果排序</td>
<td colspan="3">
<select name="orderby">
<option value="applyid"<?=$_GET['orderby']=='applyid'?' selected="selected"':''?>>ID排序</option>
<option value="dateline"<?=$_GET['orderby']=='dateline'?' selected="selected"':''?>>报名时间</option>
</select>
<select name="ordersc">
<option value="DESC"<?=$_GET['ordersc']=='DESC'?' selected="selected"':''?>>递减</option>
<option value="ASC"<?=$_GET['ordersc']=='ASC'?' selected="selected"':''?>>递增</option>
</select>
<select name="offset">
<option value="20"<?=$_GET['offset']=='20'?' selected="selected"':''?>>每页显示20个</option>
<option value="50"<?=$_GET['offset']=='50'?' selected="selected"':''?>>每页显示50个</option>
<option value="100"<?=$_GET['offset']=='100'?' selected="selected"':''?>>每页显示100个</option>
</select>
<button type="submit" value="yes" name="dosubmit" class="btn2">筛选</button>
</td>
</tr>
</table>
</div>
</form>
<form method="post" name="myform" action="<?=cpurl($module,$act)?>&">
<div class="space">
<div class="subtitle">报名会员管理</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" id="config1" trmouse="Y">
<tr class="altbg1">
<td width="25">选</td>
<td width="250">活动名称</td>
<td width="120">报名会员</td>
<td width="120">报名时间</td>
<td width="110">联系人</td>
<td width="60">性别</td>
<td width="120">联系方式</td>
<td width="*">备注</td>
</tr>
<?if($total):?>
<?while($val = $list->fetch_array()):?>
<tr>
<td><input type="checkbox" name="applyids[]" value="<?=$val['applyid']?>" /></td>
<td><a href="<?=url("party/detail/id/$val[partyid]")?>" target="_blank"><?=$val['subject']?></a></td>
<td><a href="<?=url("space/index/uid/$val[uid]")?>" target="_blank"><?=$val['username']?></a></td>
<td><?=date('Y-m-d H:i', $val['dateline'])?></td>
<td><?=$val['linkman']?></td>
<td><?=lang('party_sex_'.$val['sex'])?></td>
<td><?=$val['contact']?></td>
<td><?=$val['content']?></td>
</tr>
<?endwhile;?>
<tr class="altbg1">
<td colspan="2" class="altbg1">
<button type="button" onclick="checkbox_checked('applyids[]');" class="btn2">全选</button>
<td colspan="6" style="text-align:right;"><?=$multipage?></td>
</tr>
<?else:?>
<td colspan="8">暂无信息。</td>
<?endif;?>
</table>
</div>
<center>
<?if($total):?>
<input type="hidden" name="dosubmit" value="yes" />
<input type="hidden" name="op" value="listorder" />
<button type="button" class="btn" onclick="easy_submit('myform','delete','applyids[]')">删除所选</button>
<?endif;?>
</center>
</form>
</div><file_sep>/core/modules/tuan/detail.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'tuan');
$tid = (int)_get('id');
$T =& $_G['loader']->model(':tuan');
$T->plan_status($tid);
if(!$detail = $T->read($tid)) redirect('tuan_empty');
if(!$detail['checked']) redirect('tuan_check');
//判断是否当前内容所属当前城市,不是则跳转
if(check_jump_city($detail['city_id'])) location(url("city:$detail[city_id]/tuan/detail/id/$tid"));
$S =& $_G['loader']->model('item:subject');
$subject = $S->read($detail['sid']);
$subject_field_table_tr = $S->display_listfield($subject);
$TD =& $_G['loader']->model('tuan:discuss');
$total = $TD->count($MOD['discuss_all'] ? 0 : $detail['tid']);
$_HEAD['keywords'] = $MOD['meta_keywords'];
$_HEAD['description'] = $MOD['meta_description'];
include template('tuan_detail');
?><file_sep>/core/modules/tuan/admin/templates/tgsite_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/jquery.js"></script>
<script type="text/javascript" src="./static/javascript/autocomplete/jquery.autocomplete.min.js"></script>
<link rel="Stylesheet" href="./static/javascript/autocomplete/jquery.autocomplete.css" />
<script type="text/javascript">
var g;
function reload() {
var obj = document.getElementById('reload');
var btn = document.getElementById('switch');
if(obj.innerHTML.match(/^<.+href=.+>/)) {
g = obj.innerHTML;
obj.innerHTML = '<input type="file" name="picture" size="20">';
btn.innerHTML = '取消上传';
} else {
obj.innerHTML = g;
btn.innerHTML = '重新上传';
}
}
function check_submit() {
//if($('[name=sid]').val()=="") {
//alert('选择优惠券所属商铺。');
//return false;
//}
return true;
}
</script>
<div id="body">
<form method="post" action="<?=cpurl($module,$act,'save')?>" name="myform" enctype="multipart/form-data" onsubmit="return check_submit();">
<input id="sid" type="hidden" name="sid" value="" />
<div class="space">
<div class="subtitle">添加/编辑团购网站</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1" width="15%" align="right">网站名称:</td>
<td width="75%" class="altbg1">
<input type="text" name="sitename" value="<?=$detail['sitename']?>" class="txtbox" />
</td>
</tr>
<tr>
<td class="altbg1" align="right">开头字母:</td>
<td>
<input type="text" name="pinyin" value="<?=$detail['pinyin']?>" class="txtbox" />
</td>
</tr>
<tr>
<td class="altbg1 "align="right">网站URL:</td>
<td>
<input type="text" name="siteurl" value="<?=$detail['siteurl']?>" class="txtbox" />
</td>
</tr>
<tr>
<td class="altbg1" align="right">API类型:</td>
<td>
<SELECT name="apikey">
<?=form_tuan_crule_api($detail['apikey'])?>
</SELECT>
</td>
</tr>
<tr>
<td class="altbg1" align="right">采集API地址:</td>
<td>
<input type="text" name="siteapi" value="<?=$detail['siteapi']?>" class="txtbox" />
</td>
</tr>
<tr>
<td class="altbg1" align="right">网站权重:</td>
<td>
<input type="text" name="level" value="<?=$detail['level']?>" class="txtbox" />(A-Z)
</td>
</tr>
</table>
<center>
<?if($op=='edit'):?>
<input type="hidden" name="id" value="<?=$id?>" />
<?endif;?>
<input type="hidden" name="do" value="<?=$op?>" />
<button type="submit" name="dosubmit" value="yes" class="btn" /> 提交 </button>
<button type="button" class="btn" value="yes" onclick="history.go(-1);"> 返回 </button>
</center>
</div>
</form>
</div><file_sep>/core/modules/product/admin/menus.inc.php
<?php
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$modmenus = array(
array(
'title' => '功能设置',
'product|模块设置|config',
'product|商品模型|model_list',
),
array(
'title' => '商品管理',
'product|商品审核|product_list|checklist',
'product|商品列表|product_list',
),
);
?><file_sep>/templates/item/vip/article_list.php
<?exit?>
<!--{eval
$_HEAD['title'] = $MOD[name] . $_CFG['titlesplit'] . str_replace(' » ',$_CFG['titlesplit'],strip_tags($subtitle));
}-->
<!--{template 'header', 'item', $subject[templateid]}-->
<link href="{URLROOT}/img/vipfiles/css/shopEx_$subject[c_vipstyle].css" rel="stylesheet" type="text/css" />
<body>
<div class="wrap">
<div id="header">
<div id="crumb">
<p id="crumbL"><a href="{url modoer/index}">首页</a> » <a href="{url article/index}">$MOD[name]</a> » $subtitle
<p id="crumbR"><a href="javascript:post_log($subject[sid]);">补充信息</a> | <a href="{url item/member/ac/subject_add/subbranch_sid/$subject[sid]}">增加分店</a> | <a href="{url member/index}">管理本店</a></p>
</div>
<div id="shopBanner">
<h1>$subject[name] $subject[subname]</h1>
<p>
<!--{if $subject[c_add]}-->
<B>地址:</B></LABEL>$subject[c_add]
<!--{/if}-->
<!--{if $subject[c_tel]}-->
<B>电话:</B></LABEL>$subject[c_tel]</p>
<!--{/if}-->
<div class="headerPic">
<img src="{if $subject[c_vipbanner]}$subject[c_vipbanner]{else}{URLROOT}img/haibao/nonbanner.png{/if}" alt="$subject[name] $subject[subname]店铺海报" width="950" height="150"/>
</div>
</div>
<div id="nav">
<ul>
<!--
<li><a href="#"><span>Array</span></a></li>
<li><a href="#"><span></span></a></li>
<li class="special"><a href="#"><span>导航栏介绍</span></a></li>
-->
<li><a href="{url item/detail/id/$subject[sid]}"><span>首页</span></a></li>
<li class="current" ><a href="{url article/list/sid/$sid}"><span>店铺资讯</span></a></li>
<li><a href="{url fenlei/list/sid/$sid}"><span>诚聘英才</span></a> </li>
<li><a href="{url product/list/sid/$sid}"><span>产品展厅</span></a></li>
<li><a href="{url coupon/list/sid/$sid}"><span>优惠打折</span></a></li>
<li><a href="{url item/pic/sid/$subject[sid]}"><span>商家相册</span></a></li>
<li><a href="{url item/vipabout/id/$subject[sid]}"><span>关于我们</span></a></li>
<li><a href="{url item/vipreview/id/$subject[sid]}"><span>会员点评</span></a></li>
<li><a href="{url item/vipguestbook/id/$subject[sid]}"><span>留言板</span></a></li>
</ul>
</div>
</div>
<div id="smartAd"><img src="{if $subject[c_vipbanner2]}$subject[c_vipbanner2]{else}{URLROOT}img/haibao/non.png{/if}" alt="$subject[name] $subject[subname]店铺海报"/></a><br />
</div>
<div id="mainBody">
<div id="mainBodyL">
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>【$subject[name] $subject[subname]】</h2>
<p class="deafBoxTitMore"><a href="{url item/vipabout/id/$subject[sid]}">更多</a></p>
</div>
<div class="deafBoxCon">
<dl>
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td align="center" valign="middle">
<a href="{url item/pic/sid/$subject[sid]}"><img src="{URLROOT}/{if $subject[thumb]}$subject[thumb]{else}static/images/noimg.gif{/if}" alt="$subject[name]" width="270" height="200" /></a>
</td>
</tr>
</table>
<div class="leftnr">
<!--{if $subject[finer]}-->
店铺级别:<img src="{URLROOT}/img/vipfiles/img/vip$subject[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<div class="subject">
<h2><a href="{url item/detail/id/$sid}" src="$subject[thumb]" onMouseOver="tip_start(this,1);">$subject[name] $subject[subname]</a></h2>
<!--{eval $reviewcfg = $_G['loader']->variable('config','review');}-->
<p class="start start{print get_star($subject[avgsort],$reviewcfg[scoretype])}"></p>
<table class="subject_field_list" border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2"><span class="font_2">$subject[reviews]</span>点评,
<span class="font_2">$subject[guestbooks]</span>留言,
<span class="font_2">$subject[pageviews]</span>浏览</td>
</tr>
$subject_field_table_tr
</table>
<a class="abtn1" href="{url review/member/ac/add/type/item_subject/id/$subject[sid]}"><span>我要点评</span></a>
<a class="abtn2" href="javascript:add_favorite($sid);"><span>收藏</span></a>
<a class="abtn2" href="{url item/detail/id/$sid/view/guestbook}#guestbook"><span>留言</span></a>
<div class="clear"></div>
</dl>
</div>
</div></div>
<div id="chaBodyR">
<div id="chaBodyRTit">
<h2>商家资讯</h2>
</div>
<div class="listCon">
<!--{if $list}-->
{dbres $list $val}
<div class="article_s">
<em>{date $val[dateline]}</em>
<h2><a href="{url article/detail/id/$val[articleid]}">$val[subject]</a></h2>
<p>$val[introduce]...<a href="{url article/detail/id/$val[articleid]}">[阅读全文]</a></p>
<div><span>作者:$val[author]</span> <span>来源:$val[copyfrom]</span> <span>评论:$val[comments]</span></div>
</div>
{/dbres}
<div class="multipage">$multipage</div>
<!--{else}-->
<div class="messageborder">没有找到任何信息。</div>
<!--{/if}-->
</div>
</div>
<div class="clear"></div>
</div>
<!--{template 'footer', 'item', $subject[templateid]}--><file_sep>/core/modules/tuan/install/config.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
// 设置模块的默认配置信息
$moduleconfig = array(
'discuss_all' => '0',
'mail_num' => '10',
'need_mobile' => '0',
'mobile_preg' => '/^[0-9]{11}$/',
'send_sms' => '0',
'sms_interval' => '5',
'express' => '顺丰快递,EMS',
'index_type' => 'list',
'sms_api' => 'powereasy',
);
?><file_sep>/core/modules/party/admin/templates/picture.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<?php if($op=='upload'):?>
<form method="post" action="admincp.php?action=<?=$action?>&file=<?=$file?>&op=<?=$op?>" enctype="multipart/form-data">
<input type="hidden" name="partyid" value="<?=$partyid?>" />
<div class="space">
<div class="subtitle">上传照片:<?=$party['subject']?></div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1" width="100">活动对象:</td>
<td width="*"><a href="<?url("party/detail/partyid/$partyid")?>" target="_blank"><?=$party['subject']?></a></td>
</tr>
<tr>
<td class="altbg1">照片标题:</td>
<td><input type="text" class="txtbox2" size="30" name="title" /></td>
</tr>
<tr>
<td class="altbg1">照片上传:</td>
<td><input type="file" name="pic" /></td>
</tr>
</table>
</div>
<center>
<button type="submit" class="btn" name="dosubmit" value="yes">提交</button>
<button type="button" class="btn" onclick="document.location='admincp.php?action=<?=$action?>&file=<?=$file?>&partyid=<?=$partyid?>';">返回</button>
</center>
</form>
<? else: ?>
<form method="post" action="admincp.php?action=<?=$action?>&file=<?=$file?>" name="myform">
<input type="hidden" name="partyid" value="<?=$partyid?>" />
<div class="space">
<div class="subtitle">活动列表:<?=$party['subject']?></div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr class="altbg1">
<td width="30">删?</td>
<td width="*">照片</td>
<td width="250">名称</td>
<td width="120">上传会员</td>
<td width="100">审核状态</td>
<td width="120">上传时间</td>
</tr>
<?foreach ($list as $val):?>
<tr>
<td><input type="checkbox" name="picids[]" value="<?=$val['picid']?>" /></td>
<td><a href="uploads<?=$val['pic']?>" target="_blank"><img src="uploads<?=$val['thumb']?>" /></a></td>
<td>
<?if($val['subject']):?><a href="<?=url("party/detail/partyid/$val[partyid]")?>" target="_blank"><?=$val['subject']?></a><br /><?endif;?>
<input type="text" class="txtbox2" size="30" name="picture[<?=$val['picid']?>][title]" value="<?=$val['title']?>" />
</td>
<td><?if($val[uid]):?><a href="<?=url("space/index/suid/$val[uid]")?>" target="_blank"><?=$val['username']?></a><?else:?><?=$val['username']?><?endif;?></td>
<td><input type="checkbox" name="picture[<?=$val['picid']?>][status]" value="1"<?if($val[status])echo" checked"?> /></td>
<td><?=date('Y-m-d H:i',$val[dateline])?></td>
</tr>
<?endforeach;?>
<?if($total):?>
<tr class="altbg1">
<td colspan="6"><button type="button" class="btn2" onclick="checkbox_checked('picids[]');">反选</button></td>
</tr>
<?else :?>
<tr>
<td colspan="6">暂无信息。</td>
</tr>
<?endif;?>
</table>
<div class="multipage"><?=$multipage?></div>
</div>
<center>
<?if($total):?>
<input type="hidden" name="dosubmit" value="yes" />
<input type="hidden" name="op" value="delete" />
<button type="button" class="btn" onclick="submit_form('myform','op','delete',null,null,'picids');">批量删除</button>
<button type="button" class="btn" onclick="submit_form('myform','op','edit',null,null,null);">提交编辑</button>
<?endif;?>
<?if($op != 'check'):?>
<button type="button" class="btn" onclick="document.location='admincp.php?action=<?=$action?>&file=<?=$file?>&op=upload&partyid=<?=$partyid?>'">上传照片</button>
<button type="button" class="btn" onclick="document.location='admincp.php?action=<?=$action?>&file=list';">返回</button>
<?endif;?>
</center>
</form>
<?endif;?>
</div>
</div><file_sep>/core/modules/fenlei/list.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'fenlei');
$F =& $_G['loader']->model(':fenlei');
$_G['loader']->helper('form');
$urlpath = array();
$urlpath[] = url_path($MOD['name'], url("fenlei/index"));
$aid = _get('aid', null, 'intval');
$catid = _get('catid', null, 'intval');
$sid = _get('sid', null, 'intval');
$username = _get('username', null, '_T');
$keyword = _get('keyword', null, '_T');
$topwhere = $where = $active = array();
//城市
$where['city_id'] = $_CITY['aid'];
$topwhere['city_id'] = $_CITY['aid'];
if($sid > 0) {
$S =& $_G['loader']->model('item:subject');
if(!$subject = $S->read($sid)) redirect('iten_subject_empty');
$subject_field_table_tr = $S->display_listfield($subject);
$where['sid'] = $sid;
$urlpath[] = url_path(trim($subject['name'].' '.$subject['subname']), url("fenlei/list/sid/$sid"));
}
if($aid > 0) {
$AREA =& $_G['loader']->model('area');
$aids = $AREA->get_sub_aids($aid);
$paid = $AREA->get_parent_aid($aid, 2);
$where['aid'] = $aids;
$area_level = (count($aids) > 1 && $paid == $aid) ? 3 : 2; //显示等级
$active['paid'][$paid] = " class='selected'";
$active['aid'][$aid] = " class='selected'";
$cityid = $AREA->get_parent_aid($aid, 1);
$area = $_G['loader']->variable('area_'.$cityid);
$urlpath[] = url_path($area[$aid]['name'], url("fenlei/list/aid/$aid"));
}
if($catid > 0) {
if(!$pid = $F->category[$catid]['pid']) {//大类
$pid = $catid;
$CATE =& $_G['loader']->model('fenlei:category');
$catids = $CATE->get_sub_cats($catid);
$where['f.catid'] = array_keys($catids);
} else {//子类
$is_subcat = true;
$where['f.catid'] = $catid;
}
$active['pid'][$pid] = " class='selected'";
$active['catid'][$catid] = " class='selected'";
$urlpath[] = url_path($F->category[$catid]['name'], url("fenlei/list/sid/$sid/aid/$aid/catid/$catid"));
//置顶筛选
$topwhere['{sql}'] = "(top=1)";
if($catids) $topwhere['{sql}'] .= "OR(top=2 AND f.catid IN (".implode(',',array_keys($catids))."))";
if(!$catids && !$is_subcat) $topwhere['{sql}'] .= "OR(top=2 AND f.catid=$catid)";
if($is_subcat && !$catids) {
$topwhere['{sql}'] .= "OR(top IN (2,3) AND f.catid=$catid)";
} elseif($is_subcat) {
$topwhere['{sql}'] = "(".$topwhere['{sql}'].")";
}
} else {
$topwhere['top'] = 1;
}
$where['top'] = 0;
$where['status'] = 1;
$topwhere['top_endtime'] = array('where_more',array($_G['timestamp']));
$topwhere['status'] = 1;
if($username) {
$where['username'] = $username;
}
if($keyword) {
$where['subject'] = array('where_like', array("%{$keyword}%"));
}
$select_field = '';
if($pid > 0) {
$fenlei_field = array();
if($fields = $_G['loader']->variable('field_' . $pid, 'fenlei', FALSE)) {
foreach($fields as $val) {
if(!$val['show_list']) continue;
$select_field .= $split . $val['fieldname'];
$split = ',';
$fenlei_field[] = $val;
}
}
$PFD =& $_G['loader']->model('fielddetail');
$PFD->td_num = 1;
$PFD->class = "";
$PFD->width = "";
$PFD->align = "left";
}
$select = 'f.fid,aid,f.catid,sid,uid,username,subject,endtime,thumb,pageview,comments,content,dateline,color,color_endtime,top,top_endtime';
$orderby = array('dateline'=>'DESC');
$offset = $MOD['list_num'] > 0 ? $MOD['list_num'] : 20;
list($total, $list) = $F->find($select, $where, $orderby, get_start($_GET['page'], $offset), $offset, $select_field, TRUE);
if($total) $multipage = multi($total, $offset, $_GET['page'], url("fenlei/list/sid/$sid/aid/$aid/catid/$catid/username/$username/keyword/$keyword/page/_PAGE_"));
if($_GET['page']=='1') {
$tops = $F->tops($select, $topwhere, array('top'=>'ASC','dateline'=>'DESC'));
}
$_HEAD['keywords'] = $MOD['meta_keywords'];
$_HEAD['description'] = $MOD['meta_description'];
if($subject && $subject['templateid'] && $MOD['use_itemtpl']) {
include template('fenlei_list', 'item', $subject['templateid']);
} else {
include template('fenlei_list');
}
?><file_sep>/core/modules/weixin/admin/templates/coupon_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/jquery.js"></script>
<script type="text/javascript" src="./static/javascript/common.js"></script>
<script type="text/javascript" src="./static/javascript/item.js"></script>
<script type="text/javascript" src="./static/javascript/mdialog.js"></script>
<script type="text/javascript" src="./static/javascript/My97DatePicker/WdatePicker.js"></script>
<link rel="stylesheet" type="text/css" href="./static/images/mdialog.css">
<script type="text/javascript">
var g;
function reload() {
var obj = document.getElementById('reload');
var btn = document.getElementById('switch');
if(obj.innerHTML.match(/^<.+href=.+>/)) {
g = obj.innerHTML;
obj.innerHTML = '<input type="file" name="picture" size="20">';
btn.innerHTML = '取消上传';
} else {
obj.innerHTML = g;
btn.innerHTML = '重新上传';
}
}
function check_submit() {
/*
if ($('[name=subject]').val() == "" && $('[name=subject]').val() == "") {
alert('未填写名称。');
return false;
}
*/
return true;
}
</script>
<div id="body">
<form method="post" action="<?=cpurl($module,$act,'save')?>" name="myform"
enctype="multipart/form-data" onsubmit="return check_submit();">
<input name="sid" id="sid" type="hidden" value="<?php echo $sid;?>"/>
<div class="space">
<div class="subtitle">添加/编辑优惠信息</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1">优惠标题:</td>
<td>
<input type="text" id="subject" name="subject" value="<?=$detail['subject']?>" class="txtbox"/>
</td>
</tr>
<tr>
<td class="altbg1">优惠类型:</td>
<td>
<select name="catid">
<?=form_coupon_category(2,$detail['catid']);?>
</select>
</td>
</tr>
<tr>
<td class="altbg1">优惠方式:</td>
<td>
<select name="catid1" onchange="showbank();" id="catid1">
<?=form_coupon_category(1,$detail['catid1']);?>
</select>
</td>
</tr>
<tr>
<td class="altbg1">所属商家:</td>
<td width="450">
<div id="subject_search"></div>
<script type="text/javascript">
$('#subject_search').item_subject_search({
input_class:'txtbox3',
btn_class:'btn2',
result_css:'item_search_result',
<?if($detail['sid']):?>sid:'<?=$detail[sid]?>',<?endif;?>
hide_keyword:true,
multi:true
});
</script>
<div><span class="font_2">可选多个商家</span></div>
</td>
</tr>
<tr>
<td class="altbg1">优惠图片:</td>
<td>
<?if(!$detail['thumb']):?>
<input type="file" name="picture" size="50"/>
<?else:?>
<span id="reload">
<a href="<?=$detail['picture']?>" target="_blank" src="<?=$detail['thumb']?>" onmouseover="tip_start(this);">
<?=$detail['thumb']?>
</a>
</span> [<a href="javascript:reload();" id="switch">重新上传</a>]
<?endif;?>
</td>
</tr>
<tr>
<td class="altbg1">有效期起:</td>
<td><input type="text" name="starttime" class="txtbox2" value="<?=$detail['starttime']?date('Y-m-d', $detail['starttime']):''?>" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})" validator="{'empty':'N','errmsg':'请选择报名开始时间。'}" /> yyyy-MM-dd</td>
</tr>
<tr>
<td class="altbg1">有效期止:</td>
<td><input type="text" name="endtime" class="txtbox2" value="<?=$detail['endtime']?date('Y-m-d', $detail['endtime']):''?>" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})" validator="{'empty':'N','errmsg':'请选择报名结束时间。'}" /> yyyy-MM-dd</td>
</tr>
<tr>
<td class="altbg1">优惠说明:</td>
<td>
<?=$edit_html?>
</td>
</tr>
</table>
</div>
<center>
<?if($op=='edit'):?>
<input type="hidden" name="couponid" value="<?=$couponid?>" />
<input type="hidden" name="forward" value="<?=get_forward()?>" />
<?endif;?>
<input type="hidden" name="do" value="<?=$op?>" />
<button type="submit" name="dosubmit" value="yes" class="btn" /> 提交 </button>
<button type="button" class="btn" value="yes" onclick="history.go(-1);"> 返回 </button>
</center>
</form>
</div><file_sep>/core/modules/modoer/item/yhlist.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
// 实例化主题类
$D = & $_G ['loader']->model ( 'item:threads' );
//查询条件
$where=array(38,43,44,45,46);
$num = 15;
$start = get_start ( $_GET ['page'], $num );
$select="t.tid,t.fid,t.subject,t.dateline,t.sortid,t.cover";
list ( $total, $list ) = $D->getlist ($select, $where, $order_arr [$orderby], $start, $num, true );
if ($total) {
$multipage = multi ( $total, $num, $_GET ['page'], url ( "item/wmlist/catid/$catid/aid/$aid/order/$order/type/$type/att/$atturl/num/$num/total/$total/wfpage/$wf_page/page/_PAGE_" ) );
}
// 最近的浏览COOKIE
include template ( 'discount_list' );
?><file_sep>/templates/item/sjstyle/about.php
<?exit?>
{template vip2_header}
<script type="text/javascript">
loadscript('swfobject');
$(document).ready(function() {
if(!$.browser.msie && !$.browser.safari) {
var d = $("#thumb");
var dh = parseInt(d.css("height").replace("px",''));
var ih = parseInt(d.find("img").css("height").replace("px",''));
if(dh - ih < 3) return;
var top = Math.ceil((dh - ih) / 2);
d.find("img").css("margin-top",top+"px");
}
<!--{if $MOD['show_thumb'] && $detail['pictures']}-->
get_pictures($sid);
<!--{/if}-->
get_membereffect($sid, $modelid);
});
</script>
<link href="{URLROOT}/img/shop/$detail[c_sjstyle]/style.css" rel="stylesheet" type="text/css" />
<!--头开始-->
<div class="header">
<div class="headerinfo">$detail[name] $detail[subname]</div>
<div class="headermeun">
<ul>
<li><div><a href="{url item/detail/id/$detail[sid]}">首页</a> </div></li>
<li class="in"><div><a href="{url item/vipabout/id/$detail[sid]}">店铺介绍</a> </div></li>
<li><div><a href="{url article/list/sid/$sid}">店铺动态</a> </div></li>
<li><div><a href="{url item/pic/sid/$detail[sid]}">店铺展示</a> </div></li>
<li><div><a href="{url product/list/sid/$sid}">产品展厅</a> </div></li>
<li><div><a href="{url coupon/list/sid/$sid}">优惠打折</a> </div></li>
<li><div><a href="{url item/vipvideo/id/$detail[sid]}">视频展播</a> </div></li>
<li><div><a href="{url item/vipcontact/id/$detail[sid]}">联系方式</a> </div></li>
</ul>
</div>
</div>
<!--头结束-->
<!--头部flash-->
<!--{if $detail[c_pictop1]}-->
<div style="margin:0 auto; width:976px;">
<SCRIPT src="{URLROOT}/img/shop/js/swfobject_source.js" type=text/javascript></SCRIPT>
<DIV id=flashFCI><A href="#" arget=_blank><IMG alt="" border=0></A></DIV>
<SCRIPT type=text/javascript>
var s1 = new SWFObject("{URLROOT}/img/shop/js/focusFlash_fp.swf", "mymovie1", "976", "150", "5", "#ffffff");
s1.addParam("wmode", "transparent");
s1.addParam("AllowscriptAccess", "sameDomain");
s1.addVariable("bigSrc", "$detail[c_pictop1]{if $detail[c_pictop2]}|$detail[c_pictop2]{/if}{if $detail[c_pictop3]}|$detail[c_pictop3]{/if}");
s1.addVariable("smallSrc", "|$detail[c_pictop1]|||");
s1.addVariable("href", "||");
s1.addVariable("txt", "||");
s1.addVariable("width", "976");
s1.addVariable("height", "150");
s1.write("flashFCI");
</SCRIPT>
</div>
<!--{/if}-->
<!--end头部flash-->
<div class="content">
<div class="pagejc">
<div class="col1">
<div class="titles">
<div class="fl">基本信息</div>
<div class="fr"></div>
<div class="clear"></div>
</div>
<div class="neirongs" style="padding:10px;">
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td valign="top">
<a href="{url item/pic/sid/$detail[sid]}"><img src="{URLROOT}/{if $detail[thumb]}$detail[thumb]{else}static/images/noimg.gif{/if}" alt="$detail[name]" width="110" height="80" /></a>
</td>
<td valign="top">
<!--{loop $reviewpot $val}-->$val[name]:<img src="{URLROOT}/img/shop/eshop/z{print cfloat($detail[$val[flag]])}.gif" alt="{print cfloat($detail[$val[flag]])} 分" /><br /><!--{/loop}-->
综合:<img src="{URLROOT}/img/shop/eshop/z{print cfloat($detail[avgsort])}.gif" alt="{print cfloat($detail[avgsort])} 分" />
</td>
</tr>
</table>
<div class="lefttitle">$detail[name]</div>
<div class="leftnr">
管 理 者:
<!--{if $detail[owner]}-->
<a href="{url space/index/username/$detail[owner]}" target="_blank">$detail[owner]</a>
<!--{elseif $catcfg[subject_apply]}-->
<a href="{url item/member/ac/subject_apply/sid/$detail[sid]}"><font color="#cc0000"><b>认领$model[item_name]</b></font></a>
<!--{/if}-->
<!--{if $catcfg[use_subbranch]}-->
<a href="{url item/member/ac/subject_add/subbranch_sid/$detail[sid]}">添加分店</a>
<!--{/if}--><br />
<!--{if $detail[finer]}-->
店铺级别:<img src="{URLROOT}/img/shop/eshop/vip$detail[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
</div>
</div>
<div class="mq"></div>
<div class="titles">地图</div>
<div class="neirongs" style="padding:5px;">
<!--{if $model[usearea]}-->
<!--{eval $mapparam = array(
'title' => $detail[name] . $detail[subname],
'show' => $detail[mappoint]?1:0,
);}-->
<iframe id="item_map1" src="{url index/map/width/240/height/245/title/$mapparam[title]/p/$detail[mappoint]/show/$mapparam[show]}" frameborder="0" scrolling="no"></iframe>
<div style="text-align:center;">
<!--{if !$detail['mappoint']}-->
<a href="javascript:post_map($detail[sid], $detail[pid]);">地图未标注,我来标注</a>
<!--{else}-->
<a href="javascript:show_bigmap();">查看大图</a>
<a href="javascript:post_map($detail[sid], $detail[pid]);">报错</a>
<!--{/if}-->
</div>
<script type="text/javascript">
function show_bigmap() {
var src = "{url index/map/width/600/height/400/title/$mapparam[title]/p/$detail[mappoint]/show/$mapparam[show]}";
var html = '<iframe src="' + src + '" frameborder="0" scrolling="no" width="100%" height="400" id="ifupmap_map"></iframe>';
dlgOpen('查看大图', html, 600, 450);
}
</script>
<!--{/if}-->
</div>
<div class="mq"></div>
</div> <!--col1end-->
<div class="col2">
<!--{if $detail[content]}-->
<div class="titleb"><div class="fl">店铺介绍</div></div>
<div class="neirongb">
<ul class="field">
<!--{if $detail_custom_field}-->
<li>
<table class="custom_field" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class='key' align='left'>得分:</td>
<td width="*">
<!--{loop $reviewpot $val}-->$val[name]:<span class="font_2" style="font-size:16px;">{print cfloat($detail[$val[flag]])}</span><!--{/loop}--> 回头率:<span class="font_1" style="font-size:16px;"><strong>{print cfloat($detail[avgsort])}</strong></span>
<!--{if $detail[avgsort]>=4}--><span class="font_66"><strong>好评</strong> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-good.gif" title="好评" /> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-good.gif" title="好评" /> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-good.gif" title="好评" /></span>
<!--{elseif $detail[avgsort]>=3}--><span class="font_66"><strong>好评</strong> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-good.gif" title="好评" /> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-good.gif" title="好评" /></span>
<!--{elseif $detail[avgsort]>=2}--><span class="font_66"><strong>好评</strong> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-good.gif" title="好评" /></span>
<!--{elseif $detail[avgsort]>=1}--><span class="font_77"><strong>中评</strong> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-neu.gif" title="中评" /></span>
<!--{elseif $detail[avgsort]==0}--><!--{else}--><span class="font_88"><strong>差评</strong> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-bad.gif" title="差评" /></span><!--{/if}-->
</td>
</tr>
$detail_custom_field
<!--{if $catcfg[useeffect]}-->
<tr>
<td class='key' align='left'>会员参与:</td>
<td width="*">
<!--{if $catcfg[effect1]}-->
有 <span id="num_effect1" class="font_2">0</span> 位会员{$catcfg[effect1]}(<a href="javascript:post_membereffect($sid,'effect1');">我{$catcfg[effect1]}</a>,<a style=" text-decoration:underline;" href="javascript:get_membereffect($sid,'effect1','Y');">查看</a>) ,
<!--{/if}-->
<!--{if $catcfg[effect2]}-->
有 <span id="num_effect2" class="font_2">0</span> 位会员{$catcfg[effect2]}(<a href="javascript:post_membereffect($sid,'effect2');">我{$catcfg[effect2]}</a>,<a style=" text-decoration:underline;" href="javascript:get_membereffect($sid,'effect2','Y');">查看</a>) .
<!--{/if}-->
</td>
</tr>
<tr>
<td class='key' align='left'>{$model[item_name]}印象:</td>
<td width="*">
<span id="subject_impress">
<!--{get:item val=impress(sid/$sid/orderby/total DESC/rows/5)}-->
<span class="{print:item tagclassname(total/$val[total])}">$val[title]</span>
<!--{getempty(val)}-->
暂无信息
<!--{/get}-->
<!--{if count($_QUERY[get_val])>=4}-->
<span class="arrow-ico"><a href="javascript:item_impress_get($sid,1);">更多</a></span>
<!--{/if}-->
</span>
</td>
</tr>
<!--{if !$MOD[close_detail_total]}-->
<tr>
<td class='key' align='left'>数据统计:</td>
<td width="*">
<span class="font_2">$detail[pageviews]</span>次浏览,<span class="font_2">$detail[reviews]</span>条点评,<span class="font_2">$detail[guestbooks]</span>条留言,<span class="font_2">$detail[pictures]</span>张图片{if $detail[products]},<span class="font_2">$detail[products]</span>个产品{/if}<!--{if $detail[creator]}-->,<span style="color:#CC3300">感谢<a style="color:#CC3300" href="{url space/index/username/$detail[creator]}" title="{date $detail[addtime]}">$detail[creator]</a>上传图片!</span><!--{/if}-->
</td>
</tr>
<!--{/if}-->
<!--{/if}-->
<!--{if $detail[reviews]<=0}-->
<!--{else}-->
<td class='key' align='left'>网友推荐:</td>
<td width="*">
{get:modoer val=table(table/dbpre_tag_data/select/*/where/id=$sid and tgid=1/orderby/tagid DESC/rows/5/cachetime/10)}<a href="{url item/tag/tagname/$val[tagname]}">$val[tagname]</a><span style="font-size:11px; color:#999999;">($val[total])</span> {/get} <a style="font-size:12px; color:#CA5515;" href="javascript:disq33()">查看全部</a><img style=" margin-left:2px; margin-bottom:3px;" src="{URLROOT}/{$_G[tplurl]}pic/city_li.jpg" />
<div class="clear"></div><div id="caja3">
<p style=" float:right; padding-bottom:10px;"><a href="javascript:disq333()"><img src="{URLROOT}/{$_G[tplurl]}pic/mini-close.gif" /></a></p>
<p>{get:modoer val=table(table/dbpre_tag_data/select/*/where/id=$sid and tgid=1/orderby/tagid DESC/rows/100/cachetime/10)}<a href="{url item/tag/tagname/$val[tagname]}">$val[tagname]</a><span style="font-size:11px; color:#999999;">($val[total])</span> {/get}</p></div>
</td>
</tr>
<!--{/if}-->
<!--{if $_CFG[sharecode]}-->
<tr>
<td class='key' align='left'>内容分享:</td>
<td width="*">
$_CFG[sharecode]
</td>
</tr>
<!--{/if}-->
</table>
</li>
<!--{/if}-->
<li>
<a class="abtn1" href="{url review/member/ac/add/type/item_subject/id/$sid}" onClick="return post_review($sid)"><span><b>我要点评</b></span></a>
<a class="abtn2" href="javascript:item_impress_add($sid);"><span>添加印象</span></a>
<a class="abtn2" href="javascript:post_log($detail[sid]);"><span>补充信息</span></a>
<a class="abtn2" href="javascript:add_favorite($detail[sid]);"><span>收藏商铺</span></a>
<!--{if check_module('article')}-->
<!--{eval $postarticle_url = $detail[ownerid] && $detail[ownerid] == $user->uid ? 'ownernews' : 'membernews';}-->
<a class="abtn2" href="{url article/member/ac/article/op/add/sid/$detail[sid]}"><span>发布资讯</span></a>
<!--{/if}-->
<!--{if !$detail[owner]}-->
<a class="abtn2" href="{url item/member/ac/subject_apply/sid/$detail[sid]}"><span>认领商铺</span></a>
<!--{/if}-->
<p> </p>
<div class="content" id="content">$detail[content]</div>
</div>
<!--{/if}-->
<!--{if $MOD['show_thumb'] && $detail['pictures']}-->
<div class="titleb"><div class="fl">{$model[item_name]}图片</div><div class="fr"><a href="{url item/pic/sid/$detail[sid]}">查看全部</a> <a href="javascript:;" onclick="$('#itempics').toggle();">收起/展开</a></div></div>
<div class="neirongb">
<div class="itempics" id="itempics"{if $catcfg[detail_picture_hide]} style="display:none;"{/if}></div>
<div id="thumb" style="display:none;"><img /></div>
</div>
<!--{/if}-->
</div><!--col2-->
<div class="clear"></div>
</div><!--pagejc-->
</div><!--content-->
</div><!--wrapper-->
{template vip2_footer}
<file_sep>/core/admin/area.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
(! defined ( 'IN_ADMIN' ) || ! defined ( 'IN_MUDDER' )) && exit ( 'Access Denied' );
$op = _input ( 'op' );
$A = & $_G ['loader']->model ( 'area' );
switch ($op) {
case 'select' :
if (! $city_id = _input ( 'city_id', null, MF_INT ))
exit ();
echo form_area ( $city_id );
exit ();
break;
case 'export' :
$A->export ();
break;
case 'import' :
if (! $_POST ['dosubmit']) {
$admin->tplname = cptpl ( 'area_import' );
} else {
if (! $count = $A->import ())
redirect ( 'admincp_area_import_empty' );
redirect ( lang ( 'admincp_area_import_succeed', $count ), cpurl ( $module, $act ) );
}
break;
case 'rebuild' :
$pid=$_GET ['pid'];
//商户数量统计
//require MUDDER_CORE .'item/model/subject_class.php';
$S =& $_G['loader']->model('item:subject');
//团购数量统计
$t =& $_G['loader']->model('tuan:tuandh');
$areas=$A->get_list(8);
foreach ($areas as $area){
$shopnum=$S->get_subject_total($area['aid']);
$tuannum=$t->get_tuandh_total($area['aid']);
$A->updatenum($area['aid'],$shopnum,$tuannum);
}
redirect ('重建成功','/admin.php?module=modoer&act=area&pid='.$pid);
break;
case 'add' :
if (! $_POST ['dosubmit']) {
$pid = ( int ) $_GET ['pid'];
$admin->tplname = cptpl ( 'area_save' );
} else {
$A->save ( $_POST ['area'] );
redirect ( 'global_op_succeed', cpurl ( $module, $act, '', array (
'pid' => $_POST ['area'] ['pid']
) ) );
}
break;
case 'edit' :
if (! $_POST ['dosubmit']) {
$aid = ( int ) $_GET ['aid'];
if (! $aid)
redirect ( sprintf ( lang ( 'global_sql_keyid_invalid' ), 'aid' ) );
if (! $detail = $A->read ( $aid )) {
redirect ( 'global_op_nothing' );
}
$admin->tplname = cptpl ( 'area_save' );
} else {
$aid = ( int ) $_POST ['aid'];
if (! $aid)
redirect ( sprintf ( lang ( 'global_sql_keyid_invalid' ), 'aid' ) );
$A->save ( $_POST ['area'], $aid );
$forward = $_POST ['forward'] ? _T ( $_POST ['forward'] ) : cpurl ( $module, $act );
redirect ( 'global_op_succeed', $forward );
}
break;
case 'delete' :
$aid = _get ( 'aid', null, MF_INT_KEY );
if (! $aid)
redirect ( sprintf ( lang ( 'global_sql_keyid_invalid' ), 'aid' ) );
$A->delete ( $aid );
redirect ( 'global_op_succeed', cpurl ( $module, $act ) );
break;
default :
if (! $_POST ['dosubmit']) {
if (! $pid = ( int ) $_GET ['pid']) {
$pid = 0;
$level = 1;
} else {
if (! $detail = $A->read ( $pid )) {
redirect ( 'admincp_area_empty_pid' );
}
$level = ( int ) $detail ['level'] + 1;
}
$list = $A->get_list ( $pid );
} else {
$A->update ( $_POST ['area'] );
redirect ( 'global_op_succeed', get_forward ( cpurl ( $module, $act ) ) );
}
$admin->tplname = cptpl ( 'area_list' );
}
?><file_sep>/templates/mobile2/redirect.htm
{eval if($auto_url)$header_forward = $auto_url;}
{include mobile_template('header')}
<div class="redirect" id="page_redirect">
$msg
</div>
{include mobile_template('footer')}<file_sep>/core/modules/tuan/model/subscibe_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_tuan_subscibe extends ms_model {
var $table = 'dbpre_subscibe_email';
var $key = 'id';
var $model_flag = 'tuan';
var $_sorts = array();
function __construct() {
parent::__construct();
$this->model_flag = 'tuan';
$this->modcfg = $this->variable('config');
$this->init_field();
}
function msm_tuan_subscibe() {
$this->__construct();
}
function init_field() {
$this->add_field('sort,email,dateline');
$this->add_field_fun('sort,email', '_T');
$this->add_field_fun('dateline', 'intval');
}
function add_sort($sort) {
if(in_array($sort, $this->_sorts)) return;
$this->_sorts[] = $sort;
}
function find($select="*", $where=null, $orderby=null, $start=0, $offset=10, $total=FALSE) {
$this->db->from($this->table);
$where && $this->db->where($where);
$result = array(0,'');
if($total) {
if(!$result[0] = $this->db->count()) {
return $result;
}
$this->db->sql_roll_back('from,where');
}
$this->db->select($select?$select:'*');
if($orderby) $this->db->order_by($orderby);
if($start < 0) {
if(!$result[0]) {
$start = 0;
} else {
$start = (ceil($result[0]/$offset) - abs($start)) * $offset; //按 负数页数 换算读取位置
}
}
$this->db->limit($start, $offset);
$result[1] = $this->db->get();
return $result;
}
function emails($sort,$city_id=null,$start=0,$offset=0) {
$this->db->from($this->table);
$this->db->where('sort', $sort);
if($city_id) $this->db->where('city_id', $city_id);
$this->db->select('email,hash');
if($offset > 0) $this->db->limit($start, $offset);
return $this->db->get();
}
function save($post,$id=null) {
if($id > 0) $edit = true;
if($edit) {
if(!$detail = $this->read($id)) redirect('tuan_subscibe_empty');
} else {
$post['dateline'] = $this->global['timestamp'];
}
$post['hash'] = substr(md5($post['sort'].$post['email']),-8);
$id = parent::save($post,$id);
return $id;
}
function delete($ids) {
$ids = parent::get_keyids($ids);
parent::delete($ids);
}
function delete_hash($hash) {
$this->db->from($this->table);
$this->db->where('hash', $hash);
$this->db->delete();
}
function check_post($post,$edit = false) {
$this->loader->helper('validate');
if(!in_array($post['sort'], $this->_sorts)) redirect('tuan_subscibe_sort_invalid');
if(!$post['email']) redirect('tuan_subscibe_email_empty');
if(!validate::is_email($post['email'])) redirect('tuan_subscibe_email_invalid');
if($this->check_exists($post['sort'], $post['email'])) redirect('tuan_subscibe_exists');
}
function check_exists($sort, $email) {
$this->db->from($this->table);
$hash = substr(md5($sort.$email),-8);
$this->db->where('hash', $hash);
return $this->db->count();
}
}
?><file_sep>/core/modules/tuan/admin/templates/tuandh_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript">
loadscript('mdialog');
function start_send_mail(id) {
}
function addtuandh() {
window.location.href='admin.php?module=tuan&act=tuandh&op=new';
}
</script>
<div id="body">
<form method="post" action="<?=cpurl($module,$act)?>" name="myform">
<div class="space">
<div class="subtitle">数据查询</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="50" class="altbg1"></td>
<td width="50" class="altbg1">团购来源</td>
<td width="100">
<select name="siteid" id="siteid">
<option value="0">全部</option>
<?=form_tuan_tgsite($detail['siteid'])?>
</select>
</td>
<td width="50" class="altbg1">所属分类</td>
<td width="100">
<select name="catid" id="catid">
<option value="0">全部</option>
<?=form_tuan_category($detail['catid'])?>
</select>
</td>
<td width="30" class="altbg1">状态</td>
<td width="70">
<select name="catid" id="catid">
<option value="0">全部</option>
<option value="0">进行中</option>
<option value="0">已结束</option>
<option value="0">将开始</option>
</select>
</td>
<td width="30" class="altbg1">审核</td>
<td width="70">
<select name="catid" id="catid">
<option value="0">全部</option>
<option value="0">已审核</option>
<option value="0">未审核</option>
</select>
</td>
<td><button type="submit" value="yes" name="dosubmit" class="btn2">筛选</button> </td>
</tr>
</table>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y">
<tr class="altbg1">
<td width="30" align="center">选择</td>
<td width="30" align="center">排序</td>
<td width="270" align="center">团购名称</td>
<td width="120" align="center">商家</td>
<td width="60" align="center">分类</td>
<td width="120" align="center">网站</td>
<td width="60" align="center">状态</td>
<td width="130" align="center">操作</td>
</tr>
<?if($total):?>
<?while($val=$list->fetch_array()) {?>
<tr>
<td align="center"><input type="checkbox" name="ids[]" value="<?=$val['id']?>" /></td>
<td align="center"><input type="text" name="tgsite[<?=$val[id]?>][listorder]" value="<?=$val[listorder]?>" class="txtbox5" /></td>
<td><?=$val['subject']?></td>
<td align="center"><?=$val['sname']?></td>
<td align="center"><?=$val['catname']?></td>
<td align="center"><?=$val['webname']?></td>
<td align="center"><?=$val['status']?></td>
<td align="center">
<div>
<a href="<?=cpurl($module,$act,'edit', array('id'=>$val['id']))?>">编辑</a>
<a href="<?=cpurl($module,$act,'delete', array('id'=>$val['id']))?>" onclick="return confirm('您确定要删除吗?');">删除</a>
<a href="<?=$val['url']?>" target="_blank">出处</a>
</div>
</td>
</tr>
<?}?>
<tr class="altbg1">
<td colspan="2"><button type="button" onclick="checkbox_checked('ids[]');" class="btn2">全选</button></td>
<td colspan="4" style="text-align:right;"><?=$multipage?></td>
</tr>
<?else:?>
<tr><td colspan="10">暂无信息</td></tr>
<?endif;?>
</table>
</div>
<center>
<input type="hidden" name="op" value="update" />
<input type="hidden" name="dosubmit" value="yes" />
<button type="button" class="btn" onclick="addtuandh();">新增团购</button>
<?if($total):?>
<button type="button" class="btn" onclick="easy_submit('myform','update',null);">更新权重</button>
<?endif;?>
</center>
</form>
</div><file_sep>/core/modules/tuan/api.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
!defined('SCRIPTNAV') && define('SCRIPTNAV', 'tuan');
$n = strtolower(_get('n', null, MF_TEXT));
if(!empty($n)) {
$classfile = MOD_ROOT . 'model' . DS . 'api' . DS . $n . '.php';
if(!is_file($classfile)) show_error('不存在的团购api接口.');
$classname = 'tuan_api_'.$n;
} else {
show_error('未提供团购api名称.');
}
require_once $classfile;
$api = new $classname();
header('Content-Type:text/xml');
echo $api->get_xml();
output();
?><file_sep>/core/modules/tuan/email.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'tuan');
$TS =& $_G['loader']->model('tuan:subscibe');
$TS->add_sort('tuan');
$op = _input('op');
switch($op) {
case 'unsubscibe':
if(!$hash = _get('hash', null, MF_TEXT)) redirect(lang('global_sql_keyid_invalid','hash'));
$TS->delete_hash($hash);
redirect('global_op_succeed', url("tuan/index"));
break;
case 'send':
//邮件发送
if(!$tid = _input('tid', null, 'intval')) redirect(lang('global_sql_keyid_invalid', 'tid'));
$T =& $_G['loader']->model(':tuan');
if(!$detail = $T->read($tid)) redirect('tuan_empty');
$coupon_print = $detail['coupon_print'] ? unserialize($detail['coupon_print']) : array();
$S =& $_G['loader']->model('item:subject');
$subject = $S->read($detail['sid']);
$subject_field_table_tr = $S->display_listfield($subject);
$TS =& $_G['loader']->model('tuan:subscibe');
$offset = $MOD['mail_num'] > 0 ? $MOD['mail_num'] : 10;
$start = get_start($_GET['page'], $offset);
if(!$list = $TS->emails('tuan', $detail['city_id'], $start, $offset)) {
echo "completed";exit;
}
$_G['fullalways'] = TRUE;
include template('tuan_send_email');
//发送
$message = ob_get_contents();
ob_end_clean();
$_G['cfg']['gzipcompress'] ? @ob_start('ob_gzhandler') : ob_start();
if($_CFG['mail_use_stmp']) {
$_CFG['mail_stmp_port'] = $_CFG['mail_stmp_port'] > 0 ? $_CFG['mail_stmp_port'] : 25;
$auth = ($_CFG['mail_stmp_username'] && $_CFG['mail_stmp_password']) ? TRUE : FALSE;
$_G['loader']->lib('mail',null,false);
$MAIL = new ms_mail($_CFG['mail_stmp'], $_CFG['mail_stmp_port'], $auth, $_CFG['mail_stmp_username'], $_CFG['mail_stmp_password']);
$MAIL->debug = $_CFG['mail_debug'];
}
$succeed = $result = false;
$subject = '['.$_CFG['sitename'].']'.$detail['subject'];
while($val=$list->fetch_array()) {
$email = $val['email'];
$message = str_replace('_HASH_', $val['hash'], $message);
if($_CFG['mail_use_stmp']) {
$result = @$MAIL->sendmail($email, $_CFG['mail_stmp_email'], $subject, $message, 'HTML');
} else {
$result = @mail($email, $subject, $message);
}
if(!$succeed && $result) $succeed = TRUE;
}
$list->free_result();
$_GET['page']++;
echo $tid . ',' . $_GET['page'];
exit;
default:
//邮件订阅
$post = array('city_id' => $_CITY['aid'], 'sort'=>'tuan', 'email' => _input('email', null, MF_TEXT));
$TS->save($post);
redirect('global_op_succeed', get_forward(url("tuan/index")));
}
?><file_sep>/core/modules/fenlei/model/fenlei_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
class msm_fenlei extends ms_model {
var $table = 'dbpre_fenlei';
var $category_table = 'dbpre_fenlei_category';
var $key = 'fid';
var $model_flag = 'fenlei';
var $status = array(0,1,2);
var $category = null;
function __construct() {
parent::__construct();
$this->model_flag = 'fenlei';
$this->modcfg = $this->variable('config');
$this->category = $this->variable('category');
$this->init_field();
}
function msm_fenlei() {
$this->__construct();
}
function init_field() {
$this->add_field('catid,city_id,aid,sid,subject,uid,status,linkman,contact,email,im,address,content,endtime,mappoint,color,color_endtime,top,top_endtime');
$this->add_field_fun('catid,city_id,aid,sid,uid,status', 'intval');
$this->add_field_fun('subject,linkman,contact,email,im,address,color,color_endtime,top,top_color', '_T');
$this->add_field_fun('content', '_HTML');
}
function read($fid, $load_field = TRUE) {
if(!$result = parent::read($fid)) return;
if($result['map_lng'] != 0 && $result['map_lat'] != 0) {
$result['mappoint'] = $result['map_lng'].','.$result['map_lat'];
}
if($fields = $this->read_field($result['catid'], $fid)) {
$result = array_merge($result, $fields);
}
return $result;
}
function & read_field($catid, $fid) {
if(!$cat = $this->category[$catid]) return;
$pid = $cat['pid'] ? $cat['pid'] : $catid;
if(!$pid) return;
$table = 'dbpre_fenlei_' . $pid;
$this->db->from($table);
$this->db->where('fid',$fid);
return $this->db->get_one();
}
function list_display($detail) {
if(!$pid = $this->category[$detail['catid']]['pid']) return '';
if(!$fieldids = $this->category[$detail['catid']]['fieldids']) return;
if($fieldids) $fieldids = explode(',', $fieldids);
//生成表格内容
$FD =& $this->loader->model('fielddetail');
//样式设计
$FD->class = 'key';
$FD->width = '';
$result = '';
//载入字段信息
$fields = $this->variable('field_' . $pid);
$myfields = array();
foreach($fieldids as $id) {
$myfields[$id] = $fields[$id];
}
foreach($myfields as $val) {
if($val['show_list']) $result .= $FD->detail($val, $detail[$val['fieldname']]);
}
return $result;
}
//读取单个详细样式主题
function display_detailfield($detail) {
if(!$pid = $this->category[$detail['catid']]['pid']) return '';
if(!$fieldids = $this->category[$detail['catid']]['fieldids']) return;
if($fieldids) $fieldids = explode(',', $fieldids);
//生成表格内容
$FD =& $this->loader->model('fielddetail');
//样式设计
$FD->class = 'key';
$FD->width = '';
$result = '';
//载入字段信息
$fields = $this->variable('field_' . $pid);
$myfields = array();
foreach($fieldids as $id) {
$myfields[$id] = $fields[$id];
}
foreach($myfields as $val) {
if($val['show_detail']) $result .= $FD->detail($val, $detail[$val['fieldname']]);
}
return $result;
}
//生成提交表单
function create_from($catid, $data = null, $style = null) {
if(!$catid) redirect('fenlei_category_empty');
if(!$cat = $this->category[$catid]) return '';
if(!$cat['fieldids']) return '';
$pid = $cat['pid'];
if(!$fields = $this->variable('field_' . $pid, $this->model_flag)) return '';
//只获取选择的字段
$fieldlist = explode(',', $cat['fieldids']);
$myfields = array();
foreach($fieldlist as $id) {
if(!$id) continue;
$myfields[$id] = $fields[$id];
}
$FF =& $this->loader->model('fieldform');
if($this->in_admin) {
$FF->width = "100";
$FF->class = "altbg1";
$FF->align = "left";
} else {
$FF->width = "80";
$FF->align = "right";
}
$content = '';
foreach($myfields as $val) {
$content .= $FF->form($val, $data ? $data[$val['fieldname']] : '', $data != null) . "\r\n";
}
return $content;
}
function find($select, $where, $orderby="fid", $start=0, $offset=0, $select_field='', $ctotal=TRUE) {
$linkfield = false;
if($where['f.catid'] && $select_field) {
$catid = is_array($where['f.catid']) ? $where['f.catid'][0] : $where['f.catid'];
$pid = $this->category[$catid]['pid'];
!$pid && $pid = $catid;
if($pid) {
$table = 'dbpre_fenlei_' . $pid;
$this->db->join($this->table,'f.fid',$table,'ff.fid');
$linkfield = TRUE;
}
}
if(!$linkfield) {
$this->db->from($this->table, 'f');
}
$this->db->where($where);
$result = array(0,'');
if(!$result[0] = $this->db->count()) {
return $result;
}
$this->db->sql_roll_back('from,where');
$this->db->select($select);
if($linkfield && $select_field) $this->db->select($select_field);
if($orderby) $this->db->order_by($orderby);
if($start < 0) {
if(!$result[0]) {
$start = 0;
} else {
$start = (ceil($result[0]/$offset) - abs($start)) * $offset; //按 负数页数 换算读取位置
}
}
$this->db->limit($start, $offset);
$result[1] = $this->db->get();
return $result;
}
function tops($select, $where, $orderby=array('top'=>'ASC','dateline'=>'DESC')) {
$this->db->from($this->table,'f');
$this->db->where($where);
$this->db->select($select);
return $this->db->get();
}
function checklist($where = array()) {
$result = array(0,null,null);
$this->db->from($this->table);
if($where) $this->db->where($where);
$this->db->where('status',0);
if($result[0] = $this->db->count()) {
$this->db->sql_roll_back('from,where');
$this->db->select('fid,subject,city_id,aid,catid,dateline,uid,username,linkman');
$this->db->order_by('dateline', 'DESC');
$offset = 20;
$this->db->limit(get_start($_GET['page'], $offset), $offset);
$result[1] = $this->db->get();
$result[2] = multi($total, $_GET['offset'], $_GET['page'], cpurl($module, $act, 'checklist'));
}
return $result;
}
function save(& $post, $fid = null, $role='member') {
$edit = $fid > 0;
if($edit) {
if(!$detail = $this->read($fid)) redirect('fenlei_empty');
$catid = $detail['catid'];
if(!$this->in_admin && isset($post['status'])) unset($post['status']);
//判断权限
$access = $this->check_post_access('edit', $role, $detail['sid'], $detail['uid']);
} else {
$catid = $post['catid'];
if($this->in_admin) {
$post['uid'] = 0;
$post['username'] = $this->global['admin']->adminname;
} else {
$post['uid'] = $this->global['user']->uid;
$post['username'] = $this->global['user']->username;
$post['status'] = $this->modcfg['post_check'] ? 0 : 1;
}
$post['dateline'] = $this->global['timestamp'];
//判断权限
$access = $this->check_post_access('add', $role, $post['sid'], $post['uid']);
}
//设置城市ID
$AREA =& $this->loader->model('area');
$city_id = $AREA->get_parent_aid($post['aid']);
$post['city_id'] = $city_id;
//置顶和变色
$total_point = 0;
if($this->modcfg['buy_top']&&(!empty($post['top'])||!empty($post['top_endtime']))) {
$tops = $this->_calc_top_point($post['top'],$post['top_endtime']);
if($tops) list($post['top'],$post['top_endtime'],$top_point) = $tops;
$top_point = (int) $top_point;
}
if($this->modcfg['buy_color']&&(!empty($post['color'])||!empty($post['color_endtime']))) {
$colors = $this->_calc_color_point($post['color'],$post['color_endtime']);
if($colors) list($post['color'],$post['color_endtime'],$color_point) = $colors;
$color_point = (int) $color_point;
}
if(!$this->in_admin && ($tops||$colors)) {
if(!$pointtype = $this->modcfg['pointtype']) redirect('fenlei_post_pointtype_empty');
$total_point = $top_point + $color_point;
$pointname = display('member:point',"point/$pointtype");
if($this->global['user']->$pointtype < $total_point) {
redirect(lang('fenlei_post_point_not_enough',array($total_point,$pointname,$this->global['user']->$pointtype,$pointname)));
}
}
//有效期
if($post['endtime']) {
if(!preg_match("/^[0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $post['endtime'])) redirect('global_time_invalid');
$post['endtime'] = strtotime($post['endtime']);
}
if(!$cat = $this->category[$catid]) redirect('fenlei_category_empty');
$pid = $cat['pid'];
if(isset($post['mappoint'])) {
list($post['map_lng'],$post['map_lat']) = $this->_pares_map($post['mappoint']);
unset($post['mappoint']);
}
if(isset($post['custom_post'])) {
if(is_array($post['custom_post'])) {
$F =& $this->loader->model('fenlei:field');
$custom_post = $F->validator($catid, $post['custom_post']);
}
unset($post['custom_post']);
}
if($_FILES['thumb']['name']) {
$this->loader->lib('upload_image', NULL, FALSE);
$img = new ms_upload_image('thumb', $this->global['cfg']['picture_ext']);
$this->upload_thumb($img);
$post['thumb'] = str_replace(DS, '/', $img->path . '/' . $img->thumb_filenames['thumb']['filename']);
}
if($edit && $detail['thumb'] && $post['thumb']) {
$this->_delete_thumb($detail['thumb']);
}
$fid = parent::save($post, $fid);
//更新户用积分
if($total_point>0 && !$this->in_admin) {
$P =& $this->loader->model('member:point');
$P->update_point2($this->global['user']->uid, $pointtype, -$total_point, 'fenlei_update_point_add_des');
unset($P);
}
//更新分类统计
if($edit) {
if($detail['catid'] != $post['catid']) { //是否更换了分类
if($detail['status']) $this->category_num($detail['catid'],-1); //原分类通过审核的数量-1
if($post['status']) $this->category_num($post['catid'],1); //新分类数量+1
} else {
if(!$detail['status'] && $post['status']) {
$this->category_num($post['catid'],1); //通过审核+1
} elseif($detail['status'] && isset($post['status']) && $post['status']==0 ) {
$this->category_num($post['catid'],-1); //更改审核状态-1
}
}
if(!$detail['status'] && $post['status']) {
$this->user_point_add($detail['uid']); //用户积分
$detail['uid']>0 && $this->_feed($fid); //feed
}
} elseif($post['status']) {
define('RETURN_EVENT_ID', 'global_op_succeed');
$this->category_num($post['catid'],1); //新入不需要审核+1
$this->user_point_add($post['uid']); //用户积分
$post['uid']>0 && $this->_feed($fid); //feed
} else {
define('RETURN_EVENT_ID', 'global_op_succeed_check');
}
//更新附加表
$custom_post['catid'] = $post['catid']; //子分类ID
$this->save_field($pid, $fid, $custom_post, $edit);
return $fid;
}
//保存附加表的数据
function save_field($catid, $fid, $post=null, $edit=FALSE) {
$table = 'dbpre_fenlei_' . $catid;
if($edit && $post) {
$this->db->from($table);
$this->db->set($post);
$this->db->where('fid',$fid);
$this->db->update();
} else {
$this->db->from($table);
$this->db->set('fid',$fid);
if($post) $this->db->set($post);
$this->db->insert();
}
}
//更新
function update($post) {
if(!$post || !is_array($post)) redirect('global_op_unselect');
foreach($post as $fid => $val) {
unset($val['fid']);
$val['finer'] = (int) $val['finer'];
$this->db->from($this->table);
$this->db->set($val);
$this->db->where('fid',$fid);
$this->db->update();
}
}
//删除
function delete($ids,$up_point=false) {
$ids = parent::get_keyids($ids);
$this->_delete(array('fid'=>$ids), TRUE, $up_point);
}
//删除某些分类的
function delete_catids($catids) {
if(!$catids) return;
$this->_delete(array('catid'=>$catids), FALSE, FALSE);
}
//删除某些主题的
function delete_sids($sids) {
if(empty($sids)) return;
$where = array('sid'=>$sids);
$this->_delete($where);
}
//更新分类统计
function category_num($catid, $num=1) {
if(!$num) return;
$this->db->from($this->category_table);
if($num > 0) {
$this->db->set_add('num',$num);
} else {
$this->db->set_dec('num',abs($num));
}
$this->db->where('catid',$catid);
$this->db->update();
}
// 增加积分
function user_point_add($uid, $num = 1) {
if(!$uid) return;
$P =& $this->loader->model('member:point');
$BOOL = $P->update_point($uid, 'add_fenlei', FALSE, $num);
/*
if(!$BOOL) return;
$this->db->set_add('fenleis', $num);
$this->db->update();
*/
}
// 减少积分
function user_point_dec($uid, $num = 1) {
if(!$uid) return;
$P =& $this->loader->model('member:point');
$BOOL = $P->update_point($uid, 'add_fenlei', TRUE, $num);
/*
if(!$BOOL) return;
$this->db->set_dec('fenleis', $num);
$this->db->update();
*/
}
//增加浏览量
function pageview($fid, $num=1) {
$this->db->from($this->table);
$this->db->set_add('pageview', $num);
$this->db->where('fid',$fid);
$this->db->update();
}
//审核
function checkup($ids,$uppoint=true) {
$ids = parent::get_keyids($ids);
$this->db->from($this->table);
$this->db->where_in('fid', $ids);
$this->db->where('status', 0);
$this->db->select('fid,uid,status,catid,thumb');
if(!$q=$this->db->get()) return;
$fids = $catids = $uids = array();
while($v=$q->fetch_array()) {
$fids[] = $v['fid'];
if(isset($catids[$v['catid']])) {
$catids[$v['catid']]++;
} else {
$catids[$v['catid']] = 1;
}
if(!$uppoint||!$v['uid']) continue;
if(isset($uids[$v['uid']])) {
$uids[$v['uid']]++;
} else {
$uids[$v['uid']] = 1;
}
$v['uid'] > 0 && $this->_feed($v['fid']); //feed
}
$q->fetch_array();
if($catids) {
foreach($catids as $catid => $num) {
$this->category_num($catid, $num);
}
}
if($uids) {
foreach($uids as $uid => $num) {
$this->user_point_add($uid, $num);
}
}
if($fids) {
$this->db->from($this->table);
$this->db->set('status',1);
$this->db->where_in('fid',$fids);
$this->db->update();
}
}
//提交判断
function check_post(& $post) {
if(!$this->category) redirect('fenlei_post_not_category');
if(!$post['catid'] || $post['catid'] <1) redirect('fenlei_post_catid_empty');
if(!$this->category[$post['catid']]) redirect('fenlei_post_catid_invalid');
if(!$this->category[$post['catid']]['pid']) redirect('fenlei_post_not_subcat');
if(!$post['aid']) redirect('fenlei_post_aid_empty');
if(!$post['subject']) redirect('fenlei_post_subject_empty');
if(!$post['linkman']) redirect('fenlei_post_linkmain_empty');
if($post['contact'] && !preg_match("/^[0-9\-\+]+$/", $post['contact'])) redirect('fenlei_post_contact_invalid');
if(!$post['content']) redirect('fenlei_post_content_empty');
}
//上传图片
function upload_thumb(& $img) {
$thumb_w = $this->modcfg['thumb_width'] ? $this->modcfg['thumb_width'] : 200;
$thumb_h = $this->modcfg['thumb_height'] ? $this->modcfg['thumb_height'] : 200;
$img->set_max_size($this->global['cfg']['picture_upload_size']);
$img->userWatermark = $this->global['cfg']['watermark'];
$img->watermark_postion = $this->global['cfg']['watermark_postion'];
$img->thumb_mod = $this->global['cfg']['picture_createthumb_mod'];
//$img->limit_ext = array('jpg','png','gif');
$img->set_ext($this->global['cfg']['picture_ext']);
$img->set_thumb_level($this->global['cfg']['picture_createthumb_level']);
$img->add_thumb('thumb', 'thumb_', $thumb_w, $thumb_h);
$img->upload('fenlei');
}
//会员组权限判断
function check_access($key,$value,$jump) {
if($this->in_admin) return TRUE;
if($key=='fenlei_post') {
$value = (int) $value;
if($value) {
if(!$jump) return FALSE;
if(!$this->global['user']->isLogin) redirect('member_not_login');
redirect('fenlei_access_disable');
}
} elseif($key=='fenlei_delete') {
$value = (int) $value;
if($value) {
if(!$jump) return FALSE;
redirect('fenlei_access_delete');
}
}
return TRUE;
}
//判断2种角色的提交权限
function check_post_access($op='add',$role='member',$sid,$uid) {
if($this->in_admin) return TRUE;
if($op == 'add') {
if($role == 'owner') {
!$sid && redirect('fenlei_post_sid_empty');
$S=&$this->loader->model('item:subject');
return $S->is_mysubject($sid, $uid);
} else {
return $this->global['user']->check_access('fenlei_post', $this, 0);
}
} else {
if($role == 'owner') {
!$sid && redirect('fenlei_post_sid_empty');
$S=&$this->loader->model('item:subject');
return $S->is_mysubject($sid, $uid);
} elseif($this->global['user']->uid == $uid) {
return TRUE;
}
}
return false;
}
//判断删除权限
function check_delete_access($uid,$sid,&$mysubjects) {
if($this->in_admin) return true;
if($sid>0 && in_array($sid,$mysubjects)) return true;
if($uid>0 && $uid == $this->global['user']->uid && $this->global['user']->check_access('fenlei_delete',$this,0)) return true;
return false;
}
//删除分类信息
function _delete($where, $up_total = TRUE, $up_point = FALSE) {
$this->db->from($this->table);
$this->db->where($where);
$this->db->select('fid,sid,uid,status,catid,thumb');
if(!$q=$this->db->get()) return;
if(!$this->in_admin) {
$S =& $this->loader->model('item:subject');
$mysubjects = $S->mysubject($this->global['user']->uid);
}
$fids = $catids = $uids = array();
while($v=$q->fetch_array()) {
//权限判断
$access = $this->in_admin || $this->check_delete_access($v['uid'],$v['sid'],$mysubjects);
if(!$access) redirect('global_op_access');
$fids[$v['fid']] = $v['catid'];
if($v['thumb']) $this->_delete_thumb($v['thumb']);
if($v['status']=='1') {
if($up_total) {
if(isset($catids[$v['catid']])) {
$catids[$v['catid']]++;
} else {
$catids[$v['catid']] = 1;
}
}
if(!$up_point||!$v['uid']) continue;
if(isset($uids[$v['uid']])) {
$uids[$v['uid']]++;
} else {
$uids[$v['uid']] = 1;
}
}
}
if($up_total && $catids) {
foreach($catids as $catid => $num) {
$this->category_num($catid, -$num);
}
}
if($uids) {
foreach($uids as $uid => $num) {
$this->user_point_dec($uid, $num);
}
}
if($fids) {
$ids = array_keys($fids);
$this->_delete_fields($fids);
$this->_delete_comments($ids);
parent::delete($ids);
}
}
//删除附表
function _delete_fields($fids) {
$list = array();
foreach($fids as $id=>$catid) {
if(!$cat = $this->category[$catid]) continue;
$list[$cat['pid']][] = $id;
}
if(!$list) return;
foreach($list as $pid => $ids) {
if(!$pid||!is_numeric($pid)) continue;
$this->db->from('dbpre_fenlei_'.$pid);
$this->db->where('fid',$ids);
$this->db->delete();
}
}
//删除图片
function _delete_thumb($thumb) {
@unlink(MUDDER_ROOT . $thumb);
@unlink(MUDDER_ROOT . str_replace("/thumb_", "/", $thumb));
}
// 删除评论表
function _delete_comments($ids) {
//删除评论
if(check_module('comment')) {
$CM =& $this->loader->model(':comment');
$CM->delete_id('fenlei', $ids);
}
}
//解析地图坐标
function _pares_map($point) {
$result = array(0,0);
list($lng,$lat) = explode(',', trim($point));
if(!$lng || !$lat) return $result;
if(!preg_match("/[0-9\-\.]+/", $lng) || !preg_match("/[0-9\-\.]+/", $lat)) return $result;
return array($lng,$lat);
}
//计算置顶花费的积分
function _calc_top_point($top,$top_endtime) {
//类别
if(!$top) redirect('fenlei_post_top_empty');
if(!$this->modcfg['top_level']) return;
$tops = explode(',', $this->modcfg['top_level']);
if(count($tops) != 3) return 0;
$basenum = $tops[$top-1];
if(!$basenum || !is_numeric($basenum)) redirect('fenlei_post_top_invalid');
//时间
if(!$top_endtime) redirect('fenlei_post_top_day_empty');
if(!$this->modcfg['top_days']) return;
$days = explode("\r\n", $this->modcfg['top_days']);
if(!in_array($top_endtime, $days)) redirect('fenlei_post_top_day_invalid');
//top_endtime
list($d,$p) = explode('|', $top_endtime);
if(!$d||!$p||!is_numeric($d)||!is_numeric($p)) redirect(lang('fenlei_post_system_error').'[1]');
$point = round($p * $basenum);
$endtime = $this->global['timestamp'] + (24*3600*$d);
return array($top,$endtime,$point);
}
//计算变色花费的积分
function _calc_color_point($color,$color_endtime) {
//颜色
if(!$color) redirect('fenlei_post_color_empty');
if(!$this->modcfg['colors']) return;
$colors = explode(',', $this->modcfg['colors']);
if(!in_array($color,$colors)) redirect('fenlei_post_color_invalid');
//时间
if(!$color_endtime) redirect('fenlei_post_color_day_empty');
if(!$this->modcfg['color_days']) return;
$days = explode("\r\n", $this->modcfg['color_days']);
if(!in_array($color_endtime, $days)) redirect('fenlei_post_color_day_invalid');
list($d,$p) = explode('|', $color_endtime);
if(!$d||!$p||!is_numeric($d)||!is_numeric($p)) redirect(lang('fenlei_post_system_error').'[2]');
$endtime = $this->global['timestamp'] + (24*3600*$d);
return array($color,$endtime,$p);
}
//feed
function _feed($fid) {
if(!$fid) return;
$FEED =& $this->loader->model('member:feed');
if(!$FEED->enabled()) return;
$this->global['fullalways'] = TRUE;
if(!$detail = $this->read($fid, false)) return;
if(!$detail['uid']) return;
$feed = array();
$feed['icon'] = lang('fenlei_feed_icon');
$feed['title_template'] = lang('fenlei_feed_title_template');
$feed['title_data'] = array (
'username' => '<a href="'.url("space/index/uid/$detail[uid]").'">' . $detail['username'] . '</a>',
);
$feed['body_template'] = lang('fenlei_feed_body_template');
$feed['body_data'] = array (
'subject' => '<a href="'.url("fenlei/detail/id/$detail[fid]").'">' . $detail['subject'] . '</a>',
);
$feed['body_general'] = trimmed_title(strip_tags(preg_replace("/\[.+?\]/is", '', $detail['content'])), 150);
$FEED->save($this->model_flag, $detail['city_id'], $feed['icon'], $detail['uid'], $detail['username'], $feed);
//$FEED->add($feed['icon'], $detail['uid'], $detail['username'], $feed['title_template'], $feed['title_data'], $feed['body_template'], $feed['body_data'], $feed['body_general']);
}
}
?><file_sep>/core/modules/fenlei/model/category_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
class msm_fenlei_category extends ms_model {
var $table = 'dbpre_fenlei_category';
var $key = 'catid';
var $model_flag = 'fenlei';
function __construct() {
parent::__construct();
$this->model_flag = 'fenlei';
$this->modcfg = $this->variable('config');
$this->init_field();
}
function msm_fenlei_category() {
$this->__construct();
}
function init_field() {
$this->add_field('catid,pid,name,post_tpl,list_tpl,detail_tpl,listorder');
$this->add_field_fun('catid,pid,listorder', 'intval');
$this->add_field_fun('name,post_tpl,list_tpl,detail_tpl', '_T');
}
function read_all($pid=null) {
$this->db->from($this->table);
if(isset($pid)) {
$this->db->where('pid',$pid);
}
$this->db->order_by('listorder');
if(!$q=$this->db->get()) return;
while($v=$q->fetch_array()) {
$result[$v['catid']] = $v;
}
$q->free_result();
return $result;
}
function save($post, $catid=null) {
$edit = $catid > 0;
if($edit) {
if(!$detail = $this->read($catid)) redirect('fenlei_category_empty');
}
$newcatid = parent::save($post, $catid);
//增加一个主分类是,新建一个表
if(!$edit && $newcatid && $post['pid']==0) {
//建立分类数据附表
$this->_create_table($newcatid);
}
}
function update($post) {
if(!$post) return;
foreach($post as $key=>$val) {
parent::save($val,$key,false);
}
$this->write_cache();
}
function delete($catid) {
if(!$catid = (int) $catid) return;
if(!$category = $this->read($catid)) redirect('fenlei_category_empty');
$catids = array();
$pid = 0;
//删除的是主分类的操作
if($category['pid']) {
$pid = $category['pid'];
} else {
$pid = $catid;
$this->db->from($this->table);
$this->db->where('pid',$pid);
if($q = $this->db->get()) {
while($v = $q->fetch_array()) {
$catids[] = $v['catid'];
}
$q->free_result();
}
}
$catids[] = $catid;
$F =& $this->loader->model(':fenlei');
$F->delete_catids($catids, $pid);
parent::delete($catids); //删除分类表
}
function select($catid,$fieldids) {
if(!$catid || !is_numeric($catid)) return;
$this->db->from($this->table);
$this->db->where('catid',$catid);
$this->db->set('fieldids', is_array($fieldids)?implode(',',$fieldids):'');
$this->db->update();
$this->write_cache();
}
function write_cache($return=FALSE) {
$this->db->from($this->table);
$this->db->order_by(array('pid'=>'ASC','listorder'=>'ASC'));
$list = $this->db->get();
$result = array();
$js_content = "var fenlei_category_root = new Array();\n";
$js_content .= "var fenlei_category_sub = new Array();\n";
if($list) {
while($val=$list->fetch_array()) {
$result[$val['catid']] = $val;
if(!$val['pid']) {
$js_content .= "fenlei_category_root[$val[catid]] = '$val[name]';\n";
$js_content .= "fenlei_category_sub[$val[catid]] = new Array();\n";
} else {
$js_content .= "fenlei_category_sub[$val[pid]][$val[catid]] = '$val[name]';\n";
}
}
$list->free_result();
}
write_cache('category', arrayeval($result), $this->model_flag);
write_cache('fenlei_category', $js_content, $this->model_flag, 'js');
//js更新标识
$C =& $this->loader->model('config');
$C->save(array('jscache_flag'=>rand(1,1000)), 'fenlei');
unset($js_content);
if($return) return $return;
}
function check_post(& $post) {
if(!$post['name']) redirect('fenlei_category_name_empty');
}
//取子分类列表
function get_sub_cats($id) {
$result = array();
$category = $this->variable('category');
if($category[$id]['pid']) {
$id = $category[$id]['pid'];
}
foreach($category as $val) {
if($val['pid'] == $id) $result[$val['catid']] = $val['name'];
}
return $result;
}
function _create_table($catid) {
$sql = "fid mediumint(8) unsigned NOT NULL,\n catid smallint(5) unsigned NOT NULL,\n PRIMARY KEY (fid)";
$tablename = $this->db->dns['dbpre'] . 'fenlei_' . $catid;
$sql = "CREATE TABLE IF NOT EXISTS " . $tablename . " ($sql) ";
if ($this->db->version() > '4.1') {
$sql .= "ENGINE=MyISAM DEFAULT CHARSET=".$this->db->dns['dbcharset'];
} else {
$sql .= "TYPE=MyISAM";
}
$this->db->query($sql);
}
function _delete_table($catid) {
$tablename = $this->db->dns['dbpre'] . 'fenlei_' . $catid;
$this->db->query("DROP TABLE IF EXISTS " . $tablename);
}
}
?><file_sep>/templates/mobile/js/location.js
$(function(){
if (window.navigator.geolocation) {
var options = {
enableHighAccuracy: true,
timeout: 50000,
// 最长有效期,在重复获取地理位置时,此参数指定多久再次获取位置。
maximumAge: 6000
};
//document.getElementById('currentPosLng').innerHTML = 'GPSing';
window.navigator.geolocation.getCurrentPosition(successHandle,errorHandle,options);
} else {
notice("浏览器不支持html5来获取地理位置信息!");
}
function successHandle(position){
var lat = position.coords.longitude;
var lng = position.coords.latitude;
var dist = getDistance($.cookie('lng'),$.cookie('lat'),lng,lat);
if (dist >= 2000) {
// alert(getDistance($.cookie('lng'),$.cookie('lat'),lng,lat));
// alert($.cookie('lat')+"#####"+lat);
if(confirm('发现您到了一个新地方,要重新加载附近的优惠么?')) {
$.cookie('lat',lat);
$.cookie('lng',lng);
// window.location.reload();
history.go(0);
}
};
}
function toRad(d) { return d * Math.PI / 180; }
function getDistance(lat1, lng1, lat2, lng2) { //lat为纬度, lng为经度, 一定不要弄错
var dis = 0;
var radLat1 = toRad(lat1);
var radLat2 = toRad(lat2);
var deltaLat = radLat1 - radLat2;
var deltaLng = toRad(lng1) - toRad(lng2);
var dis = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(deltaLat / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(deltaLng / 2), 2)));
return dis * 6378137;
}
function errorHandle(error){
switch(error.code){
case error.TIMEOUT:
notice("获取地理位置信息超时!");
break;
case error.PERMISSION_DENIED:
notice("您设置了阻止该页面获取位置信息!");
break;
case error.POSITION_UNAVAILABLE:
notice("浏览器无法确定您的位置!");
break;
default:
notice("获取位置信息出错!");
break;
}
}
function notice(text) {
if (text) {
$('#notice span').text(text);
$('#notice').show();
setTimeout(function(){$('#notice').hide();}, 3000);
};
}
});
<file_sep>/core/modules/weixin/activity.php
<?php
$activityStart = false;
$numScale = 50;
$phoneNum = '';
$regIndex = 0;
if ($activityStart) {
$loader =& _G('loader');
$member = $loader->model('member:member');
$feedbackimg = $base_url.'/uploads/weixin/gesangmeiduo.jpg';
if ($user = $member->read1($userId)) {
$regIndex = $user['point6'];
$winIndex = floor($regIndex/$numScale);
$cardLeft = 35 - $winIndex;
$confirmCode = $user['mobile'];
$feedbacktitle = '成功参加活动';
$feedbackmsg = '您已成功参加活动,您的排序为:'.$regIndex;
if ($regIndex%$numScale == 0) {
$feedbacktitle = '恭喜您!';
$feedbackimg = $base_url.'/uploads/weixin/100yuanquan.jpg';
$feedbackmsg .= ',恭喜您获得【格桑梅朵100元代金券】一张,您的验证码为:'.$confirmCode.',请点击查看代金券,到店出示即可使用!';
} elseif ($cardLeft>0) {
$feedbackmsg .= ',还有【'.$cardLeft.'】张【格桑梅朵100元代金券】等你拿,赶紧邀请你的朋友来抢吧!';
} else {
$feedbacktitle = '活动已结束';
$feedbackmsg = '本次活动已经结束!请继续关注,更多惊喜在后头哦!';
}
$feedbacknews[0] = array (
'Title' => $feedbacktitle,
'Description' =>$feedbackmsg,
'PicUrl' => $feedbackimg,
'Url' => $base_url.'/article.php?act=mobile&do=detail&id=57'.$userStamp);
// $weObj->news($feedbacknews)->reply();
if ($rev_msg == $queryString) {
$weObj->news($feedbacknews)->reply();
} else {
$newsMenu[0] = $feedbacknews[0];
$weObj->news($newsMenu)->reply();
}
} else {
if ($latestRegUser = $member->readLatest()) {
$lastIndex = $latestRegUser['point6'];
// $weObj->text($lastIndex)->reply();
} else {
$lastIndex = 0;
}
$user['point6'] = $lastIndex + 1;//参与活动所获得的排序
$winIndex = floor($user['point6']/$numScale);
$cardLeft = 35 - $winIndex;
$user['point4'] = 1;//参加活动的标志
$user['point5'] = 0;//获得代金券的序号
if ($user['point6']%$numScale == 0) {
$user['mobile'] = create_password(5);
$user['mobile'] .= $winIndex;
$user['point5'] = $winIndex;
}
$user['wxid'] = $userId;
$user['groupid'] = 10;
$user['regdate'] = $_G['timestamp'];
$user['username'] = 'activity'.$user['point6'];
$user['password'] = $user['password2'] = '<PASSWORD>';
$user['email']='<EMAIL>'.$user['point6'].'<EMAIL>';
$reee = $member->save($user,null,true,false,true);
if ($cardLeft <= 0) {
$feedmacktitle = '活动已结束';
$feedbackmsg = '本次活动已经结束!请继续关注,更多惊喜在后头哦!';
} elseif ($reee) {
$feedbacktitle = '成功参加活动,点击查看结果';
$feedbackmsg = '您已成功参加活动,点击查看结果';
if ($rev_msg == $queryString) {
if ($user['mobile']) {
$feedbacktitle = '恭喜您!';
$feedbackimg = $base_url.'/uploads/weixin/100yuanquan.jpg';
$feedbackmsg = '恭喜您获得【格桑梅朵100元代金券】一张,您的验证码为:'.$user['mobile'].',请点击查看代金券,到店出示即可使用!';
} else {
$feedbackmsg = '您已成功参加活动,还有【'.$cardLeft.'】张【格桑梅朵100元代金券】等你拿,赶紧邀请你的朋友来抢吧!';
}
// $weObj->text($feedbackmsg)->reply();
}
} else {
$feedmacktitle = '参加活动失败';
$feedbackmsg = '参加活动失败!';
}
$feedbacknews[0] = array (
'Title' => $feedbacktitle,
'Description' =>$feedbackmsg,
'PicUrl' => $feedbackimg,
'Url' => $base_url.'/article.php?act=mobile&do=detail&id=57'.$userStamp);
// $weObj->text($_G['timestamp'])->reply();
if ($rev_msg == $queryString) {
$weObj->news($feedbacknews)->reply();
} else {
$newsMenu[0] = $feedbacknews[0];
$weObj->news($newsMenu)->reply();
}
}
}
function create_password($pw_length = 6) {
$randpwd = '';
for ($i = 0; $i < $pw_length; $i++)
{
$randpwd .= chr(mt_rand(97, 122));
}
return $randpwd;
}
?><file_sep>/core/modules/item/admin/templates/album_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/jquery.js"></script>
<script type="text/javascript" src="./static/javascript/item.js"></script>
<script type="text/javascript" src="./static/javascript/autocomplete/jquery.autocomplete.min.js"></script>
<link rel="Stylesheet" href="./static/javascript/autocomplete/jquery.autocomplete.css" />
<div id="body">
<form method="get" action="<?=SELF?>">
<input type="hidden" name="module" value="<?=$module?>" />
<input type="hidden" name="act" value="<?=$act?>" />
<input type="hidden" name="op" value="<?=$op?>" />
<div class="space">
<div class="subtitle">图库查询</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="50" class="altbg1">所属城市</td>
<td width="100">
<?if($admin->is_founder):?>
<select name="city_id">
<option value="">不限</option>
<?=form_city($_GET['city_id'], TRUE)?>
</select>
<?else:?>
<?=$_CITY['name']?>
<?endif;?>
</td>
<td width="50" class="altbg1">图库名称</td>
<td width="100">
<select name="city_id">
<option value="">不限</option>
</select>
</td>
<td width="50" class="altbg1">主题名称</td>
<td width="100">
<input type="text" id="sid" name="sid" class="txtbox3" />
</td>
<td width="50" class="altbg1">
<button type="submit" value="yes" name="dosubmit" class="btn2">查 询</button>
</td>
</tr>
</table>
</div>
</form>
<form method="post" name="myform" action="<?=cpurl($module,$act,'',array('pid'=>$pid))?>">
<input type="hidden" id="hsid" name="hsid" />
<div class="space">
<div class="subtitle">图库列表</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y">
<tr class="altbg1">
<td width="25">选?</td>
<td width="110">封面</td>
<td width="320">标题/说明</td>
<td width="*">所属主题</td>
<td width="50" align="center">图片数</td>
<td width="110">最后更新</td>
<td width="80">操作</td>
</tr>
<?if($total):?>
<?while($val=$list->fetch_array()):?>
<tr>
<td><input type="checkbox" name="albumids[]" value="<?=$val['albumid']?>" /></td>
<td class="picthumb"><img src="<?=$val['thumb']?$val['thumb']:'./static/images/noimg.gif'?>" /></td>
<td>
<div>标题:<br /><input type="text" class="txtbox2" name="album[<?=$val['albumid']?>][name]" value="<?=$val['name']?>" /></div>
<div>说明:<br /><input type="text" class="txtbox2" name="album[<?=$val['albumid']?>][des]" value="<?=$val['des']?>" /></div>
</td>
<td><span class="font_2">[<?=display('modoer:area',"aid/$val[city_id]")?>]</span><a href="<?=url("item/detail/id/$val[sid]")?>" target="_blank"><?=$val['subjectname'].($val['subname']?"($val[subname])":'')?></a></td>
<td align="center"><?=$val['num']?></td>
<td><?=date('Y-m-d H:i', $val['lastupdate'])?></td>
<td><a href="<?=cpurl($module,'picture_list','list',array('albumid'=>$val['albumid'],'dosubmit'=>'yes'))?>">管理图片</a></td>
</tr>
<?endwhile;?>
<tr class="altbg1">
<td colspan="2"><button type="button" onclick="checkbox_checked('picids[]');" class="btn2">全选</button></td>
<td colspan="4" style="text-align:right;"><?=$multipage?></td>
</tr>
<?else:?>
<tr>
<td colspan="6">暂无信息。</td>
</tr>
<?endif;?>
</table>
</div>
<?if($total):?>
<div class="multipage"><?=$multipage?></div>
<center>
<input type="hidden" name="dosubmit" value="yes" />
<input type="hidden" name="op" value="checkup" />
<button type="button" class="btn" onclick="easy_submit('myform','update',null)">更新修改</button>
<button type="button" class="btn" onclick="easy_submit('myform','delete','albumids[]')">删除所选</button>
</center>
<?endif;?>
</form>
</div>
<script type="text/javascript">
var url="index.php?m=item&act=ajax&do=subject&op=search1";
//var url="index.php?m=item&act=ajax&do=test";
$().ready(function() {
$("#sid").autocomplete(url, {
max: 12,
minChars: 1,
width: 400,
scrollHeight: 300,
matchContains: true,
autoFill: false,
formatItem: function(row, i, max, value) {
return value.split('-')[1];
},
formatResult: function(row, value) {
return value.split('-')[1];
}
});
$("#sname").result(function(event, data, formatted) {
$("#hsid").val(data[0].split('-')[0] );
});
});
</script><file_sep>/templates/item/sjstyle/video.php
<?exit?>
<!--{eval
$_HEAD['title'] = $detail[name] . $detail[subname] . 的视频展播;
}-->
{template vip2_header}
<script type="text/javascript">
loadscript('swfobject');
$(document).ready(function() {
if(!$.browser.msie && !$.browser.safari) {
var d = $("#thumb");
var dh = parseInt(d.css("height").replace("px",''));
var ih = parseInt(d.find("img").css("height").replace("px",''));
if(dh - ih < 3) return;
var top = Math.ceil((dh - ih) / 2);
d.find("img").css("margin-top",top+"px");
}
<!--{if $MOD['show_thumb'] && $detail['pictures']}-->
get_pictures($sid);
<!--{/if}-->
get_membereffect($sid, $modelid);
});
</script>
<link href="{URLROOT}/img/shop/$detail[c_sjstyle]/style.css" rel="stylesheet" type="text/css" />
<!--头开始-->
<div class="header">
<div class="headerinfo">$detail[name] $detail[subname]</div>
<div class="headermeun">
<ul>
<li><div><a href="{url item/detail/id/$detail[sid]}">首页</a> </div></li>
<li><div><a href="{url item/vipabout/id/$detail[sid]}">店铺介绍</a> </div></li>
<li><div><a href="{url article/list/sid/$sid}">店铺动态</a> </div></li>
<li><div><a href="{url item/pic/sid/$detail[sid]}">店铺展示</a> </div></li>
<li><div><a href="{url product/list/sid/$sid}">产品展厅</a> </div></li>
<li><div><a href="{url coupon/list/sid/$sid}">优惠打折</a> </div></li>
<li class="in"><div><a href="{url item/vipvideo/id/$detail[sid]}">视频展播</a> </div></li>
<li><div><a href="{url item/vipcontact/id/$detail[sid]}">联系方式</a> </div></li>
</ul>
</div>
</div>
<!--头结束-->
<!--头部flash-->
<!--{if $detail[c_pictop1]}-->
<div style="margin:0 auto; width:976px;">
<SCRIPT src="{URLROOT}/img/shop/js/swfobject_source.js" type=text/javascript></SCRIPT>
<DIV id=flashFCI><A href="#" arget=_blank><IMG alt="" border=0></A></DIV>
<SCRIPT type=text/javascript>
var s1 = new SWFObject("{URLROOT}/img/shop/js/focusFlash_fp.swf", "mymovie1", "976", "150", "5", "#ffffff");
s1.addParam("wmode", "transparent");
s1.addParam("AllowscriptAccess", "sameDomain");
s1.addVariable("bigSrc", "$detail[c_pictop1]{if $detail[c_pictop2]}|$detail[c_pictop2]{/if}{if $detail[c_pictop3]}|$detail[c_pictop3]{/if}");
s1.addVariable("smallSrc", "|$detail[c_pictop1]|||");
s1.addVariable("href", "||");
s1.addVariable("txt", "||");
s1.addVariable("width", "976");
s1.addVariable("height", "150");
s1.write("flashFCI");
</SCRIPT>
</div>
<!--{/if}-->
<!--end头部flash-->
<div class="content">
<div class="pagejc">
<div class="col1">
<div class="titles">
<div class="fl">基本信息</div>
<div class="fr"></div>
<div class="clear"></div>
</div>
<div class="neirongs" style="padding:10px;">
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td valign="top">
<a href="{url item/pic/sid/$detail[sid]}"><img src="{URLROOT}/{if $detail[thumb]}$detail[thumb]{else}static/images/noimg.gif{/if}" alt="$detail[name]" width="110" height="80" /></a>
</td>
<td valign="top">
<!--{loop $reviewpot $val}-->$val[name]:<img src="{URLROOT}/img/shop/eshop/z{print cfloat($detail[$val[flag]])}.gif" alt="{print cfloat($detail[$val[flag]])} 分" /><br /><!--{/loop}-->
综合:<img src="{URLROOT}/img/shop/eshop/z{print cfloat($detail[avgsort])}.gif" alt="{print cfloat($detail[avgsort])} 分" />
</td>
</tr>
</table>
<div class="lefttitle">$detail[name]</div>
<div class="leftnr">
管 理 者:
<!--{if $detail[owner]}-->
<a href="{url space/index/username/$detail[owner]}" target="_blank">$detail[owner]</a>
<!--{elseif $catcfg[subject_apply]}-->
<a href="{url item/member/ac/subject_apply/sid/$detail[sid]}"><font color="#cc0000"><b>认领$model[item_name]</b></font></a>
<!--{/if}-->
<!--{if $catcfg[use_subbranch]}-->
<a href="{url item/member/ac/subject_add/subbranch_sid/$detail[sid]}">添加分店</a>
<!--{/if}--><br />
<!--{if $detail[finer]}-->
店铺级别:<img src="{URLROOT}/img/shop/eshop/vip$detail[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<table class="custom_field" border="0" cellspacing="0" cellpadding="0">
$detail_custom_field
</table>
</div>
</div>
<div class="mq"></div>
</div> <!--col1end-->
<div class="col2">
<div class="titleb"><div class="fl">视频展播</div></div>
<div class="neirongb">
<div style="display:none;" id="thumb"><a href=""><img src="" /></a></div>
<!--{if $detail[video]}-->
<div class="mainrail" style="text-align:center;" id="video_foo"></div>
<script type="text/javascript">
$(document).ready(function() {
var so = new SWFObject("$detail[video]", 'video1', 500, 499, 7, '#FFF');
so.addParam("allowScriptAccess", "always");
so.addParam("allowFullScreen", "true");
so.addParam("wmode", "transparent");
so.write("video_foo");
});
</script>
<!--{/if}-->
</div>
</div><!--col2-->
<div class="clear"></div>
</div><!--pagejc-->
</div><!--content-->
</div><!--wrapper-->
{template vip2_footer}
<file_sep>/core/modules/tuan/model/crule/fanwei.php
<?php
/*
* meituan rule
*
*/
$rule='response-goods=subject:
limengqikey-title,cityname:
limengqikey-cityname,url:
limengqikey-url,nowprice:
limengqikey-groupprice,oldprice:
limengqikey-marketprice,lasttime:
limengqikey-endtime,thumb:
limengqikey-bigimg,nowpeople:
limengqikey-buycount,starttime:
limengqikey-begintime';
?><file_sep>/core/modules/tuan/pay_notify.php
<?php
/**
* 在线支付成功后,系统会执行当前文件,根据orderid获取订单状态,完成订单提交
*
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
$oid = _input('oid', null, MF_INT_KEY);
$O =& $_G['loader']->model('tuan:order');
$O->pay_online_succeed($oid);
echo 'succeed';
exit;<file_sep>/core/modules/tuan/assistant/wish.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
$tw =& $_G['loader']->model('tuan:wish');
$op = _input('op',null, MF_TEXT);
switch($op) {
case 'interest':
$twid = _input('twid',null,MF_INT_KEY);
$tw->interest($twid);
echo 'OK';
output();
break;
case 'undertake':
$twid = _input('twid',null,MF_INT_KEY);
$tu =& $_G['loader']->model('tuan:undertake');
if($tu->exists($twid)) redirect('tuan_undertake_exists');
if(!$wish = $tw->read($twid)) redirect('tuan_wish_empty');
$tplname = 'wish_undertake';
break;
case 'undertake_post':
$tu =& $_G['loader']->model('tuan:undertake');
$twid = _input('twid',null,MF_INT_KEY);
$post = $tu->get_post($_POST);
$id = $tu->save($post);
redirect('tuan_undertake_succeed', url('tuan/index'));
break;
default:
//权限验证
$user->check_access('tuan_post_wish', $tw);
if(check_submit('dosubmit')) {
$post = $tw->get_post($_POST);
$tw->save($post);
redirect('tuan_wish_create_succeed_check', url('tuan/index'));
} else {
$tplname = 'wish_save';
}
}
?><file_sep>/img/vipfiles/js/shopajax.js
var lastmsgid;
function ajax_reply(id)
{
$('#messageRe'+id).html('<table id="writeMessage" width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td><textarea name="reply" id="reply" cols="60" rows="6"></textarea><tr><td><input id="replyid" type="hidden" name="replyid" value='+id+' /><input class="commBtn" id="btnStyle2" type="button" name="btnStyle2" value="提 交" onclick="replysubmit();" /></td></tr></table>');
if(lastmsgid)
{
$('#messageRe'+lastmsgid).html('');
}
if(lastmsgid == id)
{
lastmsgid = '';
}else
{
lastmsgid = id;
}
}
function replysubmit(id)
{
if($('#reply').val() == "")
{
alert("回应不能为空!");
return false;
}else
{
$.ajax({
type: "POST",
url: "index.php",
data: "action=comment&opt=replysubmit&reply="+$('#reply').val()+"&replyid="+$('#replyid').val()+"&type="+$('#type').val()+"&updateid="+id,
success: function(msg)
{
$('#leaveword').html(msg);
}
});
}
}<file_sep>/core/modules/tuan/model/tuan_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_tuan extends ms_model {
var $table = 'dbpre_tuan';
var $key = 'tid';
var $model_flag = 'tuan';
var $modes = array('normal','average','wholesale','forestall');
function __construct() {
parent::__construct();
$this->model_flag = 'tuan';
$this->init_field();
$this->modcfg = $this->variable('config');
}
function msm_tuan() {
$this->__construct();
}
function init_field() {
$this->add_field('catid,city_id,sid,subject,price,market_price,sendtype,goods_total,goods_min,people_buylimit,peoples_min,starttime,endtime,expiretime,intro,content,notice,status,coupon_print,sms,checked,uid,username,mode,prices,total_price,use_ex_point,use_ex_price');
$this->add_field_fun('subject,sms,sendtype', '_T');
$this->add_field_fun('catid,city_id,sid,goods_total,goods_min,people_buylimit,peoples_min,checked,use_ex_point', 'intval');
$this->add_field_fun('intro,content', '_HTML');
$this->add_field_fun('use_ex_price', 'floatval');
}
function find($select="*", $where=null, $orderby=null, $start=0, $offset=10, $total=FALSE) {
$this->db->from($this->table);
$where && $this->db->where($where);
$result = array(0,'');
if($total) {
if(!$result[0] = $this->db->count()) {
return $result;
}
$this->db->sql_roll_back('from,where');
}
$this->db->select($select?$select:'*');
if($orderby) $this->db->order_by($orderby);
if($start < 0) {
if(!$result[0]) {
$start = 0;
} else {
$start = (ceil($result[0]/$offset) - abs($start)) * $offset; //按 负数页数 换算读取位置
}
}
$this->db->limit($start, $offset);
$result[1] = $this->db->get();
return $result;
}
//首页的今日团购
function getone($city_id=null) {
$start = strtotime(date('Y-m-d', $this->global['timestamp']));
$endtime = strtotime(date('Y-m-d', $this->global['timestamp']));
$this->db->from($this->table);
$this->db->where_less('starttime', $start);
$this->db->where_more('endtime', $endtime);
$this->db->where('status', 'new');
$this->db->where('checked', '1');
if($city_id) $this->db->where('city_id', explode(',',$city_id));
$this->db->order_by(array('listorder'=>'ASC'));
$this->db->limit(0,1);
$result = $this->db->get_one();
return $result;
}
//往期团购
function deals($where = array(), $offset = 24) {
$this->db->select('tid,catid,sid,subject,mode,thumb,price,prices,total_price,market_price,real_price,goods_total,goods_sell,goods_min,people_buylimit,peoples_sell,peoples_min,starttime,endtime,succeedtime,expiretime,status');
$this->db->from($this->table);
$this->db->where('status', 'succeeded');
$this->db->where('city_id', array(0,$this->global['city']['aid']));
$this->db->where('checked', '1');
if($where) $this->db->where($where);
$result = array(0,'','');
if($result[0] = $this->db->count()) {
$this->db->sql_roll_back('from,where');
$this->db->select('tid,catid,city_id,sid,mode,subject,picture,thumb,price,prices,total_price,market_price,real_price,goods_total,goods_sell,goods_min,people_buylimit,peoples_sell,peoples_min,starttime,endtime,succeedtime,expiretime,status');
$this->db->order_by('listorder');
$this->db->limit(get_start($_GET['page'],$offset), $offset);
$result[1] = $this->db->get();
$result[2] = multi($result[0], $offset, $_GET['page'], url("tuan/deals/page/_PAGE_"));
}
return $result;
}
//团购列表
function getlist($catid, $mode, $start, $offset) {
$this->db->from($this->table);
if($mode!='all') $this->db->where('mode', $mode);
if($catid>0) $this->db->where('catid', $catid);
$this->db->where('status', 'new');
$this->db->where('city_id', array(0,$this->global['city']['aid']));
$this->db->where('checked', '1');
$result = array(0, '');
if($result[0] = $this->db->count()) {
$this->db->sql_roll_back('from,where');
$this->db->select('tid,city_id,catid,sid,mode,subject,thumb,picture,price,prices,total_price,market_price,goods_total,goods_sell,goods_min,people_buylimit,peoples_sell,peoples_min,starttime,endtime,succeedtime,expiretime,status,intro');
$this->db->order_by('listorder');
$this->db->limit($start, $offset);
$result[1] = $this->db->get();
}
return $result;
}
//给api接口的数据
function getlist_api() {
$this->db->from($this->table);
$this->db->where('status', 'new');
$this->db->where('checked', '1');
$result = array(0, '');
if($result[0] = $this->db->count()) {
$this->db->sql_roll_back('from,where');
$this->db->select('*');
$this->db->order_by('listorder');
$this->db->limit($start, $offset);
$result[1] = $this->db->get();
}
return $result;
}
//我的团
function mylist($uid, $return_tids = false, $is_sids=false) {
if($is_sids) {
$subjects = $uid;
} else {
$S =& $this->loader->model('item:subject');
$subjects = $S->mysubject($uid);
}
if(!$subjects) return;
$this->db->from($this->table);
$this->db->where_in('sid', $subjects);
$this->db->select('tid,city_id,mode,subject,picture,thumb,price,goods_total,goods_sell,goods_min,people_buylimit,peoples_sell,peoples_min,starttime,endtime,status');
if(!$q = $this->db->get()) return;
if($return_tids) {
$list = array();
while($v=$q->fetch_array()) {
$list[] = $v['tid'];
}
$q->free_result();
return $list;
}
return $q;
}
//新建团购
function save($post, $tid = NULL) {
$edit = $tid != null;
if($edit) {
if(!$detail = $this->read($tid)) redirect('tuan_empty');
$post['goods_stock'] = $post['goods_total'] - $detail['goods_sell'];
} else {
$post['status'] = 'new';
if(!$this->in_admin) {
$post['checked'] = 0;
$post['uid'] = $this->global['user']->uid;
$post['username'] = $this->global['user']->username;
}
$post['goods_stock'] = $post['goods_total'];
}
//上传图片部分
if($_FILES['picture']['name']) {
$this->loader->lib('upload_image', NULL, FALSE);
$img = new ms_upload_image('picture', $this->global['cfg']['picture_ext']);
$this->upload_thumb($img);
$post['picture'] = str_replace(DS, '/', $img->path . '/' . $img->filename);
$post['thumb'] = str_replace(DS, '/', $img->path . '/' . $img->thumb_filenames['thumb']['filename']);
unset($img);
}
//时间转换
$post['starttime'] && $post['starttime'] = strtotime($post['starttime']);
$post['endtime'] && $post['endtime'] = strtotime($post['endtime']) + (24 * 3600 - 1);
$post['expiretime'] && $post['expiretime'] = strtotime($post['expiretime']);
if(!empty($post['coupon_print'])) $post['coupon_print'] = @serialize($post['coupon_print']);
if($edit && isset($post['endtime']) && $post['endtime']>=$this->global['timestamp']) {
$post['status'] = 'new';
}
$tid = parent::save($post, $edit?$detail:$tid);
if($this->in_admin && $edit) {
//批量更新团购券到期时间
if(_post('update_expiretime')=='1' && $post['expiretime'] != $detail['expiretime']) {
$C =& $this->loader->model('tuan:coupon');
$C->update_expiretime($tid, $post['expiretime']);
}
//批量更新未付款订单的过期时间
if( $post['endtime'] != $detail['endtime']) {
if(_post('update_endtime')=='1') {
$O =& $this->loader->model('tuan:order');
$O->update_overdue($tid, $post['endtime']);
}
}
//检查编辑过后是否成团
if($this->check_succeed($tid) && $post['sendtype']=='coupon') {
$C =& $this->loader->model('tuan:coupon');
$C->create($detail['tid']);
}
/*
if($detail['now_num']>0 && !$detail['succeedtime'] && $this->check_succeed($tid) && $post['sendtype']=='coupon') {
$C =& $this->loader->model('tuan:coupon');
$C->create($detail['tid']);
}
*/
}
return $tid;
}
//审核商家发布团购
function checkup($tids) {
}
//删除
function delete($tids) {
$ids = parent::get_keyids($tids);
//删除其他关联表
$C =& $this->loader->model('tuan:coupon');
$C->delete_tids($ids);
$O =& $this->loader->model('tuan:order');
$O->delete_tids($ids);
//删除团购
parent::delete($ids);
}
//更新
function update($post) {
if(!$post) return;
foreach($post as $tid => $val) {
$this->db->from($this->table);
$this->db->where('tid',$tid);
$this->db->set($val);
$this->db->update();
}
}
//提交检测
function check_post(& $post, $edit = false) {
$this->loader->helper('validate');
if(!in_array($post['mode'], $this->modes)) redirect('tuan_post_mode_unkown');
if(!is_numeric($post['city_id']) || $post['city_id']<0) redirect('tuan_post_city_empty');
if(!$post['subject']) redirect('tuan_post_subject_empty');
if(!$this->in_admin && !$post['sid']) redirect('tuan_post_sid_empty');
if(!$post['starttime']) redirect('tuan_post_starttime_invalid');
if(!$post['endtime']) redirect('tuan_post_endtime_invalid');
if(!$post['content']) redirect('tuan_post_content_empty');
if(!$edit && !$post['picture']) redirect('tuan_post_picture_empty');
if($post['sendtype']=='coupon' && !$post['expiretime']) redirect('tuan_post_expiretime_empty');
//goods_total,goods_sell,goods_min,people_buylimit,peoples_sell,peoples_min
if($post['use_ex_point']) {
if(!$this->modcfg['ex_pointtype']||!$this->modcfg['ex_rate']) redirect('tuan_post_exchange_invalid');
if(!$post['use_ex_price']||$post['use_ex_price']<=0) redirect('tuan_post_use_ex_price_empty');
} else
if(!$post['use_ex_point']) $post['use_ex_price'] = 0;
switch($post['mode']) {
case 'normal':
if(!validate::is_numeric($post['people_buylimit'])) redirect('tuan_post_people_buylimit_empty');
if(!validate::is_numeric($post['peoples_min'])) redirect('tuan_post_peoples_min_empty');
$post['goods_min'] = 0;
break;
case 'average':
if(!validate::is_numeric($post['peoples_min'])) redirect('tuan_post_peoples_min_empty');
if(!validate::is_numeric($post['total_price'])) redirect('tuan_post_total_price_empty');
$post['price'] = round($post['total_price'] / $post['peoples_min'], 2); //最高的支付价格
$post['people_buylimit'] = 1;
$post['goods_min'] = 0;
$post['market_price'] = $post['total_price'];
break;
case 'wholesale':
if(!validate::is_numeric($post['people_buylimit'])) redirect('tuan_post_people_buylimit_empty');
if(!$post['prices']) redirect('tuan_post_prices_empty');
$post['peoples_min'] = 0;
$prices = $this->parse_prices($post['prices'], true);
foreach($prices as $num => $price) {
$post['price'] = $price;
$post['goods_min'] = $num; //成团购买数量
break;
}
break;
case 'forestall':
if(!validate::is_numeric($post['people_buylimit'])) redirect('tuan_post_people_buylimit_empty');
if(!validate::is_numeric($post['price'])) redirect('tuan_post_price_empty');
if(!$post['prices']) redirect('tuan_post_prices_empty');
$prices = $this->forestall_parse_prices($post['prices'], true);
$post['goods_min'] = 0;
break;
default:
redirect('tuan_post_mode_unkown');
}
if(!validate::is_numeric($post['goods_total'])) redirect('tuan_post_goods_total_empty');
if(!validate::is_numeric($post['market_price'])) redirect('tuan_post_market_price_empty');
if(!$this->in_admin && !$this->check_post_access($post['sid'],$this->global['user']->uid)) {
redirect('global_op_access');
}
return $post;
}
//状态更新
function update_status($tid = null, $status = 'new') {
}
//计划检测更新状态
function plan_status($tid=null) {
$endtime = strtotime(date('Y-m-d', $this->global['timestamp']))-1;
$this->db->from($this->table,'', !$tid ? 'FORCE INDEX(plan)' : '');
$this->db->select('tid,goods_total,goods_sell,goods_min,people_buylimit,peoples_sell,peoples_min,succeedtime,endtime');
if($tid > 0) {
$this->db->where('tid', $tid);
$this->db->where('status', 'new');
}
if(!$tid) {
$this->db->where_less('endtime', $endtime);
$this->db->where('status', 'new');
$this->db->where('city_id', array(0,$this->global['city']['aid']));
}
if(!$q = $this->db->get()) return;
$uptids = $succeeded = array();
while($v = $q->fetch_array()) {
//时间到或者销售光了,就结束团购
if($v['endtime']<=$endtime||$v['goods_total']<=$v['goods_sell']) {
$uptids[] = $v['tid'];
if($v['succeedtime'] > 0) $succeeded[] = $v['tid'];
}
}
$q->free_result();
if($uptids) {
$up_price_tids = array();
foreach($uptids as $tid) {
$succeed = in_array($tid, $succeeded);
$this->db->from($this->table);
$this->db->set('status', $succeed ? 'succeeded' : 'lose');
if($v['endtime'] > $endtime) $this->db->set('endtime',$this->global['timestamp']);
$this->db->where('tid', $tid);
$this->db->update();
if($succeed) $up_price_tids[] = $tid;
}
if($up_price_tids) {
$this->_update_real_price($up_price_tids);
}
}
}
//上传图片
function upload_thumb(& $img) {
$thumb_w = $this->modcfg['thumb_width'] ? $this->modcfg['thumb_width'] : 200;
$thumb_h = $this->modcfg['thumb_height'] ? $this->modcfg['thumb_height'] : 121;
$img->set_max_size($this->global['cfg']['picture_upload_size']);
$img->userWatermark = $this->modcfg['watermark'];
$img->watermark_postion = $this->global['cfg']['watermark_postion'];
$img->thumb_mod = $this->global['cfg']['picture_createthumb_mod'];
//$img->limit_ext = array('jpg','png','gif');
$img->set_ext($this->global['cfg']['picture_ext']);
$img->set_thumb_level($this->global['cfg']['picture_createthumb_level']);
$img->add_thumb('thumb', 's_', $thumb_w, $thumb_h);
$img->upload('tuan');
}
//更新销售统计
function update_total($tid, $people_num, $goods_num) {
$this->db->from($this->table);
$this->db->set_dec('goods_stock', $goods_num);
$this->db->set_add('goods_sell', (int)$goods_num);
$this->db->set_add('peoples_sell', (int)$people_num);
$this->db->where('tid', $tid);
$this->db->update();
}
//退款后更新表的销售数量
function refund($tid, $people_num, $goods_num) {
$this->db->from($this->table);
$this->db->set_add('goods_stock', $goods_num);
$this->db->set_dec('goods_sell', (int) $goods_num);
$this->db->set_dec('peoples_sell', (int) $people_num);
$this->db->where('tid', $tid);
$this->db->update();
}
//还原团购表数据
function restore($tid) {
if(!$detail = $this->read($tid)) return;
$this->db->from($this->table);
$this->db->set('goods_sell',0);
$this->db->set('peoples_sell',0);
$this->db->set('goods_stock',$detail['goods_total']);
$this->db->where('tid',$tid);
$this->db->update();
}
//是否成功检测,并更新成功团购时间
function check_succeed($detail) {
if(!is_array($detail)) {
$tid = (int) $detail;
if(!$detail = $this->read($tid)) return FALSE;
}
$succed = false;
if($detail['mode']=='wholesale') { //按产品成团
$succed = $detail['goods_sell'] >= $detail['goods_min'];
} else { //按人数成团
$succed = $detail['peoples_sell'] >= $detail['peoples_min'];
}
if($succed) {
!$detail['succeedtime'] && $this->_update_succeed_time($detail['tid']);
return TRUE;
} else {
return FALSE;
}
}
//判断2种角色的提交权限
function check_post_access($sid,$uid) {
if($this->in_admin) return TRUE;
!$sid && redirect('article_post_sid_empty');
$S=&$this->loader->model('item:subject');
return $S->is_mysubject($sid, $uid);
return false;
}
//取得未审核数量
function get_check_count($sid=null) {
$this->db->from($this->table);
$this->db->where('checked',0);
if($sid) $this->db->where('sid',$sid);
return $this->db->count();
}
//获取并解析多价格格式
function parse_prices($prices,$show_error=true) {
$prices = trim($prices);
$ps = explode(',', $prices);
if(empty($ps)) {
$show_error && redirect('tuan_parse_prices_format');
return false;
}
$_m = 1;
$_p = 0;
$result = array();
foreach($ps as $k=>$val) {
list($m,$p) = explode('=', $val);
if(!is_numeric($m)||!is_numeric($p)) {
$show_error && redirect('tuan_parse_prices_invalid');
return false;
}
if(isset($result[$m])) {
$show_error && redirect('tuan_parse_prices_price_invalid');
return false;
}
if($_m >= $m) {
$show_error && redirect(lang('tuan_parse_prices_group_num_invalid',array($k+1, $m, $_m)));
return false;
}
if($k > 0 && $p >= $_p) {
$show_error && redirect(lang('tuan_parse_prices_group_price_invalid',array($k+1,$p,$_p)));
return false;
}
$_m = $m + 1;
$_p = $p;
$result[$m] = $p;
}
return $result;
}
//获取并解析多价格格式
function forestall_parse_prices($prices,$show_error=true) {
$prices = trim($prices);
$ps = explode(',', $prices);
if(empty($ps)) {
$show_error && redirect('tuan_parse_prices_format');
return false;
}
$_m = 1;
$_p = 0;
$result = array();
foreach($ps as $k=>$val) {
list($m,$p) = explode('=', $val);
if(!is_numeric($m)||!is_numeric($p)) {
$show_error && redirect('tuan_parse_prices_invalid');
return false;
}
if(isset($result[$m])) {
$show_error && redirect('tuan_parse_prices_price_invalid');
return false;
}
if($_m > $m) {
$show_error && redirect(lang('tuan_parse_prices_group_people_invalid',array($k+1, $m, $_m)));
return false;
}
if($k > 0 && $p <= $_p) {
$show_error && redirect(lang('tuan_parse_prices_group_people_price_invalid',array($k+1,$p,$_p)));
return false;
}
$_m = $m + 1;
$_p = $p;
$result[$m] = $p;
}
if($result) ksort($result);
return $result;
}
//计算出最终价格
function average_price($total_price,$peoples_sell) {
return round($total_price / $peoples_sell, 2);
}
//计算出最终价格
function wholesale_price($prices,$goods_sell) {
$real_price = 0;
$prices = $this->parse_prices($prices);
foreach($prices as $num => $price) {
//找到对应批发的价格
if($num >= $goods_sell) $real_price = $price;
}
return $real_price;
}
//更新团购的正式价格
function _update_real_price($tids) {
$this->db->from($this->table);
$this->db->select('tid,price,mode,prices,total_price,goods_total,goods_sell,goods_min,people_buylimit,peoples_sell,peoples_min');
$this->db->where('tid', $tids);
$this->db->where('status',succeeded);
if(!$q = $this->db->get()) return;
while($v = $q->fetch_array()) {
$real_price = $v['price'];
if($v['mode'] == 'average') {
$real_price = $this->average_price($v['total_price'], $v['peoples_sell']);
} elseif($v['mode'] == 'wholesale') {
$real_price = $this->wholesale_price($v['prices'], $v['goods_sell']);
} elseif($v['mode'] == 'forestall') {
$real_price = $price['price'];
}
if($real_price != $v['price']) {
$this->db->from($this->table);
$this->db->set('real_price', $real_price);
$this->db->where('tid',$v['tid']);
$this->db->update();
}
}
}
//更新实际价格
function _update_order_real_price($tid,$price) {
$this->db->from($this->table);
$this->db->where('tid', $tid);
$this->db->set('real_price', $price);
$this->db->update();
//更新订单
$O =& $this->loader('tuan:order');
$O->update_real_price($tid, $price);
}
//更新成功团购时间
function _update_succeed_time($tid) {
$this->db->from($this->table);
$this->db->set('succeedtime', $this->global['timestamp']);
$this->db->where('tid', $tid);
$this->db->update();
}
}
?><file_sep>/templates/item/vip/coupon_list.php
<?exit?>
<!--{eval
$_HEAD['title'] = ($subject ? ($subject[name] . ',' . $subject[subname] . ',') : '') . (isset($catid)?$category[$catid][name]:'') . $MOD[name] . $_CFG['titlesplit'] . $MOD[subtitle];
}-->
<!--{template 'header', 'item', $subject[templateid]}-->
<link href="{URLROOT}/img/vipfiles/css/shopEx_$subject[c_vipstyle].css" rel="stylesheet" type="text/css" />
<body>
<div class="wrap">
<div id="header">
<div id="crumb">
<p id="crumbL"><a href="{url modoer/index}">{lang global_index}</a> » {print implode(' » ', $urlpath)} » $subject[name] $subject[subname]
<p id="crumbR"><a href="javascript:post_log($subjectl[sid]);">补充信息</a> | <a href="{url item/member/ac/subject_add/subbranch_sid/$subject[sid]}">增加分店</a> | <a href="{url member/index}">管理本店</a></p>
</div>
<div id="shopBanner">
<h1>$subject[name] $subject[subname]</h1>
<p>
<!--{if $subject[c_add]}-->
<B>地址:</B></LABEL>$subject[c_add]
<!--{/if}-->
<!--{if $subject[c_tel]}-->
<B>电话:</B></LABEL>$subject[c_tel]</p>
<!--{/if}-->
<div class="headerPic">
<img src="{if $subject[c_vipbanner]}$subject[c_vipbanner]{else}{URLROOT}img/haibao/nonbanner.png{/if}" alt="$subject[name] $subject[subname]店铺海报" width="950" height="150"/>
</div>
</div>
<div id="nav">
<ul>
<!--
<li><a href="#"><span>Array</span></a></li>
<li><a href="#"><span></span></a></li>
<li class="special"><a href="#"><span>导航栏介绍</span></a></li>
-->
<li><a href="{url item/detail/id/$subject[sid]}"><span>首页</span></a></li>
<li><a href="{url article/list/sid/$sid}"><span>店铺资讯</span></a></li>
<li><a href="{url fenlei/list/sid/$sid}"><span>诚聘英才</span></a> </li>
<li><a href="{url product/list/sid/$sid}"><span>产品展厅</span></a></li>
<li class="current" ><a href="{url coupon/list/sid/$sid}"><span>优惠打折</span></a></li>
<li><a href="{url item/pic/sid/$subject[sid]}"><span>商家相册</span></a></li>
<li><a href="{url item/vipabout/id/$subject[sid]}"><span>关于我们</span></a></li>
<li><a href="{url item/vipreview/id/$subject[sid]}"><span>会员点评</span></a></li>
<li><a href="{url item/vipguestbook/id/$subject[sid]}"><span>留言板</span></a></li>
</ul>
</div>
</div>
<div id="smartAd"><img src="{if $subject[c_vipbanner2]}$subject[c_vipbanner2]{else}{URLROOT}img/haibao/non.png{/if}" alt="$subject[name] $subject[subname]店铺海报"/></a><br />
</div>
<div id="mainBody">
<div id="mainBodyL">
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>【$subject[name] $subject[subname]】</h2>
<p class="deafBoxTitMore"><a href="{url item/vipabout/id/$subject[sid]}">更多</a></p>
</div>
<div class="deafBoxCon">
<dl>
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td align="center" valign="middle">
<a href="{url item/pic/sid/$subject[sid]}"><img src="{URLROOT}/{if $subject[thumb]}$subject[thumb]{else}static/images/noimg.gif{/if}" alt="$subject[name]" width="270" height="200" /></a>
</td>
</tr>
</table>
<div class="leftnr">
<!--{if $subject[finer]}-->
店铺级别:<img src="{URLROOT}/img/vipfiles/img/vip$subject[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<div class="subject">
<h2><a href="{url item/detail/id/$sid}" src="$subject[thumb]" onMouseOver="tip_start(this,1);">$subject[name] $subject[subname]</a></h2>
<!--{eval $reviewcfg = $_G['loader']->variable('config','review');}-->
<p class="start start{print get_star($subject[avgsort],$reviewcfg[scoretype])}"></p>
<table class="subject_field_list" border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2"><span class="font_2">$subject[reviews]</span>点评,
<span class="font_2">$subject[guestbooks]</span>留言,
<span class="font_2">$subject[pageviews]</span>浏览</td>
</tr>
$subject_field_table_tr
</table>
<a class="abtn1" href="{url review/member/ac/add/type/item_subject/id/$subject[sid]}"><span>我要点评</span></a>
<a class="abtn2" href="javascript:add_favorite($sid);"><span>收藏</span></a>
<a class="abtn2" href="{url item/detail/id/$sid/view/guestbook}#guestbook"><span>留言</span></a>
<div class="clear"></div>
</dl>
</div>
</div>
<div id="position" class="deafBox">
<div class="deafBoxTit">
<h2>商户所在位置</h2>
</div>
<div class="deafBoxCon">
<!--{eval $model=$I->get_model($subject[catid],1);}-->
<!--{if $model[usearea]}-->
<div class="mainrail">
<!--{eval $mapparam = array(
'width' => '270',
'height' => '265',
'title' => $subject[name] . $subject[subname],
'p' => $subject[mappoint],
'show' => $subject[mappoint]?1:0,
);}-->
<iframe src="{URLROOT}/index.php?act=map&{print url_implode($mapparam)}" frameborder="0" scrolling="no" height="265" width="270"></iframe>
<div style="text-align:center;margin:5px 0;">
<!--{if !$subject['mappoint']}-->
<a href="javascript:post_map($subject[sid], $subject[pid]);">地图未标注,我来标注</a>
<!--{else}-->
<a href="javascript:show_bigmap();">查看大图</a>
<a href="javascript:post_map($subject[sid], $subject[pid]);">报错</a>
<!--{/if}-->
</div>
</div>
<script type="text/javascript">
function show_bigmap() {
<!--{eval $mapparam = array(
'width' => '600',
'height' => '400',
'title' => $subject[name] . $subject[subname],
'p' => $subject[mappoint],
'show' => $subject[mappoint]?1:0,
);}-->
var src = "{URLROOT}/index.php?act=map&{print url_implode($mapparam)}";
var html = '<iframe src="' + src + '" frameborder="0" scrolling="no" width="100%" height="400" id="ifupmap_map"></iframe>';
dlgOpen('查看大图', html, 600, 450);
}
</script>
<!--{/if}-->
</div>
</div>
</div>
<div id="chaBodyR">
<div id="chaBodyRTit">
<h2>优惠券信息</h2>
</div>
<div class="listCon">
<div style="border:1px solid #ddd;margin-top:10px; margin-bottom:10px;">
<div class="c_category2">
<ul >
<li><b>分类:</b></li>
{get:coupon val=category()}
<li$active[catid][$val[catid]]><a href="{url coupon/list/sid/$sid/catid/$val[catid]}">$val[name]</a></li>
{/get}
</ul>
<div class="clear" style="border-bottom:1px dashed #ccc; "></div>
<ul>
<li><b>排序:</b></li>
<li$active[order][dateline]><a href="{url coupon/list/sid/$sid/catid/$catid/order/dateline}">最新发布</a></li>
<li$active[order][pageview]><a href="{url coupon/list/sid/$sid/catid/$catid/order/pageview}">浏览量</a></li>
<li$active[order][effect1]><a href="{url coupon/list/sid/$sid/catid/$catid/order/effect1}">最有用的</a></li>
<li$active[order][comments]><a href="{url coupon/list/sid/$sid/catid/$catid/order/comments}">最多评论</a></li>
</ul>
<div class="clear"></div>
</div>
</div>
{dbres $list $val}
<div class="il_coupon2">
<h2>[<a href="{url coupon/index/catid/$val[catid]}">$category[$val[catid]][name]</a>] <a href="{url coupon/detail/id/$val[couponid]}">$val[subject]</a></h2>
<div class="thumb"><a href="{url coupon/detail/id/$val[couponid]}"><img src="{URLROOT}/$val[thumb]" alt="$val[subject]" /></a></div>
<ul class="info">
<li class="full">商户:<a href="{url item/detail/id/$val[sid]}">$val[name].$val[subname]</a></li>
<li>开始日期:{date $val[starttime], 'Y-m-d'}</li>
<li>截止日期:{date $val[endtime], 'Y-m-d'}</li>
<li class="full">现有<span class="font_2">$val[pageview]</span>次浏览,<span class="font_2">$val[comments]</span>个评论,其中有<span class="font_2">$val[effect1]</span>人认为有用</li>
<li class="full">优惠:$val[des]</li>
</ul>
<div class="clear"></div>
</div>
{/dbres}
</div>
<div class="pageRoll">
<div class=plist id=pageConDown> 以上优惠最终解释权归【$subject[name] $subject[subname]】所有 </div> </div>
</div>
<div class="clear"></div>
</div>
<!--{template 'footer', 'item', $subject[templateid]}--><file_sep>/core/modules/modoer/item/admin/picture_list.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(! defined ( 'IN_ADMIN' ) || ! defined ( 'IN_MUDDER' )) && exit ( 'Access Denied' );
$P = & $_G ['loader']->model ( MOD_FLAG . ':picture' );
$op = isset ( $_POST ['op'] ) ? $_POST ['op'] : $_GET ['op'];
switch ($op) {
case 'add' :
$sid = $_GET ['sid'];
if (empty ( $sid )) {
redirect ( '请选择商家!' );
}
$admin->tplname = cptpl ( 'picture_upload', MOD_FLAG );
break;
case 'upload' :
$P->save ( $P->get_post ( $_POST ) );
redirect ( 'global_op_succeed', cpurl ( $module, $act ) );
break;
case 'save' :
$post = $P->get_post ( $_POST, FALSE );
$P->save ( $post );
redirect ( 'global_op_succeed', cpurl ( $module, $act, '', array ('sid' => $sid ) ) );
break;
case 'delete' :
$P->delete ( $_POST ['picids'] );
redirect ( 'global_op_succeed', cpurl ( $module, $act, '', array (
'pid' => $_GET ['pid']
) ) );
break;
case 'update' :
$P->update ( $_POST ['picture'] );
redirect ( 'global_op_succeed', cpurl ( $module, $act, '', array (
'pid' => $_GET ['pid']
) ) );
break;
case 'set_thumb' :
if (! $picid = _input ( 'picid', null, MF_INT_KEY ))
redirect ( lang ( 'global_sql_keyid_invalid', 'picid' ) );
$A = & $_G ['loader']->model ( 'item:album' );
$A->set_thumb ( $picid );
redirect ( 'global_op_succeed', cpurl ( $module, $act, 'list' ) );
default :
$op = 'list';
$tempname = 'picture_list';
$_G ['loader']->helper ( 'form', 'album' );
$P->db->join ( $P->table, 'p.sid', 'dbpre_subject', 's.sid', MF_DB_LJ );
$P->db->join_together ( 'p.albumid', 'dbpre_album', 'a.albumid', MF_DB_LJ );
if (! $admin->is_founder)
$P->db->where ( 'p.city_id', $_CITY ['aid'] );
if (is_numeric ( $_GET ['city_id'] ) && $_GET ['city_id'] >= 0)
$P->db->where ( 'p.city_id', $_GET ['city_id'] );
if ($_GET ['sid']){
$P->db->where ( 'p.sid', $_GET ['sid'] );
}
if ($_GET ['title'])
$P->db->where_like ( 'p.title', '%' . $_GET ['title'] . '%' );
if ($_GET ['starttime'])
$P->db->where_more ( 'p.addtime', strtotime ( $_GET ['starttime'] ) );
if ($_GET ['endtime'])
$P->db->where_less ( 'p.addtime', strtotime ( $_GET ['endtime'] ) );
if ($total = $P->db->count ()) {
$P->db->sql_roll_back ( 'from,where' );
! $_GET ['orderby'] && $_GET ['orderby'] = 'picid';
! $_GET ['ordersc'] && $_GET ['ordersc'] = 'DESC';
$P->db->order_by ( 'p.' . $_GET ['orderby'], $_GET ['ordersc'] );
$P->db->limit ( get_start ( $_GET ['page'], $_GET ['offset'] ), $_GET ['offset'] );
$P->db->select ( 'p.*,s.name as subjectname,s.subname,a.name as albumname' );
$list = $P->db->get ();
$multipage = multi ( $total, $_GET ['offset'], $_GET ['page'], cpurl ( $module, $act, 'list', $_GET ) );
}
$admin->tplname = cptpl ( $tempname, MOD_FLAG );
}
?><file_sep>/core/modules/tuan/index.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'tuan');
if(!_get('today') && $MOD['index_type'] == 'list') {
include MOD_ROOT . 'list.php';
} else {
$T =& $_G['loader']->model(':tuan');
$T->plan_status();
if($detail = $T->getone("0,$_CITY[aid]")) {
$tplname = 'tuan_detail';
$S =& $_G['loader']->model('item:subject');
$subject = $S->read($detail['sid']);
$subject_field_table_tr = $S->display_listfield($subject);
$TD =& $_G['loader']->model('tuan:discuss');
$total = $TD->count($MOD['discuss_all'] ? 0 : $detail['tid']);
} else {
$tplname = 'tuan_subscribe';
}
$_HEAD['keywords'] = $MOD['meta_keywords'];
$_HEAD['description'] = $MOD['meta_description'];
//include template($tplname);
}
?><file_sep>/core/modules/product/admin/templates/product_save.tpl - ���� (2).php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/validator.js"></script>
<script type="text/javascript" src="./static/javascript/item.js"></script>
<script type="text/javascript" src="./static/javascript/product.js"></script>
<script type="text/javascript">
function checkform(obj) {
return true;
}
var g;
function reload() {
var obj = document.getElementById('reload');
var btn = document.getElementById('switch');
if(obj.innerHTML.match(/^<.+href=.+>/)) {
g = obj.innerHTML;
obj.innerHTML = '<input type="file" name="picture" size="20">';
btn.innerHTML = '取消上传';
} else {
obj.innerHTML = g;
btn.innerHTML = '重新上传';
}
}
function product_create_category(sid) {
if (!is_numeric(sid)) {
alert('未选择产品主题。');
return false;
}
var catname = prompt('请输入您的分类名称:','');
if(!catname) return;
$.post("<?=cpurl($module,$act,'create_category')?>", {'sid':sid, 'catname':catname, 'in_ajax':1 },
function(result) {
if (is_message(result)) {
myAlert(result);
} else if(is_numeric(result)) {
$("<option value='"+result+"'"+' selected="selected"'+">"+catname+"</option>").appendTo($('#catid'));
} else {
alert('产品读取失败,可能网络忙碌,请稍后尝试。');
}
});
product_show_rename_button();
}
//重命名分类
function product_rename_category() {
var catid = $('#catid').val();
var name = $('#catid').find("option:selected").text();
var catname = prompt('请输入您的分类名称:',name);
if(!catname) return;
$.post("<?=cpurl($module,$act,'rename_category')?>", {'catid':catid, 'catname':catname, 'in_ajax':1 },
function(result) {
if (is_message(result)) {
myAlert(result);
} else if(result=='OK') {
$('#catid').find("option:selected").text(catname);
msgOpen('更新成功!');
} else {
alert('产品读取失败,可能网络忙碌,请稍后尝试。');
}
});
}
//显示重命名分类的按钮
function product_show_rename_button() {
var catid = $('#catid').val();
if(catid>0) {
$('#rename_category').show();
} else {
$('#rename_category').hide();
}
}
</script>
<div id="body">
<form method="post" action="<?=cpurl($module,$act,'save')?>" enctype="multipart/form-data" onsubmit="return validator(this);">
<input type="hidden" name="sid" value="<?=$detail['sid']?>" />
<div class="space">
<div class="subtitle">添加/编辑菜品分类</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1" width="15%">所属商家:</td>
<td width="75%">
<input id="sname" type="text" name="sname" value="" class="txtbox" />
<script type="text/javascript">
var url="index.php?m=item&act=ajax&do=subject&op=search1";
$().ready(function() {
$("#sname").autocomplete(url, {
max: 12,
minChars: 1,
width: 400,
scrollHeight: 300,
matchContains: true,
autoFill: false,
formatItem: function(row, i, max, value) {
return value.split('-')[1];
},
formatResult: function(row, value) {
return value.split('-')[1];
}
});
$("#sname").result(function(event, data, formatted) {
$("#sid").val(data[0].split('-')[0] );
});
});
</script>
</td>
</tr>
<tr>
<td width="100" class="altbg1" align="right"><span class="font_1">*</span>菜品名称:</td>
<td width="*">
<input type="text" name="subject" class="txtbox" size="40" value="<?=$detail['subject']?>"
validator="{'empty':'N','errmsg':'请填写菜品名称。'}" />
</td>
</tr>
<tr>
<td class="altbg1">菜品类别:</td>
<td>
<select name="mtype" id="mtype" validator="{'empty':'N','errmsg':'请选择菜品分类。'}"
onchange="product_show_rename_button();">
<option value="" style="color:#CC0000">==选择菜品分类==</option>
<?=form_product_category($sid, $detail['catid']);?>
</select>
<button type="button" onclick="product_create_category(<?=$sid?>);" class="btn2">新建类别</button>
<button type="button" onclick="product_rename_category();" class="btn2" id="rename_category"<?if(!$detail['catid']):?>style="display:none;"<?endif;?>>重命名</button>
</td>
</tr>
<tr>
<td class="altbg1">菜品价格:</td>
<td>
<input type="text" name="price" class="txtbox" value="<?=$detail['price']?>"/>
</td>
</tr>
<tr>
<td class="altbg1" align="right" valign="top">菜品介绍:</td>
<td><textarea name="description" style="width:500px;height:50px;"><?=$detail['description']?></textarea></td>
</tr>
<tr>
<td class="altbg1" align="right">菜品图片:</td>
<td>
<?if(!$detail['thumb']):?>
<input type="file" name="picture" size="20" />
<?else:?>
<span id="reload"><a href="<?=$detail['picture']?>" target="_blank" src="<?=$detail['thumb']?>" onmouseover="tip_start(this);"><?=$detail['thumb']?></a></span> [<a href="javascript:reload();" id="switch">重新上传</a>]
<?endif;?>
</td>
</tr>
</table>
<center>
<input type="hidden" name="do" value="<?=$op?>" />
<input type="hidden" name="pid" value="<?=$_GET['pid']?>" />
<input type="hidden" name="forward" value="<?=get_forward()?>" />
<button type="submit" class="btn" name="dosubmit" value="yes">提交</button>
<button type="button" class="btn" onclick="history.go(-1);">返回</button>
</center>
</div>
</form>
</div>
<file_sep>/core/modules/tuan/admin/undertake.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$TW =& $_G['loader']->model('tuan:wish');
$TU =& $_G['loader']->model('tuan:undertake');
$op = _input('op');
switch($op) {
case 'delete':
$ids = _input('ids', null);
$TU->delete($ids);
redirect('global_op_succeed_delete', get_forward(cpurl($module,'wish'),1));
break;
case 'set_undertaker':
$twid = _input('id',null,MF_INT_KEY);
$id = _input('id',null,MF_INT_KEY);
$TW->set_undertaker($id);
redirect('global_op_succeed', get_forward(cpurl($module,$act,'',array('twid'=>$twid)),1));
break;
default:
$op = 'list';
$twid = _input('twid',null,MF_INT_KEY);
if(!$twid) redirect(lang('global_sql_keyid_invalid','twid'));
$wish = $TW->read($twid);
$where = array();
$where['twid'] = $twid;
$orderby = array('twid'=>'desc');
$start = get_start($_GET['page'], $_GET['offset']);
list($total, $list) = $TU->find('*', $where, $orderby, $start, $_GET['offset'], TRUE);
if($total) {
$multipage = multi($total, $offset, $_GET['page'], cpurl($module, $act, 'list', $_GET));
}
$admin->tplname = cptpl('undertake_list', MOD_FLAG);
}
?><file_sep>/core/modules/tuan/model/crule/qqtuan.php
<?php
/*
* meituan rule
*
*/
$rule='urlset-url=subject:
limengqikey-data-display-title,cityname:
limengqikey-data-display-city,url:
limengqikey-loc,nowprice:
limengqikey-data-display-price,oldprice:
limengqikey-data-display-value,lasttime:
limengqikey-data-display-endTime,thumb:
limengqikey-data-display-image1,nowpeople:
limengqikey-data-display-bought,starttime:
limengqikey-data-display-startTime';
?><file_sep>/core/modules/tuan/admin/coupon.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$TC =& $_G['loader']->model('tuan:coupon');
$op = _input('op');
switch($op) {
case 'send':
$tid = _get('tid', null, 'intval');
$TC->create($tid);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'used':
$serials = _post('serials', null);
foreach($serials as $s) {
$TC->use_coupon($s);
}
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
case 'send_sms':
$tid = _input('tid',null,MF_INT_KEY);
$page = _input('page',null,MF_INT);
list($total, $mobile) = $TC->send_batch_sms($tid, $page);
redirect(array('tuan_batch_send_sms_succeed', array($total,$mobile)));
break;
default:
$TC->update_status(); //更新团购券状态
$op = 'list';
$where = array();
if(!$admin->is_founder) $where['city_id'] = $_CITY['aid'];
$where['status'] = $_GET['status'] = _get('status', 'new', MF_TEXT);
if($_GET['status'] == 'new') {
if($_GET['tid'] > 0) $where['tid'] = $_GET['tid'];
if($_GET['serial']) $where['serial'] = explode("\r\n", $_GET['serial']);
}
$offset = 30;
$start = get_start($_GET['page'], $offset);
list($total,$list) = $TC->getlist($where, $start, $offset, TRUE);
if($total) $multipage = multi($total, $offset, $_GET['page'], cpurl($module, $act, 'list', $_GET));
$lsit_total = $TC->status_total();
$admin->tplname = cptpl('coupon_list', MOD_FLAG);
}
?><file_sep>/core/modules/tuan/deals.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'tuan');
$T =& $_G['loader']->model(':tuan');
if($_G['timestamp'] % 2 == 0) $T->plan_status();
list($total,$list,$multipage) = $T->deals();
$_HEAD['keywords'] = $MOD['meta_keywords'];
$_HEAD['description'] = $MOD['meta_description'];
include template('tuan_deals');
?><file_sep>/core/modules/weixin/search.php
<?php
function doSearch($q) {
$q = str_replace(array("\r\n","\r","\n") ,'', $q);
//if(!$q) location('mobile/index');
$_G['db']->from('dbpre_item');
// $_G['db']->select('*');
// $_G['db']->where('city_id', array(0,$_CITY['aid']));
// $_G['db']->where_concat_like('content,subject', "%{$q}%");
// $_G['db']->where('status', 1);
// $multipage = '';
// if($total = $_G['db']->count()) {
// $_G['db']->sql_roll_back('from,select,where');
// $orderby = array($post['ordersort']=>$post['ordertype']);
// $offset = 10;
// $start = get_start($_GET['page'], $offset);
// $_G['db']->order_by($orderby);
// $_G['db']->limit($start, $offset);
// $list = $_G['db']->get();
// if($total) {
// $multipage = mobile_page($total, $offset, $_GET['page'], url("item/mobile/do/search/keyword/$q/page/_PAGE_"));
// }
// }
//$news = array();
// $i=0;
// for (; $i < total && $i < 9; $i++) {
// $news[$i] = array('Title'=>$list[$i]['subject'],
// 'Description'=>$list[$i]['content'],
// 'PicUrl'=>'',
// 'Url'=>$base_url.'/coupon.php?act=mobile&do=detail&id='.$list[$i]['couponid'].'&f=2');
// }
// $news[$i] = array('Title'=>'更多优惠',
// 'Description'=>'点击查找更多超值优惠内容!',
// 'PicUrl'=>'',
// 'Url'=>$base_url.'/coupon.php?keyword='.$rev_msg.'&act=mobile&do=search');
return 1;
}
?>
<file_sep>/core/modules/party/admin/templates/party_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/item.js"></script>
<script type="text/javascript" src="./static/javascript/validator.js"></script>
<script type="text/javascript" src="./static/javascript/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript">
var g;
function reload() {
var obj = document.getElementById('reload');
var btn = document.getElementById('switch');
if(obj.innerHTML.match(/^<.+href=.+>/)) {
g = obj.innerHTML;
obj.innerHTML = '<input type="file" name="picture" size="20">';
btn.innerHTML = '取消上传';
} else {
obj.innerHTML = g;
btn.innerHTML = '重新上传';
}
}
</script>
<div id="body">
<form method="post" name="myform" action="<?=cpurl($module,$act,'save')?>&" enctype="multipart/form-data" onsubmit="return validator(this);">
<div class="space">
<div class="subtitle">添加/编辑活动</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1" width="120">活动类型:</td>
<td width="*">
<select name="catid" validator="{'empty':'N','errmsg':'请选择活动类型。'}">
<?=form_party_category($detail['catid'])?>
</select>
</td>
</tr>
<tr>
<td class="altbg1">活动名称:</td>
<td><input type="text" name="subject" class="txtbox" value="<?=$detail['subject']?>" validator="{'empty':'N','errmsg':'请填写活动名称。'}" /></td>
</tr>
<tr>
<td class="altbg1">关联商家:</td>
<td>
<input id="sname" type="text" name="sname" value="" class="txtbox" />(如果不关联主题,则留空!)
<script type="text/javascript">
//var url='item/ajax/do/subject/op/search1';
var url="index.php?m=item&act=ajax&do=subject&op=search1";
//var url="index.php?m=item&act=ajax&do=test";
$().ready(function() {
$("#sname").autocomplete(url, {
max: 12,
minChars: 1,
width: 400,
scrollHeight: 300,
matchContains: true,
autoFill: false,
formatItem: function(row, i, max, value) {
return value.split('-')[1];
},
formatResult: function(row, value) {
return value.split('-')[1];
}
});
$("#sname").result(function(event, data, formatted) {
$("#sid").val(data[0].split('-')[0] );
});
});
</script>
</td>
</tr>
<tr>
<td class="altbg1">所在地区:</td>
<td>
<?if($admin->is_founder):?>
<select name="city_id" onchange="select_city(this,'aid');">
<?=form_city($detail['city_id'])?>
</select>
<?endif;?>
<select name="aid" id="aid" validator="{'empty':'N','errmsg':'请选择活动地区。'}">
<option value="">全部</option>
<?=form_area($detail['city_id'], $detail['aid'])?>
</select>
</td>
</tr>
<tr>
<td class="altbg1">详细地址:</td>
<td><input type="text" name="address" class="txtbox" value="<?=$detail['address']?>" validator="{'empty':'N','errmsg':'请填写活动地址。'}" /></td>
</tr>
<tr>
<td class="altbg1">报名截止时间:</td>
<td><input type="text" name="joinendtime" class="txtbox2" value="<?=$detail['joinendtime']?date('Y-m-d H:i', $detail['joinendtime']):''?>" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm'})" validator="{'empty':'N','errmsg':'请选择报名截止时间。'}" /> yyyy-MM-dd HH:mm</td>
</tr>
<tr>
<td class="altbg1">开始时间:</td>
<td><input type="text" name="begintime" class="txtbox2" value="<?=$detail['joinendtime']?date('Y-m-d H:i', $detail['begintime']):''?>" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm'})" validator="{'empty':'N','errmsg':'请选择活动开始时间。'}" /> yyyy-MM-dd HH:mm</td>
</tr>
<tr>
<td class="altbg1">结束时间:</td>
<td><input type="text" name="endtime" class="txtbox2" value="<?=$detail['joinendtime']?date('Y-m-d H:i', $detail['endtime']):''?>" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm'})" validator="{'empty':'N','errmsg':'请选择活动结束时间。'}" /> yyyy-MM-dd HH:mm</td>
</tr>
<tr>
<td class="altbg1">预计费用:</td>
<td><input type="text" name="price" class="txtbox4" value="<?=$detail['price']?>" validator="{'empty':'N','errmsg':'请填写预计费用。'}" /> 元/人</td>
</tr>
<tr>
<td class="altbg1">活动封面:</td>
<td>
<?if(!$detail['thumb']):?>
<input type="file" name="picture" size="20" />
<?else:?>
<span id="reload"><a href="<?=$detail['picture']?>" target="_blank" src="<?=$detail['thumb']?>" onmouseover="tip_start(this);"><?=$detail['thumb']?></a></span>
[<a href="javascript:reload();" id="switch">重新上传</a>]
<?endif;?>
</td>
</tr>
<tr>
<td class="altbg1">联系人:</td>
<td><input type="text" name="linkman" class="txtbox3" value="<?=$detail['linkman']?>" validator="{'empty':'N','errmsg':'请填写联系人姓名。'}" /></td>
</tr>
<tr>
<td class="altbg1">联系方式:</td>
<td><input type="text" name="contact" class="txtbox2" value="<?=$detail['contact']?>" validator="{'empty':'N','errmsg':'请填写联系方式。'}" /></td>
</tr>
<tr>
<td class="altbg1">审核通过:</td>
<td><?=form_bool('status',isset($detail['status'])?$detail['status']:1)?></td>
</tr>
<tr>
<td class="altbg1" valign="top">活动介绍:</td>
<td><?=$edit_html?></td>
</tr>
</table>
</div>
<center>
<input type="hidden" name="do" value="<?=$op?>" />
<?if($op=='edit'):?>
<input type="hidden" name="partyid" value="<?=$detail['partyid']?>" />
<?endif;?>
<input type="hidden" name="forward" value="<?=get_forward()?>" />
<button type="submit" class="btn" name="dosubmit" value="yes">提交</button>
<input type="button" value=" 返回 " class="btn" onclick="history.go(-1);" />
</center>
</form>
</div><file_sep>/core/modules/item/admin/subject_list_easy.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(! defined ( 'IN_ADMIN' ) || ! defined ( 'IN_MUDDER' )) && exit ( 'Access Denied' );
$op = _input ( 'op' );
$I = & $_G ['loader']->model ( MOD_FLAG . ':subject' );
echo $jump;
switch ($op) {
case 'select' :
$sids = implode ( ",", $_POST ['sids'] );
redirect ( 'global_op_succeed', '/admin.php?module=coupon&act=coupon&op=add&sids='.$sids );
break;
default :
$I->db->from ( 'dbpre_subject' );
$I->db->where ( 'status', 1 );
if ($_GET ['keyword']) {
$I->db->where_like ( 'name', '%' . _T ( $_GET ['keyword'] ) . '%' );
}else{
$I->db->where ( 'status', '' );
}
$total = $I->db->count ();
if ($total) {
$I->db->sql_roll_back ( 'from,where' );
if ($total > 1) {
$I->db->where_not_equal ( 'subname', '' );
}
! $_GET ['orderby'] && $_GET ['orderby'] = 'name';
! $_GET ['ordersc'] && $_GET ['ordersc'] = 'DESC';
$I->db->order_by ( $_GET ['order'], $_GET ['ordersc'] );
$I->db->limit ( get_start ( $_GET ['page'], $_GET ['offset'] ), $_GET ['offset'] );
$list = $I->db->get ();
$multipage = multi ( $total, $_GET ['offset'], $_GET ['page'], cpurl ( $module, $act, 'list', $_GET ) );
}
$admin->tplname = cptpl ( 'subject_list_easy', MOD_FLAG );
}
?>
<file_sep>/core/modules/item/admin/templates/subject_film.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./data/cachefiles/area.js"></script>
<script type="text/javascript" src="./static/javascript/item.js"></script>
<script type="text/javascript" src="./data/cachefiles/item_category_1.js"></script>
<style type="text/css">
.img img { max-width:80px; max-height:60px; border:1px solid #ccc; padding:1px;
_width:expression(this.width > 80 ? 80 : true); _height:expression(this.height > 60 ? 60 : true); }
</style>
<div id="body">
<form method="get" action="<?=SELF?>">
<input type="hidden" name="module" value="<?=$module?>" />
<input type="hidden" name="act" value="<?=$act?>" />
<input type="hidden" name="op" value="<?=$op?>" />
<div class="space">
<div class="subtitle">影片筛选</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1">影片关键字</td>
<td><input type="text" name="keyword" class="txtbox3" value="<?=$_GET['keyword']?>" /></td>
</tr>
<tr>
<td class="altbg1">发布时间</td>
<td colspan="3"><input type="text" name="starttime" class="txtbox3" value="<?=$_GET['starttime']?>" /> ~ <input type="text" name="endtime" class="txtbox3" value="<?=$_GET['endtime']?>" /> (YYYY-MM-DD)</td>
</tr>
<tr>
<td><button type="submit" value="yes" name="dosubmit" class="btn2">筛选</button></td>
</tr>
</table>
</div>
</form>
<form method="post" name="myform" action="<?=cpurl($module,$act,'',array('pid'=>$pid))?>">
<div class="space">
<div class="subtitle">排片管理</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y" >
<tr class="altbg1">
<td width="25">选择</td>
<td width="*">影片名称</td>
<td width="*">放映时间<?=p_order('addtime');?></td>
</tr>
<?if($total):?>
<?while($val=$list->fetch_array()):?>
<tr>
<td><input type="checkbox" name="sids[]" value="<?=$val['sid']?>" /></td>
<td><?=$val['subject']?></td>
<td><input type="text" name="subjects[<?=$val['sid']?>][finer]" value="<?=$val['finer']?>" class="txtbox5" /></td>
</tr>
<?endwhile;?>
<tr>
<td colspan="12" class="altbg1">
<button type="button" onclick="checkbox_checked('sids[]');" class="btn2">全选</button>
</td>
</tr>
<?else:?>
<tr>
<td colspan="15">暂无信息。</td>
</tr>
<?endif;?>
</table>
</div>
<?if($total):?>
<script type="text/javascript">
$('.subject_operation').powerFloat({position:'8-6',targetMode:"ajax"});
</script>
<div class="multipage"><?=$multipage?></div>
<center>
<input type="hidden" name="dosubmit" value="yes" />
<input type="hidden" name="op" value="" />
<button type="button" class="btn" onclick="easy_submit('myform','update',null)">保存排片</button>
<button type="button" class="btn" onclick="easy_submit('myform','delete','sids[]')">删除排片</button>
</center>
<?endif;?>
</form>
</div><file_sep>/core/modules/tuan/model/coupon_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_tuan_coupon extends ms_model {
var $table = 'dbpre_tuan_coupon';
var $key = 'id';
var $model_flag = 'tuan';
var $sms = null;
var $status_arr = array('available','used','expired');
function __construct() {
parent::__construct();
$this->model_flag = 'tuan';
$this->modcfg = $this->variable('config');
if($this->modcfg['send_sms']) {
$this->sms = $this->get_sms();
}
}
function msm_tuan_coupon() {
$this->__construct();
}
private function get_sms() {
$this->loader->model('sms:factory',null);
$this->sms = msm_sms_factory::create();
}
function read($id,$select='*',$is_serial=false) {
if(!$is_serial) return parent::read($id);
if(!$id) redirect(lang('global_sql_keyid_invalid', 'serial'));
$where = array();
$where['serial'] = $id;
$row = $this->db->get_easy($select, $this->table, $where);
$result = $row ? $row->fetch_array() : FALSE;
return $result;
}
function create($tid, $oid=null) {
$T =& $this->loader->model(':tuan');
if(!$detail = $T->read($tid)) return;
if(!$T->check_succeed($detail)) return;
$O =& $this->loader->model('tuan:order');
if(!$list = $O->get_sent_list($tid)) return;
if(!$sserial = $this->_create_serial()) {
$sserial = date('ymd', $this->global['timestamp']) . '000000';
}
$num_1 = substr($sserial, 0, 6);
$num_2 = (int)substr($sserial,-6);
$data = array();
while($val = $list->fetch_array()) {
for($i=1; $i<= $val['num']; $i++) {
$num_2 += 1;
$newserial = sprintf("%s%06d", $num_1, $num_2);
list(,$password) = $this->_create($newserial, $val['tid'], $val['oid'], $val['uid'], $val['username'], $detail['expiretime']);
// //短信发送收集,只发送当前订单的优惠券(避免大量优惠券同时发送,造成页面超时现象)
if($this->modcfg['send_sms'] && $val['mobile'] && $val['oid'] == $oid && $oid > 0) {
$data[] = array (
'username' => $val['username'],
'mobile' => $val['mobile'],
'id' => $newserial,
'pw' => $password,
);
}
}
$O->update_sent($val['oid']);
}
$list->free_result();
//发送手机短信
if($this->modcfg['send_sms'] && $data) {
$this->send_sms($data, $detail['subject'], $detail['sms']);
}
}
function send_sms($data, $title, $message) {
if(!$data||!$message) return;
$mobiles = '';
$s = array('{title}','{username}','{id}','{pw}');
$result = false;
foreach($data as $k => $v) {
$r = array($title,$v['username'], $v['id'], $v['pw']);
$message = str_replace($s, $r, $message);
$result = $this->_send_sms($v['mobile'], $message);
}
return $result;
}
function single_send_sms($couponid) {
if(!$coupon = $this->read($couponid)) redirect('tuan_coupon_empty');
if($this->global['timestamp'] - $this->modcfg['sms_interval'] <= $coupon['sms_sendtime']) {
redirect('tuan_sms_send_quick');
}
$this->db->join('dbpre_tuan_order','o.tid','dbpre_tuan','t.tid','LEFT JOIN');
$this->db->select('o.username,o.mobile,t.subject,t.sms');
$this->db->where('o.oid',$coupon['oid']);
if(!$detail = $this->db->get_one()) redirect('tuan_empty');
$data[] = array(
'username' => $detail['username'],
'mobile' => $detail['mobile'],
'id' => $coupon['serial'],
'pw' => $coupon['passward'],
);
if(!$this->send_sms($data, $detail['subject'], $detail['sms'])) {
//增加发送失败次数
$this->db->from($this->table)->where('id',$couponid)->set_add('sms_error',1)->update();
redirect('tuan_sms_send_lost');
}
//更新发送时间
$this->db->from($this->table);
$this->db->set('sms_sendtime',$this->global['timestamp']);
$this->db->where('id',$couponid);
$this->db->update();
//返回发送的手机号
return $detail['mobile'];
}
function send_batch_sms($tid, $page) {
if(!$tid) redirect(lang('global_sql_keyid_invalid','tid'));
$O =& $this->loader->model('tuan:order');
$this->db->from($O->table);
$this->db->where('status','payed');
$this->db->where('tid', $tid);
$this->db->where_not_equal('mobile','');
$q = $this->db->get();
if(!$q) redirect('tuan_batch_send_sms_empty');
$oids = array();
while ($v = $q->fetch_array()) {
$oids[] = $v['oid'];
}
$q->free_result();
if(!$oids) redirect('tuan_batch_send_sms_empty');
$offset = 1;
$start = get_start($page, $offset);//每次只发1条
$this->db->from($this->table);
$this->db->where('oid',$oids);
$this->db->where('sms_sendtime', 0);
$this->db->where('sms_error', 0);
$total = $this->db->count();
if(!$total) redirect('END');
$this->db->sql_roll_back('from,where');
$this->db->order_by('id','ASC');
$this->db->limit($start,$offset);
$coupon = $this->db->get_one();
if(!$coupon) redirect('END');
$mobile = $this->single_send_sms($coupon['id']);
return array($total, $mobile);
}
//批量更新团购券有效期
function update_expiretime($tid, $expiretime) {
$this->db->from($this->table);
$this->db->set('expiretime', $expiretime);
$this->db->where('tid',$tid);
$this->db->where_not_equal('expiretime', $expiretime);
$this->db->update();
}
//更新团购全有效期
function update_status($tid=null) {
$expiretime = strtotime(date('Y-m-d', $this->global['timestamp']+3600*24));
$this->db->from($this->table);
$this->db->set('status','expired');
$this->db->where_less('expiretime', $expiretime);
if($tid > 0) $this->db->where('tid', $tid);
$this->db->update();
}
//使用团购券
function use_coupon($serial, $passward=null) {
if(!$serial = trim($serial)) redirect('tuan_coupon_serial_empty');
$passward = trim($passward);
$this->db->from($this->table);
$this->db->where('serial', $serial);
if(!$coupon = $this->db->get_one()) redirect('tuan_coupon_empty');
if(!$this->in_admin) {
if(!$passward) redirect('tuan_coupon_pw_empty');
if($coupon['passward'] != $passward) redirect('tuan_coupon_pw_invalid');
}
if($coupon['status']!='new') redirect('tuan_coupon_expiretime');
if(date('Ymd', $coupon['expiretime']) < date('Ymd', $this->global['timestamp'])) redirect('tuan_coupon_expiretime');
//验证正确,更新券
$this->db->from($this->table);
$this->db->set('usetime',$this->global['timestamp']);
$this->db->set('status', 'used');
if(!$this->in_admin) {
$this->db->set('op_uid', $this->global['user']->uid);
$this->db->set('op_username', $this->global['user']->username);
} else {
$this->db->set('op_username', $this->global['admin']->adminname);
}
$this->db->where('id', $coupon['id']);
$this->db->update();
//给消费用户积分
$P =& $this->loader->model('member:point');
$P->update_point($coupon['uid'], 'use_tuan_coupon', 0, 1, FALSE, TRUE, lang('tuan_coupon_use_point_des'));
unset($P);
}
//取得我的某个订单的团购券
function my_single($uid, $oid, $status, $start=0, $offset=0) {
$this->db->from($this->table);
$this->db->where('uid', $uid);
$this->db->where('oid', $oid);
if(!in_array($status, $this->status_arr)) $status = 'available';
if($status == 'used') {
$this->db->where_not_equal('usetime', 0);
} elseif($status == 'expired') {
$this->db->where('usetime', 0);
$this->db->where_less('expiretime', $this->global['timestamp']);
} else {
$this->db->where('usetime', 0);
}
if(!$total = $this->db->count()) return array(0,null);
$this->db->sql_roll_back('from,where');
$this->db->order_by(array('dateline'=>'DESC'));
$this->db->limit($start,$offset);
$list = $this->db->get();
return array($total, $list);
}
//取得我的所有团购券
function my_all($uid, $status, $start=0, $offset=0) {
$this->db->join($this->table, 'tc.tid', 'dbpre_tuan', 't.tid');
$this->db->where('tc.uid', $uid);
if(!in_array($status, $this->status_arr)) $status = 'available';
if($status == 'used') {
$this->db->where_not_equal('usetime', 0);
} elseif($status == 'expired') {
$this->db->where('tc.usetime', 0);
$this->db->where_less('tc.expiretime', $this->global['timestamp']);
} else {
$this->db->where('tc.usetime', 0);
}
$this->db->group_by('tc.oid');
$SQL = "select count(*) from (" . $this->db->get_sql(1) . ") a";
$this->db->_cache_sql();
$row = $this->db->query($SQL);
$total = (int)$row->result(0);
if(!$total) {
$this->db->_cache_sql(1);
return array(0,null);
}
$this->db->sql_roll_back('from,where,group_by');
$this->db->select('tc.*');
$this->db->select('t.subject,t.thumb');
$this->db->select('tc.oid', 'coupon_count', 'COUNT( ? )');
$this->db->order_by(array('tc.dateline'=>'DESC','tc.tid'=>'ASC'));
$this->db->limit($start,$offset);
$list = $this->db->get();
return array($total, $list);
}
//后台列表
function getlist($where, $start, $offset) {
$this->db->join($this->table, 'tc.tid', 'dbpre_tuan', 't.tid');
if(!is_array($where)) $where = array('status', $where);
foreach($where as $k => $v) {
if(preg_match("/^[a-z]+$/", $k)) $k = 'tc.' . $k;
$this->db->where($k, $v);
}
if(!$total = $this->db->count()) return array(0,null);
$this->db->sql_roll_back('from,where');
$this->db->select('tc.*');
$this->db->select('t.subject,t.thumb');
$this->db->order_by(array('tc.tid'=>'ASC','tc.serial'=>'ASC'));
$this->db->limit($start,$offset);
$list = $this->db->get();
return array($total, $list);
}
//某个团购的团购全状态统计
function status_total($tid=null) {
$this->db->from($this->table);
if($tid > 0) $this->db->where('tid',$tid);
$this->db->group_by('status');
$this->db->select('status');
$this->db->select('id', 'count', 'COUNT(?)');
if(!$q = $this->db->get()) return array();
$result = array();
$result['total'] = 0;
while($v=$q->fetch_array()) {
$result['total'] += $v['count'];
foreach($v as $_k=>$_v) {
$result[$v['status']][$_k] = $_v;
}
}
$q->free_result();
return $result;
}
//短信息发送统计
function sms_total($tid) {
$O =& $this->loader->model('tuan:order');
$this->db->from($O->table);
$this->db->where('status','payed');
$this->db->where('tid',$tid);
$this->db->where_not_equal('mobile','');
$q = $this->db->get();
if(!$q) return array(0,0,0,0);
$oids = array();
while ($v = $q->fetch_array()) {
$oids[] = $v['oid'];
}
$q->free_result();
//统计总数
$count = $this->db->from($this->table)->where('oid', $oids)->count();
//统计已经发送的
$send = $this->db->from($this->table)->where('oid', $oids)->where_not_equal('sms_sendtime', 0)->count();
//统计未发送的
$not_send = $this->db->from($this->table)->where('oid', $oids)->where('sms_sendtime', 0)->where('sms_error', 0)->count();
//统计发送失败的
$error = $this->db->from($this->table)->where('oid', $oids)->where('sms_sendtime', 0)->where_more('sms_error', 1)->count();
//返回
return array($count, $send, $not_send, $error);
}
//删除
function delete_tids($tids) {
$ids = parent::get_keyids($tids);
$this->db->where('tid', $ids);
$this->db->from($this->table);
$this->db->delete();
}
//删除订单时
function delete_order($oids) {
$ids = parent::get_keyids($oids);
$this->db->where('oid', $ids);
$this->db->from($this->table);
$this->db->delete();
}
//发送手机短信
function _send_sms($mobiles, $message) {
if(!$this->sms) $this->get_sms();
return $this->sms->send($mobiles, $message);
}
function _create($start_serial, $tid, $oid, $uid, $username, $expiretime) {
$insert = array();
$insert['oid'] = $oid;
$insert['tid'] = $tid;
$insert['uid'] = $uid;
$insert['username'] = $username;
$insert['oid'] = $oid;
$insert['serial'] = $start_serial;
$insert['passward'] = random(6);
$insert['expiretime'] = $expiretime;
$insert['usetime'] = 0;
$insert['dateline'] = $this->global['timestamp'];
$insert['op_uid'] = 0;
$insert['op_username'] = '';
$this->db->from($this->table);
$this->db->set($insert);
$this->db->insert();
return array($insert['serial'], $insert['passward']);
}
function _create_serial() {
$this->db->from($this->table);
$this->db->select('serial');
$starttime = strtotime(date('Y-m-d', $this->global['timestamp']));
$endtime = $starttime + (24*3600-1);
$this->db->where_between_and('dateline', $starttime, $endtime);
$this->db->order_by('serial', 'DESC');
return $this->db->get_value();
}
}
?><file_sep>/templates/item/sjstyle/index.php
<?exit?>
{template vip2_header}
<script type="text/javascript">
loadscript('swfobject');
$(document).ready(function() {
if(!$.browser.msie && !$.browser.safari) {
var d = $("#thumb");
var dh = parseInt(d.css("height").replace("px",''));
var ih = parseInt(d.find("img").css("height").replace("px",''));
if(dh - ih < 3) return;
var top = Math.ceil((dh - ih) / 2);
d.find("img").css("margin-top",top+"px");
}
<!--{if $MOD['show_thumb'] && $detail['pictures']}-->
get_pictures($sid);
<!--{/if}-->
get_membereffect($sid, $modelid);
});
</script>
<link href="{URLROOT}/img/shop/$detail[c_sjstyle]/style.css" rel="stylesheet" type="text/css" />
<!--头开始-->
<div class="header">
<div class="headerinfo">$detail[name] $detail[subname]</div>
<div class="headermeun">
<ul>
<li class="in"><div><a href="{url item/detail/id/$detail[sid]}">首页</a> </div></li>
<li><div><a href="{url item/vipabout/id/$detail[sid]}">店铺介绍</a> </div></li>
<li><div><a href="{url article/list/sid/$sid}">店铺动态</a> </div></li>
<li><div><a href="{url item/pic/sid/$detail[sid]}">店铺展示</a> </div></li>
<li><div><a href="{url product/list/sid/$sid}">产品展厅</a> </div></li>
<li><div><a href="{url coupon/list/sid/$sid}">优惠打折</a> </div></li>
<li><div><a href="{url item/vipvideo/id/$detail[sid]}">视频展播</a> </div></li>
<li><div><a href="{url item/vipcontact/id/$detail[sid]}">联系方式</a> </div></li>
</ul>
</div>
</div>
<!--头结束-->
<!--头部flash-->
<!--{if $detail[c_pictop1]}-->
<div style="margin:0 auto; width:976px;">
<SCRIPT src="{URLROOT}/img/shop/js/swfobject_source.js" type=text/javascript></SCRIPT>
<DIV id=flashFCI><A href="#" arget=_blank><IMG alt="" border=0></A></DIV>
<SCRIPT type=text/javascript>
var s1 = new SWFObject("{URLROOT}/img/shop/js/focusFlash_fp.swf", "mymovie1", "976", "150", "5", "#ffffff");
s1.addParam("wmode", "transparent");
s1.addParam("AllowscriptAccess", "sameDomain");
s1.addVariable("bigSrc", "$detail[c_pictop1]{if $detail[c_pictop2]}|$detail[c_pictop2]{/if}{if $detail[c_pictop3]}|$detail[c_pictop3]{/if}");
s1.addVariable("smallSrc", "|$detail[c_pictop1]|||");
s1.addVariable("href", "||");
s1.addVariable("txt", "||");
s1.addVariable("width", "976");
s1.addVariable("height", "150");
s1.write("flashFCI");
</SCRIPT>
</div>
<!--{/if}-->
<!--end头部flash-->
<div class="content">
<div class="pagejc">
<div class="col1">
<div class="titles">
<div class="fl">基本信息</div>
<div class="fr"></div>
<div class="clear"></div>
</div>
<div class="neirongs" style="padding:10px;">
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td valign="top">
<a href="{url item/pic/sid/$detail[sid]}"><img src="{URLROOT}/{if $detail[thumb]}$detail[thumb]{else}static/images/noimg.gif{/if}" alt="$detail[name]" width="110" height="80" /></a>
</td>
<td valign="top">
<!--{loop $reviewpot $val}-->$val[name]:<img src="{URLROOT}/img/shop/eshop/z{print cfloat($detail[$val[flag]])}.gif" alt="{print cfloat($detail[$val[flag]])} 分" /><br /><!--{/loop}-->
综合:<img src="{URLROOT}/img/shop/eshop/z{print cfloat($detail[avgsort])}.gif" alt="{print cfloat($detail[avgsort])} 分" />
</td>
</tr>
</table>
<div class="lefttitle">$detail[name]</div>
<div class="leftnr">
管 理 者:
<!--{if $detail[owner]}-->
<a href="{url space/index/username/$detail[owner]}" target="_blank">$detail[owner]</a>
<!--{elseif $catcfg[subject_apply]}-->
<a href="{url item/member/ac/subject_apply/sid/$detail[sid]}"><font color="#cc0000"><b>认领$model[item_name]</b></font></a>
<!--{/if}-->
<!--{if $catcfg[use_subbranch]}-->
<a href="{url item/member/ac/subject_add/subbranch_sid/$detail[sid]}">添加分店</a>
<!--{/if}--><br />
<!--{if $detail[finer]}-->
店铺级别:<img src="{URLROOT}/img/shop/eshop/vip$detail[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<table class="custom_field" border="0" cellspacing="0" cellpadding="0">
$detail_custom_field
</table>
</div>
</div>
<!--{if check_module('article')}-->
<div class="mq"></div>
<div class="titles"><div class="fl">新闻</div><div class="fr"><a href="{url article/viplist/sid/$sid}">查看全部</a></div><div class="clear"></div></div>
<div class="neirongs">
<table width="99%" border="0" cellpadding="0" cellspacing="0" >
<!--{get:article val=getlist(sid/$sid/orderby/dateline DESC/rows/5)}-->
<tr><td>
<a href="{url article/detail/id/$val[articleid]}" title="$val[subject]">{sublen $val[subject],16}</a>
</td></tr>
<!--{getempty(val)}-->
<tr><td>暂无信息</td></tr>
<!--{/get}-->
</table>
</div>
<!--{/if}-->
<!--{if $catcfg[use_subbranch]}-->
<div class="mq"></div>
<div class="titles"><div class="fl">分店</div><div class="fr"></div><div class="clear"></div></div>
<div class="neirongs">
<table width="99%" border="0" cellpadding="0" cellspacing="0" >
<tr><td>
<!--{eval
$name = _T($detail[name]);
$city_id = $_CITY[aid];
}-->
<!--{datacallname:主题_相关主题}-->
</td></tr>
</table>
</div>
<!--{/if}-->
<!--{if $detail['coupons'] && check_module('coupon')}-->
<div class="mq"></div>
<div class="titles"><div class="fl">优惠券</div><div class="fr"><a href="{url coupon/list/sid/$sid}">查看全部</a></div><div class="clear"></div></div>
<div class="neirongs">
<table width="99%" border="0" cellpadding="0" cellspacing="0" >
<!--{get:coupon val=list_subject(sid/$sid/orderby/dateline DESC/rows/5)}-->
<tr><td>
<a href="{url coupon/detail/id/$val[couponid]}" title="$val[subject]">{sublen $val[subject],16}</a> <cite>{date $val[dateline],'m-d'}</cite>
</td></tr>
<!--{/get}-->
</table>
</div>
<!--{/if}-->
<div class="mq"></div>
<div class="titles">地图</div>
<div class="neirongs" style="padding:5px;">
<!--{if $model[usearea]}-->
<!--{eval $mapparam = array(
'title' => $detail[name] . $detail[subname],
'show' => $detail[mappoint]?1:0,
);}-->
<iframe id="item_map1" src="{url index/map/width/240/height/245/title/$mapparam[title]/p/$detail[mappoint]/show/$mapparam[show]}" frameborder="0" scrolling="no"></iframe>
<div style="text-align:center;">
<!--{if !$detail['mappoint']}-->
<a href="javascript:post_map($detail[sid], $detail[pid]);">地图未标注,我来标注</a>
<!--{else}-->
<a href="javascript:show_bigmap();">查看大图</a>
<a href="javascript:post_map($detail[sid], $detail[pid]);">报错</a>
<!--{/if}-->
</div>
<script type="text/javascript">
function show_bigmap() {
var src = "{url index/map/width/600/height/400/title/$mapparam[title]/p/$detail[mappoint]/show/$mapparam[show]}";
var html = '<iframe src="' + src + '" frameborder="0" scrolling="no" width="100%" height="400" id="ifupmap_map"></iframe>';
dlgOpen('查看大图', html, 600, 450);
}
</script>
<!--{/if}-->
</div>
<div class="mq"></div>
<div class="titles">
<span class="selected" id="btn_subject1" onclick="tabSelect(1,'subject')">同类{$model[item_name]}</span>
<!--{if $model[usearea]}-->
<span class="unselected" id="btn_subject2" onclick="tabSelect(2,'subject')">附近{$model[item_name]}</span>
<!--{/if}-->
<div class="clear"></div></div>
<div class="neirongs">
<div class="none" id="subject1" datacallname="主题_同类主题" params="{city_id:'$_CITY[aid]','catid':'$detail[catid]','sid':'$sid'}"></div>
<!--{if $model[usearea]}-->
<div class="none" id="subject2" datacallname="主题_附近主题" params="{city_id:'$_CITY[aid]','aid':'$detail[aid]','sid':'$sid'}"></div>
<!--{/if}-->
</div>
<script type="text/javascript">
$(document).ready(function() {
tabSelect(1,'subject');
});
</script>
<div class="mq"></div>
</div> <!--col1end-->
<div class="col2">
<div class="titleb">商铺海报</div>
<div class="neirongb">
<link rel="stylesheet" type="text/css" href="{URLROOT}/img/shop/other/shop_right.css" />
<script type="text/javascript" src="{URLROOT}/img/shop/other/tab.js"></script>
<div class="showpic">
<!--{if $detail[c_weihuabg]}-->
<img src="$detail[c_weihuabg]" width="709" height="220" border="0"/>
<!--{else}-->
<img src="{URLROOT}/img/shop/other/ch.gif" width="709" height="220" border="0"/>
<!--{/if}-->
<span>品牌文化</span>
<div>
<!--{if $detail[c_weihua]}-->
<p>$detail[c_weihua]</p>
<!--{else}-->
<p>本店尚无海报标语</p>
<!--{/if}-->
</div>
</div>
</div><!--neirongb商铺海报end-->
<div class="titleb">商铺视频</div>
<div class="neirongb">
<script type="text/javascript">tab_hotshop = new TabClass({tabName:'tab_hotshop', cntName:'cnt_hotshop', tabShowCls:'HotshopTon', number:3});</script>
<DIV id="store_r1_left">
<DIV class="gray f14" id=store_r1_left_b>
<UL id=tab_hotshop_0 onMouseMove="tab_hotshop.show(0);"><B>全景逛店</B></UL>
<UL id=tab_hotshop_1 onMouseMove="tab_hotshop.show(1);"><B>店面形象</B></UL>
<UL id=tab_hotshop_2 class="HotshopTon" onMouseMove="tab_hotshop.show(2);"><B>视频展示</B></UL>
</DIV>
<DIV id=cnt_hotshop_0 style="DISPLAY: none">
<DIV id=tv>
<!--{if $detail[c_qj]}-->
<object id="video" name="video" width="480" height="397">
<param name="movie" value="$detail[c_qj]"></param>
<param name="allowScriptAccess" value="always"></param>
<param name="allowFullScreen" value="true"></param>
<param name="wmode" value="transparent"></param>
<embed src="$detail[c_qj]" type="application/x-shockwave-flash" width="480" height="397" allowFullScreen="true" wmode="transparent" allowScriptAccess="always"></embed>
</object>
<!--{else}-->
<object id="video" name="video" width="480" height="397">
<param name="movie" value="{URLROOT}/img/shop/360swf.swf" type="application/x-shockwave-flash"></param>
<param name="allowScriptAccess" value="always"></param>
<param name="allowFullScreen" value="true"></param>
<param name="wmode" value="transparent"></param>
<embed src="{URLROOT}/img/shop/360swf.swf" type="application/x-shockwave-flash" width="480" height="397" allowFullScreen="true" wmode="transparent" allowScriptAccess="always"></embed>
</object>
<!--{/if}-->
</DIV>
<DIV class=gray id=store_r1_left_d2>
<UL><A
href="http://fpdownload.macromedia.com/get/flashplayer/current/licensing/win/install_flash_player_active_x.exe"
target=_blank>·无法观看店铺全景,请安装最新FLASH播放器·</A></UL>
</DIV></DIV>
<DIV id=cnt_hotshop_1 style="DISPLAY: none">
<DIV id=tv>
<!--{if $detail[thumb]}-->
<a href="{url item/pic/sid/$detail[sid]}" target="_blank"><img src="{URLROOT}/$detail[thumb]" alt="$detail[name]" width="480" height="397" border="0" /></a>
<!--{else}-->
<a href="{url item/member/ac/pic_upload/sid/$sid}" target="_blank"><img src="{URLROOT}/img/shopimg/noimg2.gif" alt="上传图片" width="480" height="397" border="0" /></a>
<!--{/if}-->
</DIV>
<DIV class=gray id=store_r1_left_d2><SPAN id=pagebar1>
<!--{if $detail[pictures]}-->
<a href="{url item/pic/sid/$detail[sid]}">共<font color="#FF6600">$detail[pictures]</font>张图片</a>
<!--{/if}-->
<A href="{url item/pic/sid/$detail[sid]}" target="_blank">查看全部图片</A>
<a href="{url item/member/ac/pic_upload/sid/$sid}" target="_blank"><font color="#FF6600">我来上传图片</font></a></SPAN></DIV></DIV>
<DIV id=cnt_hotshop_2>
<DIV id=tv>
<!--{if $detail[video]}-->
<object id="video" name="video" width="480" height="397">
<param name="movie" value="$detail[video]"></param>
<param name="allowScriptAccess" value="always"></param>
<param name="allowFullScreen" value="true"></param>
<param name="wmode" value="transparent"></param>
<embed src="$detail[video]" type="application/x-shockwave-flash" width="480" height="397" allowFullScreen="true" wmode="transparent" allowScriptAccess="always">
</embed>
</object>
<!--{else}-->
<object id="video" name="video" width="480" height="397">
<param name="movie" value="http://www.56.com/n_v163_/c22_/23_/9_/hsl8158_/123552792188x_/36480_/0_/41505513.swf"></param>
<param name="allowScriptAccess" value="always"></param>
<param name="allowFullScreen" value="true"></param>
<param name="wmode" value="transparent"></param>
<embed src="http://www.56.com/n_v163_/c22_/23_/9_/hsl8158_/123552792188x_/36480_/0_/41505513.swf" type="application/x-shockwave-flash" width="480" height="397" allowFullScreen="true" wmode="transparent" allowScriptAccess="always"></embed>
</object>
<!--{/if}-->
</DIV>
<DIV class=gray id=store_r1_left_d2>
<UL><A
href="http://fpdownload.macromedia.com/get/flashplayer/current/licensing/win/install_flash_player_active_x.exe"
target=_blank>·无法观看店铺全景,请安装最新FLASH播放器·</A></UL>
</DIV></DIV>
<UL id=temp_store_VPV2_2 style="DISPLAY: none"></UL>
</DIV><!--store_r1_leftend-->
<DIV id="store_r1_right">
<!--{if !$MOD[close_detail_total]}-->
<DIV class="store180">
<H3>数据统计</H3>
<DIV class="store170 gray">
<UL><LABEL>[<B>已浏览</B>]</LABEL><span class="fontred"><strong>$detail[pageviews]</strong>次</span></UL>
<UL><LABEL>[<B>已点评</B>]</LABEL><span class="fontred"><strong>$detail[reviews]</strong>条</span></UL>
<UL><LABEL>[<B>已留言</B>]</LABEL><span class="fontred"><strong>$detail[guestbooks]</strong>条</span></UL>
<UL><LABEL>[<B>已上传</B>]</LABEL><span class="fontred"><strong>$detail[pictures]</strong>图</span></UL>
{if $detail[products]}
<UL><LABEL>[<B>有产品</B>]</LABEL><span class="fontred"><strong>$detail[products]</strong>个</span></UL>
{/if}
<!--{if $detail[card_msg]}-->
<UL><LABEL>[<B>会员卡</B>]</LABEL><span class="fontred"><strong>$detail[card_msg]折</strong></span></UL>
<!--{else}-->
<UL><LABEL>[<B>会员卡</B>]</LABEL><span class="fontred"><strong>尚未与网站签约</strong></span></UL>
<!--{/if}-->
<UL><LABEL>[<B>优惠券</B>]</LABEL><span class="fontred"><strong>$detail[coupons]</strong>张</span></UL>
<!--{if $detail[creator]}-->
<UL><LABEL>[<B>登记人</B>]</LABEL><a href="{url space/index/username/$detail[creator]}" title="{date $detail[addtime]}"><span class="fontred"><strong>$detail[creator]</strong></span></a></UL>
<!--{/if}-->
</DIV></DIV>
<!--{/if}-->
<DIV class="store180" >
<H3>点评得分</H3>
<DIV class="store170 gray">
<!--{loop $reviewpot $val}-->
<UL><LABEL>[<B>$val[name]</B>]</LABEL><span class="font_1" style="font-size:16px; font-weight:bold;">{print cfloat($detail[$val[flag]])}</span></UL>
<!--{/loop}-->
<UL><LABEL>[<B>综合得分</B>]</LABEL><span class="font_1" style="font-size:16px;"><strong>{print cfloat($detail[avgsort])}</strong></span></UL>
</DIV></DIV>
<DIV class="store180" >
<H3>网友互动</H3>
<DIV class="store170 gray">
<!--{if $catcfg[useeffect]}-->
<div style="float:left">
<!--{if $catcfg[effect1]}--><a href="javascript:post_membereffect($sid,'effect1');" class="ybg">我{$catcfg[effect1]}<br /><span id="num_effect1" class="num">0</span></a><!--{/if}-->
</div>
<div style="float:right">
<!--{if $catcfg[effect2]}--><a href="javascript:post_membereffect($sid,'effect2');" class="ybg">我{$catcfg[effect2]}<br /><span id="num_effect2" class="num">0</span></a><!--{/if}-->
</div>
<!--{/if}-->
</DIV>
<DIV class="store170 gray" style=" padding-top:10px;">
<div style="float:left"><a href="{url item/member/ac/review_add/sid/$sid}" onclick="return post_review($sid);"><img src="{URLROOT}/img/shop/other/pl_btn.gif" /></a></div>
<div style="float:right">
<!--{if !$detail[owner]}-->
<a href="{url item/member/ac/subject_apply/sid/$detail[sid]}"><img src="{URLROOT}/img/shop/other/rl_btn.gif" alt="认领后具有更多的管理权限,可以发布商铺信息,发布商铺产品." title="认领后具有更多的管理权限,可以发布商铺信息,发布商铺产品." /></a>
<!--{/if}-->
</div>
</DIV>
</DIV><!--store180-->
</DIV><!--store_r1_rightend-->
</div><!--neirongb-->
<!--{if $detail[description]}-->
<div class="titleb"><div class="fl">商铺简介</div><div class="fr"><a href="{url item/vipabout/id/$detail[sid]}">详细内容</a></div></div>
<div class="neirongb">
$detail[description]
</div>
<!--{/if}-->
<!--{if $MOD['show_thumb'] && $detail['pictures']}-->
<div class="titleb"><div class="fl">{$model[item_name]}图片</div><div class="fr"><a href="{url item/pic/sid/$detail[sid]}">查看全部</a> <a href="javascript:;" onclick="$('#itempics').toggle();">收起/展开</a></div></div>
<div class="neirongb">
<div class="itempics" id="itempics"></div>
<div id="thumb" style="display:none;"><img /></div>
</div>
<!--{/if}-->
<!--{if $_G['modules']['product'] && $detail['products']}-->
<div class="titleb"><div class="fl">{$model[item_name]}产品</div><div class="fr"><a href="{url product/list/sid/$sid}">查看全部</a></div></div>
<div class="neirongb">
<div class="prli">
<!--{datacallname:产品_主题产品_风格页中}-->
</div>
</div>
<!--{/if}-->
<script type="text/javascript" src="{URLROOT}/static/javascript/review.js"></script>
<style type="text/css">@import url("{URLROOT}/{$_G[tplurl]}css_review.css");</style>
<a name="$view" id="$view"></a>
<!--{if $view == 'forum'}-->
{template item_subject_detail_forum}
<!--{elseif $view == 'guestbook'}-->
{template item_subject_detail_guestbook}
<!--{else}-->
{template item_subject_detail_review}
<!--{/if}-->
</div><!--col2-->
<div class="clear"></div>
</div><!--pagejc-->
</div><!--content-->
</div><!--wrapper-->
{template vip2_footer}
<file_sep>/core/modules/tuan/model/sms/sms_chanyoo_class.php
<?php
/**
* 开源软件增值服务平台接口
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
class sms_chanyoo extends msm_sms_base {
var $url = '';
var $username = '';
var $password = '';
function sms_chanyoo($params) {
$this->__construct($params);
}
//构造函数,参数 param 为短信接口帐号
function __construct($params) {
parent::__construct($params);
$this->url = 'http://api.chanyoo.cn/gbk/interface/send_sms.aspx';
$this->set_account($params); //设置短信帐号
}
//设置短信帐号
function set_account($params) {
if(!$params['sms_chanyoo_username']) redirect('tuan_sms_id_empty');
if(!$params['sms_chanyoo_password']) redirect('tuan_sms_password_empty');
$this->username = $params['sms_chanyoo_username'];
$this->password = $params['<PASSWORD>'];
if($params['customstr']) $this->customstr = $params['customstr'];
if($params['url']) $this->url = $params['url'];
}
//发送短信息
function send($mobile, $message) {
if(!$mobile) redirect('tuan_sms_mobile_empty');
if(!$message) redirect('tuan_sms_content_empty');
if(strtolower($this->global['charset']) != 'utf-8' && $this->global['in_ajax']) {
$this->loader->lib('chinese', NULL, FALSE);
$CHS = new ms_chinese('utf-8', $this->global['charset']);
$message = $message ? $CHS->Convert($message) : '';
}
$params = $this->_createParam($mobile, $message);
return $this->_send($params);
}
function _createParam($mobile, $message) {
if(strtolower($this->global['charset']) != 'gb2312') {
$this->loader->lib('chinese', NULL, FALSE);
$CHS = new ms_chinese($this->global['charset'], 'gb2312');
$mobile = $CHS->Convert($mobile);
$message = $CHS->Convert($message);
}
$id = $this->_create_id();
$params = array (
'username' => $this->username,
'password' => $<PASSWORD>,
'receiver' => $mobile,
'content' => $message,
'sendtime' => '',
);
return $params;
}
//生成一个短信发送的句柄id
function _create_id() {
return $this->username . '_' . $this->global['timestamp'] . '_' . mt_rand(10000000,99999999);
}
//通过http协议的post短信息,并返回api的反馈信息(写入log文件,以便调试)
function _send($data) {
$url = parse_url($this->url);
if (!isset($url['port'])) {
$url['port'] = "";
}
if (!isset($url['query'])) {
$url['query'] = "";
}
$encoded = "";
foreach($data as $k => $v) {
$encoded .= ($encoded ? "&" : "");
$encoded .= rawurlencode($k)."=".rawurlencode($v);
}
$fp = @fsockopen($url['host'], $url['port'] ? $url['port'] : 80);
if (!$fp) {
$this->_log_result("Failed to open socket to $url[host]");
return 0;
}
fputs($fp, sprintf("POST %s%s%s HTTP/1.0\n", $url['path'], $url['query'] ? "?" : "", $url['query']));
fputs($fp, "Host: $url[host]\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\n");
fputs($fp, "Content-length: " . strlen($encoded) . "\n");
fputs($fp, "Connection: close\n\n");
fputs($fp, "$encoded\n");
$line = fgets($fp, 1024);
if (!eregi("^HTTP/1\.. 200", $line)) {
$this->_log_result($line);
return 0;
}
$results = ""; $inheader = 1;
while(!feof($fp)) {
$line = fgets($fp, 1024);
if ($inheader && ($line == "\n" || $line == "\r\n")) {
$inheader = 0;
}
if (!$inheader) {
$results .= $line;
}
}
fclose($fp);
$results = trim($results);
$xml = simplexml_load_string($results);
if ($xml->result >= 0)
{
return true;
}
else
{
$this->_log_result($encoded, $results); //记录发送不成功的返回信息
return false;
}
}
// 日志消息,把返回的参数记录下来
function _log_result($params, $word='') {
if($fp = @fopen(MUDDER_ROOT . 'data' . DS . 'logs' . DS . "dysms_log.php", "a")) {
flock($fp, LOCK_EX) ;
fwrite($fp,"<?php exit();?>\r\ndate:".strftime("%Y-%m-%d %H:%M:%S", $this->global['timestamp'])."\r\n".$word."\r\n".$params."\r\n");
flock($fp, LOCK_UN);
fclose($fp);
}
}
}
?><file_sep>/core/modules/tuan/model/api_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_tuan_api extends ms_model {
var $model_flag = 'tuan';
function __construct() {
parent::__construct();
$this->model_flag = 'tuan';
$this->modcfg = $this->variable('config');
}
}
?><file_sep>/core/modules/about/model/about_class.php
<?php
/**
* @author 轩<<EMAIL>>
* @copyright (c)2009-2011 风格店铺
* @copyright 风格店铺(www.cmsky.org)
*/
class msm_about extends ms_model {
var $table = 'dbpre_about_page';
var $key = 'apid';
var $model_flag = 'about';
function __construct() {
parent::__construct();
$this->model_flag = 'about';
$this->init_field();
$this->modcfg = $this->variable('config');
}
function msm_about() {
$this->__construct();
}
function init_field() {
$this->add_field('apid,city_id,groupname,pname,mark,templates,title,keywords,description,content,enabled');
$this->add_field_fun('apid,city_id', 'intval');
$this->add_field_fun('groupname,pname,mark,templates,title,keywords,description,enabled', '_T');
$this->add_field_fun('content', '_HTML');
}
function read_mark($info) {
$this->db->from($this->table);
$this->db->where('mark', $info);
$result = $this->db->get_one();
return $result;
}
function get_list($select,$where,$orderby,$start,$offset) {
$result = array(0,'');
$this->db->from($this->table);
$this->db->where($where);
if($result[0] = $this->db->count()) {
$this->db->sql_roll_back('from,where');
$this->db->select($select);
$this->db->limit($start,$offset);
$this->db->order_by($orderby);
$result[1] = $this->db->get();
}
return $result;
}
function group_list() {
$this->db->from($this->table);
$this->db->select('groupname');
$this->db->select('groupname', 'count', 'COUNT(?)');
$this->db->group_by('groupname');
if(!$q = $this->db->get()) return;
$result = array();
while($v=$q->fetch_array()) {
$result[$v['groupname']] = $v['count'];
}
return $result;
}
function save($post, $apid = NULL) {
$edit = $apid != null;
if($this->modcfg['post_filter']) {
$W =& $this->loader->model('word');
$post['content'] = $W->filter($post['content']);
}
if($edit) {
if(!$detail = $this->read($apid)) redirect('about_empty');
}
$apid = parent::save($post, $apid);
return $apid;
}
function delete($ids) {
$ids = parent::get_keyids($ids);
parent::delete($ids);
$this->write_cache();
}
function check_post(& $post) {
if(!$post['pname']) redirect('about_post_pname_empty');
if(!$post['groupname']) redirect('aboutcp_page_groupname_empty');
}
function write_cache() {
$this->db->from($this->table);
$this->db->select('apid,city_id,groupname,pname,mark,templates,title,keywords,description,enabled');
$this->db->order_by('apid');
$result = array();
if($r = $this->db->get()) {
while($v=$r->fetch_array()) {
$result[$v['apid']] = $v;
}
$r->free_result();
}
write_cache('page', arrayeval($result), $this->model_flag);
}
}
?><file_sep>/core/lib/chinese.php
<?php
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
define ( 'MUDDER_TABLESDIR', MUDDER_CORE . 'lib' . DS . 'tables' . DS );
class ms_chinese {
var $PINYIN_table = array ();
var $unicode_table = array ();
var $ctf;
var $SourceText = "";
var $config = array (
'codetable_dir' => MUDDER_TABLESDIR,
'source_lang' => '',
'target_lang' => '',
'GBtoBIG5_table' => 'gb-big5.table',
'BIG5toGB_table' => 'big5-gb.table',
'GBtoPINYIN_table' => 'gb-pinyin.table',
'GBtoUnicode_table' => 'gb-unicode.table',
'BIG5toUnicode_table' => 'big5-unicode.table',
'CHtoPINYIN_table' => 'ch-pinyin.table'
);
function __construct($source_lang, $target_lang) {
$search = array (
"utf-8",
"gbk"
);
$replace = array (
"utf8",
"gb2312"
);
$this->config ['source_lang'] = strtoupper ( str_replace ( $search, $replace, $source_lang ) );
$this->config ['target_lang'] = strtoupper ( str_replace ( $search, $replace, $target_lang ) );
}
function ms_chinese($source_lang, $target_lang) {
$this->__construct ( $source_lang, $target_lang );
}
function Convert($source_string = '') {
if ($source_string == '') {
return $source_string;
}
$this->SourceText = $source_string;
if ($this->config ['source_lang'] == 'BIG5' && $this->config ['target_lang'] == 'GB2312') {
$lib_convert = false;
} elseif ($this->config ['source_lang'] == 'GB2312' && $this->config ['target_lang'] == 'BIG5') {
$lib_convert = false;
} elseif ($this->config ['target_lang'] != 'PINYIN') {
$lib_convert = false;
} else {
$lib_convert = true;
}
if (function_exists ( 'mb_convert_encoding' ) && $lib_convert) {
return mb_convert_encoding ( $this->SourceText, $this->config ['source_lang'], $this->config ['target_lang'] );
}
if (function_exists ( 'iconv' ) && $lib_convert) {
return iconv ( $this->config ['source_lang'], $this->config ['target_lang'] . "//IGNORE", $this->SourceText );
}
$this->OpenTable ();
if (($this->config ['source_lang'] == "GB2312" || $this->config ['source_lang'] == "BIG5") && ($this->config ['target_lang'] == "GB2312" || $this->config ['target_lang'] == "BIG5")) {
return $this->GB2312toBIG5 ();
}
if (($this->config ['source_lang'] == "GB2312" || $this->config ['source_lang'] == "BIG5") || $this->config ['source_lang'] == "UTF8"&& $this->config ['target_lang'] == "PINYIN") {
return $this->CHStoPINYIN ();
}
if (($this->config ['source_lang'] == "GB2312" || $this->config ['source_lang'] == "BIG5" || $this->config ['source_lang'] == "UTF8") && ($this->config ['target_lang'] == "UTF8" || $this->config ['target_lang'] == "GB2312" || $this->config ['target_lang'] == "BIG5")) {
return $this->CHStoUTF8 ();
}
if (($this->config ['source_lang'] == "GB2312" || $this->config ['source_lang'] == "BIG5") && $this->config ['target_lang'] == "UNICODE") {
return $this->CHStoUNICODE ();
}
}
function _hex2bin($hexdata) {
$bindata = '';
for($i = 0; $i < strlen ( $hexdata ); $i += 2)
$bindata .= chr ( hexdec ( substr ( $hexdata, $i, 2 ) ) );
return $bindata;
}
/*
* 映射表函数
*
*
*/
function OpenTable() {
//原始编码为GB2312
if ($this->config ['source_lang'] == "GB2312") {
//GB2312->BIG5
if ($this->config ['target_lang'] == "BIG5") {
$this->ctf = fopen ( $this->config ['codetable_dir'] . $this->config ['GBtoBIG5_table'], "r" );
if (is_null ( $this->ctf )) {
echo 'Fail to open coverting table!';
exit ();
}
}
//GB2312->PINYIN
if ($this->config ['target_lang'] == "PINYIN") {
$tmp = @file ( $this->config ['codetable_dir'] . $this->config ['GBtoPINYIN_table'] );
if (! $tmp) {
echo 'Fail to open coverting table!';
exit ();
}
$i = 0;
for($i = 0; $i < count ( $tmp ); $i ++) {
$tmp1 = explode ( " ", $tmp [$i] );
$this->PINYIN_table [$i] = array (
$tmp1 [0],
$tmp1 [1]
);
}
}
//GB2312->UTF8
if ($this->config ['target_lang'] == "UTF8") {
$tmp = @file ( $this->config ['codetable_dir'] . $this->config ['GBtoUnicode_table'] );
if (! $tmp) {
echo 'Fail to convert encoding!';
exit ();
}
$this->unicode_table = array ();
while ( list ( $key, $value ) = each ( $tmp ) )
$this->unicode_table [hexdec ( substr ( $value, 0, 6 ) )] = substr ( $value, 7, 6 );
}
//GB2312->UNICODE
if ($this->config ['target_lang'] == "UNICODE") {
$tmp = @file ( $this->config ['codetable_dir'] . $this->config ['GBtoUnicode_table'] );
if (! $tmp) {
echo 'Fail to open coverting table!';
exit ();
}
$this->unicode_table = array ();
while ( list ( $key, $value ) = each ( $tmp ) )
$this->unicode_table [hexdec ( substr ( $value, 0, 6 ) )] = substr ( $value, 9, 4 );
}
}
//原始编码为BIG5
if ($this->config ['source_lang'] == "BIG5") {
//BIG5->GB2312
if ($this->config ['target_lang'] == "GB2312") {
$this->ctf = fopen ( $this->config ['codetable_dir'] . $this->config ['BIG5toGB_table'], "r" );
if (is_null ( $this->ctf )) {
echo 'Fail to open coverting table!';
exit ();
}
}
//BIG5->UTF8
if ($this->config ['target_lang'] == "UTF8") {
$tmp = @file ( $this->config ['codetable_dir'] . $this->config ['BIG5toUnicode_table'] );
if (! $tmp) {
echo 'Fail to open coverting table!';
exit ();
}
$this->unicode_table = array ();
while ( list ( $key, $value ) = each ( $tmp ) )
$this->unicode_table [hexdec ( substr ( $value, 0, 6 ) )] = substr ( $value, 7, 6 );
}
//BIG5->UNICODE
if ($this->config ['target_lang'] == "UNICODE") {
$tmp = @file ( $this->config ['codetable_dir'] . $this->config ['BIG5toUnicode_table'] );
if (! $tmp) {
echo 'Fail to open coverting table!';
exit ();
}
$this->unicode_table = array ();
while ( list ( $key, $value ) = each ( $tmp ) )
$this->unicode_table [hexdec ( substr ( $value, 0, 6 ) )] = substr ( $value, 9, 4 );
}
//BIG5->PINYIN
if ($this->config ['target_lang'] == "PINYIN") {
$tmp = @file ( $this->config ['codetable_dir'] . $this->config ['GBtoPINYIN_table'] );
if (! $tmp) {
echo 'Fail to open coverting table!';
exit ();
}
$i = 0;
for($i = 0; $i < count ( $tmp ); $i ++) {
$tmp1 = explode ( " ", $tmp [$i] );
$this->PINYIN_table [$i] = array (
$tmp1 [0],
$tmp1 [1]
);
}
}
}
//原始编码为UTF8
if ($this->config ['source_lang'] == "UTF8") {
//UTF8->GB2312
if ($this->config ['target_lang'] == "GB2312") {
$tmp = @file ( $this->config ['codetable_dir'] . $this->config ['GBtoUnicode_table'] );
if (! $tmp) {
echo 'Fail to open coverting table!';
exit ();
}
$this->unicode_table = array ();
while ( list ( $key, $value ) = each ( $tmp ) )
$this->unicode_table [hexdec ( substr ( $value, 7, 6 ) )] = substr ( $value, 0, 6 );
}
//UTF8->BIG5
if ($this->config ['target_lang'] == "BIG5") {
$tmp = @file ( $this->config ['codetable_dir'] . $this->config ['BIG5toUnicode_table'] );
if (! $tmp) {
echo 'Fail to open coverting table!';
exit ();
}
$this->unicode_table = array ();
while ( list ( $key, $value ) = each ( $tmp ) )
$this->unicode_table [hexdec ( substr ( $value, 7, 6 ) )] = substr ( $value, 0, 6 );
}
}
//UTF8->PINYIN
if ($this->config ['target_lang'] == "PINYIN") {
$tmp = @file ( $this->config ['codetable_dir'] . $this->config ['CHtoPINYIN_table'] );
if (! $tmp) {
echo 'Fail to open coverting table!';
exit ();
}
$i = 0;
for($i = 0; $i < count ( $tmp ); $i ++) {
$tmp1 = explode ( " ", $tmp [$i] );
$this->PINYIN_table [$i] = array (
$tmp1 [0],
$tmp1 [1]
);
}
}
}
function OpenFile($position, $isHTML = false) {
$tempcontent = @file ( $position );
if (! $tempcontent) {
echo 'Fail to open file!';
exit ();
}
$this->SourceText = implode ( "", $tempcontent );
if ($isHTML) {
$this->SourceText = eregi_replace ( "charset=" . $this->config ['source_lang'], "charset=" . $this->config ['target_lang'], $this->SourceText );
$this->SourceText = eregi_replace ( "\n", "", $this->SourceText );
$this->SourceText = eregi_replace ( "\r", "", $this->SourceText );
}
}
function SiteOpen($position) {
$tempcontent = @file ( $position );
if (! $tempcontent) {
echo 'Fail to open file!';
exit ();
}
$this->SourceText = implode ( "", $tempcontent );
$this->SourceText = eregi_replace ( "charset=" . $this->config ['source_lang'], "charset=" . $this->config ['target_lang'], $this->SourceText );
}
function setvar($parameter, $value) {
if (! trim ( $parameter ))
return $parameter;
$this->config [$parameter] = $value;
}
function CHSUtoUTF8($c) {
$str = "";
if ($c < 0x80) {
$str .= $c;
}
else if ($c < 0x800) {
$str .= (0xC0 | $c >> 6);
$str .= (0x80 | $c & 0x3F);
}
else if ($c < 0x10000) {
$str .= (0xE0 | $c >> 12);
$str .= (0x80 | $c >> 6 & 0x3F);
$str .= (0x80 | $c & 0x3F);
}
else if ($c < 0x200000) {
$str .= (0xF0 | $c >> 18);
$str .= (0x80 | $c >> 12 & 0x3F);
$str .= (0x80 | $c >> 6 & 0x3F);
$str .= (0x80 | $c & 0x3F);
}
return $str;
}
function CHStoUTF8() {
if ($this->config ["source_lang"] == "BIG5" || $this->config ["source_lang"] == "GB2312") {
$ret = "";
while ( $this->SourceText ) {
if (ord ( substr ( $this->SourceText, 0, 1 ) ) > 127) {
if ($this->config ["source_lang"] == "BIG5") {
$utf8 = $this->CHSUtoUTF8 ( hexdec ( $this->unicode_table [hexdec ( bin2hex ( substr ( $this->SourceText, 0, 2 ) ) )] ) );
}
if ($this->config ["source_lang"] == "GB2312") {
$utf8 = $this->CHSUtoUTF8 ( hexdec ( $this->unicode_table [hexdec ( bin2hex ( substr ( $this->SourceText, 0, 2 ) ) ) - 0x8080] ) );
}
for($i = 0; $i < strlen ( $utf8 ); $i += 3)
$ret .= chr ( substr ( $utf8, $i, 3 ) );
$this->SourceText = substr ( $this->SourceText, 2, strlen ( $this->SourceText ) );
}
else {
$ret .= substr ( $this->SourceText, 0, 1 );
$this->SourceText = substr ( $this->SourceText, 1, strlen ( $this->SourceText ) );
}
}
$this->unicode_table = array ();
$this->SourceText = "";
return $ret;
}
if ($this->config ["source_lang"] == "UTF8") {
$out = "";
$len = strlen ( $this->SourceText );
$i = 0;
while ( $i < $len ) {
$c = ord ( substr ( $this->SourceText, $i ++, 1 ) );
switch ($c >> 4) {
case 0 :
case 1 :
case 2 :
case 3 :
case 4 :
case 5 :
case 6 :
case 7 :
// 0xxxxxxx
$out .= substr ( $this->SourceText, $i - 1, 1 );
break;
case 12 :
case 13 :
// 110x xxxx 10xx xxxx
$char2 = ord ( substr ( $this->SourceText, $i ++, 1 ) );
$char3 = $this->unicode_table [(($c & 0x1F) << 6) | ($char2 & 0x3F)];
if ($this->config ["target_lang"] == "GB2312")
$out .= $this->_hex2bin ( dechex ( $char3 + 0x8080 ) );
if ($this->config ["target_lang"] == "BIG5")
$out .= $this->_hex2bin ( $char3 );
break;
case 14 :
// 1110 xxxx 10xx xxxx 10xx xxxx
$char2 = ord ( substr ( $this->SourceText, $i ++, 1 ) );
$char3 = ord ( substr ( $this->SourceText, $i ++, 1 ) );
$char4 = $this->unicode_table [(($c & 0x0F) << 12) | (($char2 & 0x3F) << 6) | (($char3 & 0x3F) << 0)];
if ($this->config ["target_lang"] == "GB2312")
$out .= $this->_hex2bin ( dechex ( $char4 + 0x8080 ) );
if ($this->config ["target_lang"] == "BIG5")
$out .= $this->_hex2bin ( $char4 );
break;
}
}
return $out;
}
}
function CHStoUNICODE() {
$utf = "";
while ( $this->SourceText ) {
if (ord ( substr ( $this->SourceText, 0, 1 ) ) > 127) {
if ($this->config ["source_lang"] == "GB2312")
$utf .= "&#x" . $this->unicode_table [hexdec ( bin2hex ( substr ( $this->SourceText, 0, 2 ) ) ) - 0x8080] . ";";
if ($this->config ["source_lang"] == "BIG5")
$utf .= "&#x" . $this->unicode_table [hexdec ( bin2hex ( substr ( $this->SourceText, 0, 2 ) ) )] . ";";
$this->SourceText = substr ( $this->SourceText, 2, strlen ( $this->SourceText ) );
} else {
$utf .= substr ( $this->SourceText, 0, 1 );
$this->SourceText = substr ( $this->SourceText, 1, strlen ( $this->SourceText ) );
}
}
return $utf;
}
function GB2312toBIG5() {
$max = strlen ( $this->SourceText ) - 1;
for($i = 0; $i < $max; $i ++) {
$h = ord ( $this->SourceText [$i] );
if ($h >= 160) {
$l = ord ( $this->SourceText [$i + 1] );
if ($h == 161 && $l == 64) {
$gb = " ";
} else {
fseek ( $this->ctf, ($h - 160) * 510 + ($l - 1) * 2 );
$gb = fread ( $this->ctf, 2 );
}
$this->SourceText [$i] = $gb [0];
$this->SourceText [$i + 1] = $gb [1];
$i ++;
}
}
fclose ( $this->ctf );
$result = $this->SourceText;
$this->SourceText = "";
return $result;
}
function PINYINSearch($num) {
if ($num > 0 && $num < 160) {
return chr ( $num );
}
elseif ($num < - 20319 || $num > - 10247) {
return "";
} else {
for($i = count ( $this->PINYIN_table ) - 1; $i >= 0; $i --) {
if ($this->PINYIN_table [$i] [1] <= $num)
break;
}
return $this->PINYIN_table [$i] [0];
}
}
function CHStoPINYIN() {
if ($this->config ['source_lang'] == "BIG5") {
$this->ctf = fopen ( $this->config ['codetable_dir'] . $this->config ['BIG5toGB_table'], "r" );
if (is_null ( $this->ctf )) {
echo 'Fail to open file!';
exit ();
}
$this->SourceText = $this->GB2312toBIG5 ();
$this->config ['target_lang'] = "PINYIN";
}
$ret = array ();
$ri = 0;
for($i = 0; $i < strlen ( $this->SourceText ); $i ++) {
$p = ord ( substr ( $this->SourceText, $i, 1 ) );
if ($p > 160) {
$q = ord ( substr ( $this->SourceText, ++ $i, 1 ) );
$p = $p * 256 + $q - 65536;
}
$ret [$ri] = $this->PINYINSearch ( $p );
$ri = $ri + 1;
}
$this->SourceText = "";
$this->PINYIN_table = array ();
return implode ( " ", $ret );
}
}
<file_sep>/core/modules/party/admin/templates/comment.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="post" action="admincp.php?action=<?=$action?>&file=<?=$file?>" name="myform">
<input type="hidden" name="partyid" value="<?=$partyid?>" />
<div class="space">
<div class="subtitle">活动讨论:<?=$party['subject']?></div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr class="altbg1">
<td width="25"> <a href="javascript:allchecked();">选</a></td>
<td width="*">提问者</td>
<td width="200">问题</td>
<td width="200">回复</td>
</tr>
<?foreach ($list as $val):?>
<tr>
<td><input type="checkbox" name="commentids[]" value="<?=$val['commentid']?>" /></td>
<td><a href="<?=url("space/index/suid/$val[uid]")?>" target="_blank"><?=$val['username']?></a><br /><?=date('Y-m-d H:i',$val[dateline])?></td>
<td><textarea name="comment[<?=$val['commentid']?>][message]" rows="3" style="width:250px;"><?=$val['message']?></textarea></td>
<td><textarea name="comment[<?=$val['commentid']?>][reply]" rows="3" style="width:250px;"><?=$val['reply']?></textarea></td>
</tr>
<?endforeach;?>
<?if (!$total):?>
<tr>
<td colspan="5">暂无信息。</td>
</tr>
<?endif;?>
</table>
<center>
<?if ($total):?>
<input type="hidden" name="op" value="<?=$op?>" />
<input type="hidden" name="partyid" value="<?=$partyid?>" />
<input type="hidden" name="dosubmit" value="yes" />
<button type="button" class="btn" onclick="submit_form('myform','op','edit',null,null,null);">提交编辑</button>
<button type="button" class="btn" onclick="submit_form('myform','op','delete', null, null,'applyids[]');">删除所选</button>
<?endif;?>
<button type="button" class="btn" onclick="document.location='<?=url("modoer/admincp/action/$action/file/list")?>'"/> 返 回 </button>
</center>
</div>
</form>
</div><file_sep>/core/modules/item/admin/tag_list.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
$op = $_POST['op'] ? $_POST['op'] : $_GET['op'];
$TAG =& $_G['loader']->model(MOD_FLAG.':tag');
switch($op) {
case 'new':
//Loader中的方法,加载form.php
$_G['loader']->helper('form','item');
$admin->tplname = cptpl('tag_add', MOD_FLAG);
break;
case 'add':
$groupid = $_POST['tgid'];
$tags = $_POST['tagname'];
$TAG->add1(8, $groupid, $tags);
redirect('global_op_succeed', get_forward(cpurl($module,$act),1));
break;
case 'edit':
if($_POST['dosubmit']) {
$tagid = (int) $_POST['tagid'];
$TAG->edit($_POST['tagname'], $tagid,$_POST['sort1'], $_POST['merge']);
redirect('global_op_succeed', get_forward(cpurl($module,$act),1));
} else {
$tagid = (int) $_GET['tagid'];
if(!$detail = $TAG->read($tagid)) {
redirect('item_tag_empty_tagid');
}
$admin->tplname = cptpl('tag_save', MOD_FLAG);
}
break;
case 'close':
$TAG->close($_POST['tagids'], (int)$_POST['closed']);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'delete':
$TAG->delete_tagids($_POST['tagids']);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
default:
$op='list';
$_G['loader']->helper('form','item');
//联系查询
$TAG->db->join ( $TAG->table, 'a.tgid', 'dbpre_taggroup', 's.tgid', MF_DB_LJ );
if (! $admin->is_founder)
$TAG->db->where ( 'a.city_id', $_CITY ['aid'] );
if ($total = $TAG->db->count ()) {
$TAG->db->sql_roll_back ( 'from,where' );
if(!empty($_GET['sort1'])) $TAG->db->where ( 'sort1',$_GET['sort1']);
$TAG->db->order_by ( 'a.tagid asc');
$TAG->db->limit ( get_start ( $_GET ['page'], $_GET ['offset'] ), $_GET ['offset'] );
$TAG->db->select ( 'a.*,s.name ' );
$list = $TAG->db->get ();
$multipage = multi ( $total, $_GET ['offset'], $_GET ['page'], cpurl ( $module, $act, 'list', $_GET ) );
}
$admin->tplname = cptpl('tag_list', MOD_FLAG);
}
?><file_sep>/core/lib/database.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
define ( "MF_DB_J", 'JOIN' );
define ( "MF_DB_LJ", 'LEFT JOIN' );
define ( "MF_DB_RJ", 'RIGHT JOIN' );
$_G ['loader']->lib ( 'mysql', NULL, FALSE );
class ms_database extends ms_mysql {
//所支持的组合子句集合
var $var_fields = array ('set', 'select', 'from', 'where', 'group_by', 'having', 'order_by', 'limit' );
var $table = '';
var $where = '';
var $set = '';
var $select = '';
var $from = '';
var $group_by = '';
var $having = '';
var $order_by = '';
var $limit = '';
//缓存
var $cache_table = '';
var $cache_where = '';
var $cache_select = '';
var $cache_from = '';
var $cache_group_by = '';
var $cache_having = '';
var $cache_order_by = '';
var $cache_limit = '';
function ms_database(& $dns) {
$this->__construct ( $dns );
}
function __construct(& $dns) {
parent::__construct ( $dns );
$this->connect ();
}
// 获取一个表名
function get_table($tablename) {
return str_replace ( "dbpre_", $this->dns ['dbpre'], $tablename );
}
// 设置SQL中的from子句
function from($tablename, $asname = null, $sql = null) {
$this->from = $this->get_table ( $tablename ) . ($asname ? " $asname" : '');
if ($sql)
$this->from .= ' ' . $sql;
return $this;
}
// 关联2个表
function join($table1, $key1, $table2, $key2, $jointype = 'JOIN') {
if (! preg_match ( "/^([a-z]+)\.([a-z0-9_]+)$/i", $key1, $match1 ))
redirect ( '无效的关联表字段。' );
if (! preg_match ( "/^([a-z]+)\.([a-z0-9_]+)$/i", $key2, $match2 ))
redirect ( '无效的关联表字段。' );
$table1 = $this->get_table ( $table1 );
$table2 = $this->get_table ( $table2 );
$asname1 = $match1 [1];
$asname2 = $match2 [1];
$key1 = $this->_ck_field ( $match1 [2] );
$key2 = $this->_ck_field ( $match2 [2] );
$this->from = sprintf ( "%s %s %s %s %s ON (%s.%s = %s.%s)", $table1, $asname1, $jointype, $table2, $asname2, $asname1, $key1, $asname2, $key2 );
return $this;
}
/*
* function:关联第3,4..个表
* $together_key:主表关联字段
* $table:附表
* $key:附表关联字段
* $jointype:连接类型
* $this->db->join_together('s.sid', 'dbpre_subject_shops', 'b.sid', 'LEFT JOIN');
*
*/
function join_together($together_key, $table, $key, $jointype = 'JOIN') {
if (! preg_match ( "/^([a-z]+)\.([a-z0-9_]+)$/i", $together_key, $match1 ))
redirect ( '无效的关联表字段。' );
if (! preg_match ( "/^([a-z]+)\.([a-z0-9_]+)$/i", $key, $match2 ))
redirect ( '无效的关联表字段。' );
$together_asname = $match1 [1];
$asname = $match2 [1];
$table = $this->get_table ( $table );
$together_key = $this->_ck_field ( $match1 [2] );
$key = $this->_ck_field ( $match2 [2] );
$this->from .= sprintf ( " %s %s %s ON (%s.%s = %s.%s)", $jointype, $table, $asname, $together_asname, $together_key, $asname, $key );
return $this;
}
// 设置查询字段
function select($fields, $asname = NULL, $fun = NULL) {
$split = $this->select ? ',' : '';
if (is_string ( $fields )) {
if ($fun) {
$fields = str_replace ( '?', $this->_ck_field ( $fields ), $fun );
} else {
$fields = $this->_ck_field ( $fields );
}
$select = $fields . ($asname ? (' AS ' . $this->_ck_field ( $asname )) : '');
$this->select .= $split . $select;
} elseif (is_array ( $fields )) {
foreach ( $fields as $key ) {
$this->select .= $split . $this->_ck_field ( $fields );
$split = ',';
}
}
return $this;
}
// 设置更新字段或插入字段数据
function set($key, $value = null) {
if (is_array ( $key )) {
foreach ( $key as $k => $v ) {
$this->set ( $k, $v );
}
} else {
$this->_ck_field ( $key );
$this->set [$key] = $this->_escape ( $value );
}
return $this;
}
// 设置更新2个字段值相同
function set_equal($key1, $key2) {
$this->_ck_field ( $key1 );
$this->_ck_field ( $key2 );
$this->set [$key1] = $key2;
return $this;
}
// 设置更新字段累加
function set_add($key, $value = 1) {
if (! $value)
return;
$this->_ck_field ( $key );
$this->set [$key] = $key . '+' . $this->_escape ( $value );
return $this;
}
// 设置更新字段减少
function set_dec($key, $value = 1) {
$this->_ck_field ( $key );
$this->set [$key] = $key . '-' . $this->_escape ( $value );
return $this;
}
// 直接使用SQL表示set的值
function set_src($key, $value) {
$this->set [$key] = $key . '-' . $value;
return $this;
}
// 设置查询字段,支持array(key,value);支持sql/前台查询语句;支持子查询语句
function where($key, $value = '', $split = 'AND') {
//支持数组方式(arry(key,value));支持函数调用.
if (is_array ( $key )) {
foreach ( $key as $k => $v ) {//array('where_in',array(1,2,3,4))
//$where['s.dzid']=array('where_not_equal',array(''));
if (is_array ( $v ) && count ( $v ) == 2 && is_array ( $v [1] )) {
$fun = $v [0];
$args = array_merge ( array ($k ), $v [1] );
call_user_func_array ( array (&$this, $fun ), $args );
} else {
$this->where ( $k, $v, $split );
}
}
} elseif ($key == '{sql}') {//sql/...
$this->_exp_where ( 'sql', $value, $split );
} elseif (is_array ( $value )) {//如果$value=1,2,3,4的形式
$this->where_in ( $key, $value, $split );
} else {
$where = $this->_ck_field ( $key ) . " = " . $this->_escape ( $value );
$this->where .= ($this->where ? " $split " : '') . $where;
}
return $this;
}
// 查询字段表达式,用户复杂的where子句
function where_exp($exp, $key, $value, $split = 'AND') {
if (is_array ( $value )) {
foreach ( $value as $_k => $val ) {
$value [$_k] = $this->_escape ( $val );
}
$value = implode ( ",", $value );
}
$where = sprintf ( str_replace ( " ? ", " %s ", $exp ), $this->_ck_field ( $key ), $value );
$this->where .= ($this->where ? " $split " : '') . $where;
return $this;
}
// 设置查询子句形式 field != 'value'
function where_not_equal($key, $value, $split = 'AND') {
$where = $this->_ck_field ( $key ) . " != " . $this->_escape ( $value );
$this->where .= ($this->where ? " $split " : '') . $where;
return $this;
}
// 设置查询子句形式 field >= 'value' 或 field > 'value'
function where_more($key, $value, $equal = 1, $split = 'AND') {
$mark = $equal ? '>=' : '>';
$where = $this->_ck_field ( $key ) . $mark . $this->_escape ( $value );
$this->where .= ($this->where ? " $split " : '') . $where;
return $this;
}
// 设置查询子句形式 field <= 'value' 或 field < 'value'
function where_less($key, $value, $equal = 1, $split = 'AND') {
$mark = $equal ? '<=' : '<';
$where = $this->_ck_field ( $key ) . $mark . $this->_escape ( $value );
$this->where .= ($this->where ? " $split " : '') . $where;
return $this;
}
// 设置查询子句形式 in
function where_in($key, $values, $split = 'AND') {
if (count ( $values ) == 0)
return;
if (count ( $values ) == 1) {
$this->where ( $key, $values [0], $split );
return;
}
foreach ( $values as $_key => $_val ) {
$values [$_key] = $this->_escape ( $_val );
}
$where = $this->_ck_field ( $key ) . " IN (" . implode ( ",", $values ) . ")";
$this->where .= ($this->where ? " $split " : '') . $where;
return $this;
}
// 设置查询子句形式 not in
function where_not_in($key, $values, $split = 'AND') {
foreach ( $values as $_key => $_val ) {
$values [$key] = $this->_escape ( $_val );
}
$where = $this->_ck_field ( $key ) . " NOT IN (" . implode ( ",", $values ) . ")";
$this->where .= ($this->where ? " $split " : '') . $where;
return $this;
}
// 设置查询子句形式 field between 100 and 200
function where_between_and($key, $begin, $end, $split = 'AND') {
$where = $this->_ck_field ( $key ) . " BETWEEN " . $this->_escape ( $begin ) . " AND " . $this->_escape ( $end );
$this->where .= ($this->where ? " $split " : '') . $where;
return $this;
}
// 设置查询子句形式 field like '100%'
function where_like($key, $value, $split = 'AND', $kh = '') {
$where = $this->_ck_field ( $key ) . " LIKE " . $this->_escape ( $value );
$this->where .= ($this->where ? " $split " : '') . ($kh == '(' ? '(' : '') . $where . ($kh == ')' ? ')' : '');
return $this;
}
// 设置查询子句形式 or
function where_or($key, $value) {
if (is_array ( $value )) {
$this->where_in ( $key, $value, 'OR' );
} else {
$where = $this->_ck_field ( $key ) . " = " . $this->_escape ( $value );
$this->where .= ($this->where ? ' OR ' : '') . $where;
}
return $this;
}
// 设置查询子句形式 CONCAT(field,field2) like '100%'
function where_concat_like($keys, $value, $split = 'AND', $kh = '') {
if (is_string ( $keys ))
$keys = explode ( ',', $keys );
foreach ( $keys as $k => $v ) {
$keys [$k] = $this->_ck_field ( trim ( $v ) );
}
$where = "CONCAT(" . implode ( ',', $keys ) . ") LIKE " . $this->_escape ( $value );
$this->where .= ($this->where ? " $split " : '') . ($kh == '(' ? '(' : '') . $where . ($kh == ')' ? ')' : '');
return $this;
}
// 设置exist子查询
function where_exist($sql, $split = 'AND', $kh = '') {
$where = 'exists(' . $this->get_table ( $sql ) . ')';
$this->where .= ($this->where ? " $split " : '') . ($kh == '(' ? '(' : '') . $where . ($kh == ')' ? ')' : '');
return $this;
}
// 设置exist子查询
function where_in_select($key, $sql, $split = 'AND', $kh = '') {
$where = $key . ' IN(' . $this->get_table ( $sql ) . ')';
$this->where .= ($this->where ? " $split " : '') . ($kh == '(' ? '(' : '') . $where . ($kh == ')' ? ')' : '');
}
// 设置group_by子句
function group_by($groups) {
if (is_array ( $groups )) {
foreach ( $groups as $key => $val ) {
$groups [$key] = $this->_ck_field ( $val );
}
$groupby = implode ( ',', $groups );
} elseif (is_string ( $groups )) {
$groupby = $this->_ck_field ( $groups );
}
$this->group_by .= ($this->group_by ? ',' : '') . $groupby;
return $this;
}
//设置having子句
function having($exp) {
$this->having = $exp;
}
// 设置order_by子句
function order_by($field, $type = 'ASC') {
if ($field == 'NULL') {
$this->order_by = "NULL";
return $this;
} elseif (is_string ( $field )) {
if (strpos ( $field, ' ' )) {
list ( $field, $type ) = explode ( ' ', $field );
}
$orderby = $this->_ck_field ( $field ) . ($type == 'DESC' ? (' ' . $type) : '');
} elseif (is_array ( $field )) {
$split = '';
foreach ( $field as $key => $val ) {
$orderby .= $split . $this->_ck_field ( $key ) . ($val == 'DESC' ? (' ' . $val) : '');
$split = ',';
}
}
$this->order_by .= ($this->order_by ? ',' : '') . $orderby;
return $this;
}
// 设置 limit 子句
function limit($start, $offset) {
$start = ( int ) $start;
$offset = ( int ) $offset;
if (! $start && ! $offset)
return;
if (! $start) {
$this->limit = "$offset";
}
if (! $offset) {
$offset = 10;
}
$this->limit = "$start, $offset";
return $this;
}
/*******************************************************/
/*******************查询*********************************/
/*******************************************************/
//直接快速查询方法
function get_easy($select, $from, $where = null, $group_by = null, $order_by = null, $limit = null) {
$this->select ( $select );
$this->from ( $from );
if ($where) {
foreach ( $where as $sk => $sv ) {
$this->where ( $sk, $sv );
}
}
if ($group_by)
$this->group_by ( $group_by );
if ($order_by)
$this->order_by ( $order_by [0], $order_by [1] );
if ($limit)
$this->limit ( $limit [0], $limit [1] );
return $this->get ();
}
//单条数据查询
function get_one($method = '', $clear_var = TRUE) {
if (! $this->limit)
$this->limit ( 0, 1 );
$SQL = $this->get_sql ( 0 );
$result = $this->query ( $SQL, $method );
$this->_cache_sql (); //sql cache
if ($clear_var) {
$this->clear ();
}
if ($result) {
return $result->fetch_array ();
} else {
return false;
}
}
//单个字段值查询
function get_value($clear_var = TRUE) {
$this->limit ( 0, 1 );
$SQL = $this->get_sql ( 0 );
$result = $this->query ( $SQL );
$this->_cache_sql (); //sql cache
if ($clear_var) {
$this->clear ();
}
return $result ? $result->result ( 0 ) : FALSE;
}
//返回数据条数
function count($clear_var = TRUE) {
$SQL = $this->get_sql ( 1 );
$row = $this->query ( $SQL );
$this->_cache_sql ();
if ($clear_var) {
$this->clear ();
}
return $row->result ( 0 );
}
//从组合的sql中获取mysql_result句柄
function get($method = '', $clear_var = TRUE) {
$SQL = $this->get_sql ( 0 );
//echo $SQL; echo "<br/>";
$result = $this->query ( $SQL, $method );
$this->_cache_sql (); //sql cache
if ($clear_var) {
$this->clear ();
}
return $result;
}
//构造查询(总数)SQL
function get_sql($get_count_sql = FALSE) {
foreach ( $this->var_fields as $v ) {
$$v = $v;
}
if (! $this->$from)
show_error ( lang ( 'global_sql_invalid', "FROM(Get)" ) );
$SQL = "SELECT " . ($get_count_sql ? "COUNT(*)" : ($this->$select ? $this->$select : "*")) . " FROM " . $this->$from . ($this->$where ? " WHERE " . $this->where : "") . ($this->$group_by ? " GROUP BY " . $this->$group_by : "") . ($this->$having ? " HAVING " . $this->$having : "") . ($this->$order_by ? " ORDER BY " . $this->$order_by : "") . ($get_count_sql ? '' : ($this->$limit ? " LIMIT " . $this->$limit : ""));
//echo $SQL;
// echo "</br>";
return $SQL;
}
/*******************************************************/
/*******************增加、删除、修改*********************/
/*******************************************************/
//插入/替换表操作
function insert($replace = FALSE, $clear_var = TRUE) {
$SQL = $this->insert_sql ( $replace, 0 );
// return $SQL;
$this->exec ( $SQL );
$this->_cache_sql ();
if ($clear_var) {
$this->clear ();
}
}
//更新表数据
function replace($clear_var = TRUE) {
$SQL = $this->insert_sql ( true, 0 );
$this->exec ( $SQL );
$this->_cache_sql ();
if ($clear_var) {
$this->clear ();
}
}
//更细数据
function update($clear_var = TRUE) {
$SQL = $this->insert_sql ( 0, 1 );
$this->exec ( $SQL, 'unbuffer' );
$this->_cache_sql ();
if ($clear_var) {
$this->clear ();
}
}
//自由执行插入操作
function edit_easy($sql,$clear_var = TRUE) {
$this->exec ( $sql, 'unbuffer' );
$this->_cache_sql ();
if ($clear_var) {
$this->clear ();
}
}
//组合一个插入sql
function insert_sql($replace = FALSE, $update = FALSE) {
foreach ( $this->var_fields as $v ) {
$$v = $v;
}
//表不存在
if (empty ( $this->$from ))
show_error ( lang ( 'global_sql_invalid', 'FROM(insert)' ) );
if (empty ( $this->$set ))
show_error ( lang ( 'global_sql_invalid', 'SET(insert)' ) );
$split = $setsql = '';
foreach ( $this->$set as $key => $val ) {
$setsql .= $split . $key . '=' . $val;
$split = ',';
}
if ($update) {
$SQL = "UPDATE " . $this->$from . " SET " . $setsql . ($this->$where ? " WHERE " . $this->$where : "");
} else {
$SQL = ($replace ? "REPLACE " : "INSERT ") . $this->$from . " SET " . $setsql;
}
//echo $SQL;
//echo "</br>";
return $SQL;
}
//执行删除操作
function delete($clear_var = TRUE) {
$SQL = $this->delete_sql ();
$this->exec ( $SQL );
$this->_cache_sql ();
if ($clear_var) {
$this->clear ();
}
}
//组合成一个删除sql
function delete_sql() {
foreach ( $this->var_fields as $v ) {
$$v = $v;
}
if (! $this->$from)
show_error ( lang ( 'global_sql_invalid', "FROM(delete)" ) );
$SQL = "DELETE FROM " . $this->$from . ($this->$where ? " WHERE " . $this->$where : "");
return $SQL;
}
//清空一个表
function clear_table() {
if (! $this->$from)
show_error ( lang ( 'global_sql_invalid', 'FROM(Clear Table)' ) );
$this->db->exec ( "TRUNCATE TABLE " . $this->$from );
}
//删除一个表
function drop_table() {
if (! $this->$from)
show_error ( lang ( 'global_sql_invalid', 'FROM(Dorp Table)' ) );
$this->db->exec ( "DROP TABLE IF EXISTS " . $this->$from );
}
//清理当前的sql个子句内容
function clear($name = 'ALL') {
if ($name == 'ALL') {
foreach ( $this->var_fields as $v ) {
$this->$v = '';
}
} elseif (isset ( $name [$this->var_fields] )) {
$this->$name = '';
}
}
//SQL代码回滚,将在缓存的SQL重新设置成当前有效的SQL,支持回滚部分参数
function sql_roll_back($vars = null) {
$arr = $vars ? (is_array ( $vars ) ? $vars : explode ( ',', $vars )) : $this->var_fields;
foreach ( $arr as $v ) {
$n = 'cache_' . $v;
$this->$v = $this->$n;
}
return $this;
}
//特殊含义的sql解析
function _exp_where($exp, $value, $split) {
$pattern_arr = array ("/ union /i", "/ select /i", "/ update /i", "/ outfile /i" );
$where = '';
switch ($exp) {
case 'sql' :
foreach ( $pattern_arr as $p )
if (preg_match ( $p, $value ))
return;
$where = $value;
break;
}
if (! $where)
return;
$this->where .= ($this->where ? " $split " : '') . $where;
}
//转换插入sql的值
function _escape($str) {
switch (gettype ( $str )) {
case 'string' :
$str = "'" . $this->_escape_str ( $str ) . "'";
break;
case 'boolean' :
$str = ($str === FALSE) ? 0 : 1;
break;
default :
$str = ($str === NULL) ? 'NULL' : $str;
break;
}
return $str;
}
//缓存SQL各子句数据
function _cache_sql($clear = FALSE) {
foreach ( $this->var_fields as $v ) {
$n = 'cache_' . $v;
$this->$n = $this->$v;
if ($clear)
$this->$v = '';
}
}
/*****************************************************************/
//单条数据查询
function _get_one($sql,$method = '', $clear_var = TRUE) {
if (! $this->limit)
$this->limit ( 0, 1 );
$result = $this->query ( $sql, $method );
if ($result) {
return $result->fetch_array ();
} else {
return false;
}
}
}
<file_sep>/core/modules/about/page.php
<?php
/**
* @author 轩<<EMAIL>>
* @copyright (c)2009-2011 风格店铺
* @copyright 风格店铺(www.cmsky.org)
*/
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'about');
$I =& $_G['loader']->model(MOD_FLAG.':about');
$info = _get('info', null, '_T');
$urlpath = array();
if(!$info) {
location(url("about/page/info/".$MOD['page']));
} else {
$detail = $I->read_mark($info);
$urlpath[] = url_path($detail['pname'], url("about/page/info/".$info));
$_HEAD['title'] = $detail['title'];
$_HEAD['keywords'] = $detail['keywords'];
$_HEAD['description'] = $detail['description'];
include template($detail['templates']);
}
?><file_sep>/static/images/msweb/left.js
// JavaScript Document
function life(i){
switch(i){
case 11:
document.getElementById("life11").style.display="block";
document.getElementById("life12").style.display="none";
document.getElementById("life13").style.display="none";
document.getElementById("lifebg11").className="ss_mainc31";
document.getElementById("lifebg12").className="ss_mainc32";
document.getElementById("lifebg13").className="ss_mainc32";
break;
case 12:
document.getElementById("life11").style.display="none";
document.getElementById("life12").style.display="block";
document.getElementById("life13").style.display="none";
document.getElementById("lifebg11").className="ss_mainc32";
document.getElementById("lifebg12").className="ss_mainc31";
document.getElementById("lifebg13").className="ss_mainc32";
break;
case 13:
document.getElementById("life11").style.display="none";
document.getElementById("life12").style.display="none";
document.getElementById("life13").style.display="block";
document.getElementById("lifebg11").className="ss_mainc32";
document.getElementById("lifebg12").className="ss_mainc32";
document.getElementById("lifebg13").className="ss_mainc31";
break;
}
}
<file_sep>/core/modules/tuan/nav.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
define ( 'SCRIPTNAV', 'tuan' );
$T = & $_G ['loader']->model ( 'tuan:tuandh' );
// 加载类别信息
$catid = ( int ) $_GET ['catid'];
if($catid==0) $catid=1;
//构造导航
$cat = $_G ['loader']->variable ( 'category', 'tuan' );
$urlpath [] = url_path ( '无锡团购导航', url ( "tuan/nav/" ) );
if ($paid) {
$urlpath [] = url_path ( $cat [$paid] ['name'], url ( "tuan/nav/catid/$pid/aid/$paid" ) );
}
if ($paid != $catid) {
$urlpath [] = url_path ( $area [$aid] ['name'], url ( "tuan/nav/catid/$pid/aid/$aid" ) );
}
$btypes = $styps = '';
if ($cat){
foreach ( $cat as $key => $val ) {
if ($val ['pid']==0){
$btypes [$key] = $val ['name'].'('.$val['num'].')';
}
if ($catid == $val ['pid']){
$stypes [$key] = $val ['name'].'('.$val['num'].')';
}
}
}
// 加载地区信息
$aid = ( int ) $_GET ['aid'];
// 载入地区
$area = $_G ['loader']->variable ( 'area_' . $_CITY ['aid'], null, false );
// 地区级别
$area_level = $area [$aid] ['level'];
if ($area_level == 2) {
$paid = 0;
} else {
$paid = $area [$aid] ['pid'];
}
// 构造连接
if ($paid) {
$urlpath [] = url_path ( $area [$paid] ['name'], url ( "item/list/catid/$pid/aid/$paid" ) );
}
if ($paid != $aid) {
$urlpath [] = url_path ( $area [$aid] ['name'], url ( "item/list/catid/$pid/aid/$aid" ) );
}
// 区街联动
$boroughs = $streets = '';
if ($area)
foreach ( $area as $key => $val ) {
if ($val ['level'] == 2)
$boroughs [$key] = $val ['name'] . '(' . $val ['tuannum'] . ')';
if ($val ['level'] == 3 && $val ['listorder'] == 1 && ($aid == $val ['pid'] || $paid == $val ['pid'])) {
$streets [$key] = $val ['name'];
$counter ++;
}
if ($counter > 10) {
break;
}
}
// 没有选择区时
$counter = 0;
if ($aid == 0) {
foreach ( $area as $key => $val ) {
if ($val ['level'] == 3 && $val ['listorder'] == 1) {
$streets [$key] = $val ['name'];
$counter ++;
}
if ($counter > 10) {
break;
}
}
}
// 检索团购数据
$flag = $_GET ['flag'];
if (empty ( $flag ))
$flag = '1';
$offset = $MOD ['list_num'] > 0 ? $MOD ['list_num'] : 40;
$start = get_start ( $_GET ['page'], $offset );
list ( $total, $list ) = $T->getlist2 ( $flag, $catid, $aid, $start, $offset );
if ($total) {
$multipage = multi ( $total, $offset, $_GET ['page'], url ( "tuan/nav/page/_PAGE_" ) );
}
// 子类选择
$active = array ();
$active ['type'] [$type] = ' class="selected"';
$active ['num'] [$num] = ' class="selected"';
$active ['orderby'] [$orderby] = ' class="selected"';
// 页画SEO信息
$_HEAD ['title'] = '无锡团购,无锡团购导航,无锡美食团购,阿果生活网';
$_HEAD ['keywords'] = $MOD ['meta_keywords'];
$_HEAD ['description'] = $MOD ['meta_description'];
include template ( 'tuandh_list' );
?>
<file_sep>/core/modules/modoer/item/share.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
// 实例化主题类
$D = & $_G ['loader']->model ( 'item:threads' );
// 排序数组
$orderlist = lang ( 'item_list_orderlist' );
//查询条件
$where=array(48);
$num = abs ( _cookie ( 'list_display_item_subject_num', ( int ) $MOD ['list_num'], 'intval' ) );
(! $num || ! in_array ( $num, $numlist )) && $num = 20;
$offset = $num;
$wf_count = 5;
$wf_offset = $num * $wf_count;
$wf_page = _get ( 'wfpage', 1, MF_INT_KEY );
$start = get_start ( ($wf_page - 1) * $wf_count + $_GET ['page'], $num );
$tplname = 'item_subject_waterfall';
if (_input ( 'waterfall' ) == 'Y' && $_G ['in_ajax']) {
$tplname = 'share_waterfall_li';
}
$select="t.tid,t.fid,t.subject,t.dateline,t.sortid,t.cover,views,replies";
list ( $total, $list ) = $D->getlist ($select, $where, $order_arr [$orderby], $start, $num, true );
if ($total) {
$multipage = multi ( $total, $num, $_GET ['page'], url ( "item/wmlist/catid/$catid/aid/$aid/order/$order/type/$type/att/$atturl/num/$num/total/$total/wfpage/$wf_page/page/_PAGE_" ) );
}
$_HEAD ['title'] = parse_seo_tags ( $MOD ['seo_list_title'], $seo_tags );
$_HEAD ['keywords'] = parse_seo_tags ( $MOD ['seo_list_keywords'], $seo_tags );
$_HEAD ['description'] = parse_seo_tags ( $MOD ['seo_list_description'], $seo_tags );
// 最近的浏览COOKIE
include template ( 'share_waterfall' );
?><file_sep>/core/modules/item/admin/album.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(! defined ( 'IN_ADMIN' ) || ! defined ( 'IN_MUDDER' )) && exit ( 'Access Denied' );
$A = & $_G ['loader']->model ( MOD_FLAG . ':album' );
$op = isset ( $_POST ['op'] ) ? $_POST ['op'] : $_GET ['op'];
switch ($op) {
case 'update' :
$A->update ( _post ( 'album' ) );
redirect ( 'global_op_succeed', get_forward ( cpurl ( $module, $act, 'list' ) ) );
break;
case 'delete' :
$A->delete ( _post ( 'albumids' ) );
redirect ( 'global_op_succeed_delete', get_forward ( cpurl ( $module, $act, 'list' ) ) );
break;
default :
$op = 'list';
//联系查询
$A->db->join ( $A->table, 'a.sid', 'dbpre_subject', 's.sid', MF_DB_LJ );
if (! $admin->is_founder)
$A->db->where ( 'a.city_id', $_CITY ['aid'] );
if (is_numeric ( $_GET ['city_id'] ) && $_GET ['city_id'] >= 0)
$A->db->where ( 'a.city_id', $_GET ['city_id'] );
if ($_GET ['sid'])
$A->db->where ( 'a.sid', $_GET ['sid'] );
if ($_GET ['name'])
$A->db->where_like ( 'a.name', '%' . $_GET ['name'] . '%' );
if ($_GET ['starttime'])
$A->db->where_more ( 'a.lastupdate', strtotime ( $_GET ['starttime'] ) );
if ($_GET ['endtime'])
$A->db->where_less ( 'a.lastupdate', strtotime ( $_GET ['endtime'] ) );
if ($total = $A->db->count ()) {
$A->db->sql_roll_back ( 'from,where' );
! $_GET ['orderby'] && $_GET ['orderby'] = 'albumid';
! $_GET ['ordersc'] && $_GET ['ordersc'] = 'DESC';
$A->db->order_by ( 'a.' . $_GET ['orderby'], $_GET ['ordersc'] );
$A->db->limit ( get_start ( $_GET ['page'], $_GET ['offset'] ), $_GET ['offset'] );
$A->db->select ( 'a.*,s.name as subjectname,s.subname' );
$list = $A->db->get ();
$multipage = multi ( $total, $_GET ['offset'], $_GET ['page'], cpurl ( $module, $act, 'list', $_GET ) );
}
$admin->tplname = cptpl ( 'album_list', MOD_FLAG );
}<file_sep>/core/modules/tuan/model/dhdata_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_tuan_dhdata extends ms_model {
var $table = 'dbpre_tuan_collect_data';
var $key = 'id';
var $model_flag = 'tuan';
function __construct() {
parent::__construct();
$this->model_flag = 'tuan';
$this->init_field();
$this->modcfg = $this->variable('config');
}
function msm_tuan_tgsite() {
$this->__construct();
}
function init_field() {
$this->add_field('subject,shortsubject,thumb,oldprice,nowprice,desc,
lasttime,starttime,salesnum,range,sid,sname,catid,catname,subcatname,subcatid');
$this->add_field_fun('desc,subject', '_T');
$this->add_field_fun('subcatid,catid', 'intval');
}
function save($post, $id=null) {
$edit = $id > 0;
if($edit) {
if(!$detail = $this->read($id)) redirect('tuan_tgsite_empty');
}
$id = parent::save($post,$id);
return $id;
}
//数据提交检测函数,实现父类的方法
function check_post($post, $edit = false) {
}
//团购数据采集
function spider($ids) {
}
}
?><file_sep>/core/modules/tuan/assistant/order.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
$O =& $_G['loader']->model('tuan:order');
$op = _input('op');
switch($op) {
case 'cancel':
//$O->cancel(_POST['oids']);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'detail':
$oid = _get('oid', null, 'intval');
if(!$detail = $O->read($oid)) redirect('tuan_order_empty');
if($detail['uid'] != $user->uid) redirect('global_op_access');
$detail['contact'] = $detail['contact'] ? unserialize($detail['contact']) : array();
$detail['express'] = $detail['express'] ? unserialize($detail['express']) : array();
$T =& $_G['loader']->model(':tuan');
$tuan = $T->read($detail['tid']);
$ranking = $O->get_ranking($detail['tid'], $oid);
$tplname = 'm_order_detail';
break;
default:
$O->plan_overdue($user->uid); //被动更新订单状态
$status_arr = array('new','payed','canceled','overdue','refunded');
$status = _get('status');
if(!in_array($status, $status_arr)) $status = '';
list($total,$list) = $O->myorders($status);
if($total) $mulitpage = multi($result[0],$offset,$page,url('tuan/member/ac/order/page/_PAGE_'));
$tplname = 'm_order';
}
?><file_sep>/core/modules/tuan/helper/misc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
class misc_tuan {
function & get_sms_class($config) {
global $_G;
$api = $config['sms_api'] ? $config['sms_api'] : 'powereasy';
$name = 'sms_' . $api;
if(!isset($_G[$name])) {
$apifile = 'core' . DS . 'modules' . DS . 'tuan' . DS . 'model' . DS . 'sms' . DS . $name . '_class.php';
if(!is_file(MUDDER_ROOT . $apifile)) show_error(lang('global_file_not_exist', $apifile));
if(!class_exists('msm_sms_base')) {
include MUDDER_ROOT . 'core' . DS . 'modules' . DS . 'tuan' . DS . 'model' . DS . 'sms_class.php';
}
include MUDDER_ROOT . $apifile;
$_G[$name] = new $name($config);
}
return $_G[$name];
}
}
?><file_sep>/core/modules/modoer/item/app/wmdetail.php
<?php
/*
* 安卓应用:商家信息和外卖菜单功能
* 调用方法:http://127.0.0.7/item.php?act=app&do=wmdetail&sid=
* @paras:sid
* @格式:{msg,data(item,menu)}
*
*/
!defined('IN_MUDDER') && exit('Access Denied');
// 实例化主题类
$T = & $_G ['loader']->model ( 'item:takeout' );
$json = & $_G ['loader']->lib ( 'json', NULL, TRUE );
$sid = ( int ) $_GET ['sid'];
$sid=7416;
if (! $sid)
redirect ( lang ( 'global_sql_keyid_invalid', 'id' ) );
// 取得主题信息
if ($sid) {
$detail = $T->read ( $sid );
} else {
http_404 ();
}
if (! $detail || ! $detail ['status']) {
redirect ( 'item_empty' );
}
//商机信息
$item=array('sid'=>$sid,'fullname'=>$detail['fullname'],'fullname'=>$detail['fullname'],'dihua'=>$detail['c_dianhua'],'dizhi'=>$detail['c_dizhi']);
// 计算商家菜品总数
$P = & $_G ['loader']->model ( ':product' );
//$detail ['pronums'] = $P->get_subject_total ( $sid );
// 解析配送范围
//$S = & $_G ['loader']->model ( 'item:subject' );
//$ranages= $S->get_mytag ( $detail ['c_range'] );
//按分类显示菜单
$where = array ();
$where ['s.sid'] = $sid;
$orderby = array (
's.catid' => 'DESC',
's.listorder' => 'DESC'
);
$select = "s.pid,s.sid,s.subject,s.thumb,s.description,s.pageview,s.price,s.catid,c.name ";
list ($total, $list ) = $P->find ( $select, $where, $orderby, 0, 300, TRUE );
if ($total) {
while ( $val = $list->fetch_array () ) {
$menu [] = seatch_to_menu_array ( $val );
}
$list->free_result ();
$output = $json->encode ( array (
'msg' => '10001',
'item' => $item ,
'menu' => $menu
) );
echo $output;
output ();
}
// 构造菜品数组
function seatch_to_menu_array(&$val) {
return array (
'pid' => $val ['pid'],
'sid' => $val ['sid'],
'subject' => $val ['subject'],
'price' => $val ['price'],
'catid' => $val ['catid'],
'catname' => $val ['name'],
'pageview' => $val ['pageview']
);
}
?>
<file_sep>/core/modules/party/admin/apply.inc.php.bak
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$PA =& $_G['loader']->model('party:apply');
$op = _input('op');
switch($op) {
case 'delete':
$PA->delete(_post('applyids'));
redirect('global_op_succeed_delete', get_forward(cpurl($module,$act)));
break;
default:
$op = 'list';
$PA->db->join($PA->table, 'pa.partyid', 'dbpre_party', 'p.partyid');
if(!$admin->is_founder) $PA->db->where('city_id', $_CITY['aid']);
if($_GET['partyid']) $PA->db->where('pa.partyid', $_GET['partyid']);
if($_GET['username']) $PA->db->where('pp.username', $_GET['username']);
if($_GET['starttime']) $PA->db->where_more('pa.dateline', strtotime($_GET['starttime']));
if($_GET['endtime']) $PA->db->where_less('pa.dateline', strtotime($_GET['endtime']));
if($total = $PA->db->count()) {
$PA->db->sql_roll_back('from,where');
!$_GET['orderby'] && $_GET['orderby'] = 'applyid';
!$_GET['ordersc'] && $_GET['ordersc'] = 'ASC';
$PA->db->order_by('pa.'.$_GET['orderby'], $_GET['ordersc']);
$PA->db->limit(get_start($_GET['page'], $_GET['offset']), $_GET['offset']);
$PA->db->select('pa.*,p.subject');
$list = $PA->db->get();
$multipage = multi($total, $_GET['offset'], $_GET['page'], cpurl($module,$act,'list',$_GET));
}
$admin->tplname = cptpl('apply_list', MOD_FLAG);
}
?><file_sep>/core/modules/tuan/admin/order.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$TO =& $_G['loader']->model('tuan:order');
$op = _input('op');
$goods_status = lang('tuan_good_status');
switch($op) {
case 'delete':
$oids = _post('oids');
$TO->delete($oids);
redirect('global_op_succeed_delete', get_forward(cpurl($module,$act)));
break;
case 'cancel':
$oid = _get('oid', null, MF_INT_KEY);
$TO->cancel($oid);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'refund':
$oid = _get('oid', null, MF_INT_KEY);
$TO->refund($oid);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'localpay':
$oid = _get('oid', null, MF_INT_KEY);
$TO->localpay($oid);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'detail':
$oid = _get('oid', null, MF_INT_KEY);
if(!$order = $TO->read($oid)) redirect('tuan_order_empty');
$order['contact'] = $order['contact'] ? unserialize($order['contact']) : array();
$order['express'] = $order['express'] ? unserialize($order['express']) : array();
$T =& $_G['loader']->model(':tuan');
$tuan = $T->read($order['tid']);
$_G['loader']->helper('form','tuan');
$admin->tplname = cptpl('order_detail', MOD_FLAG);
break;
case 'good_status':
if(!$oid = _post('oid',null,'intval')) redirect(lang('global_sql_keyid_invalid','oid'));
$post = $TO->get_post($_POST);
$TO->update_good_status($oid,$post);
redirect('global_op_succeed', get_forward(cpurl($module,$act),1));
break;
case 'refund_tuan':
$tid = _post('tid', null, MF_INT_KEY);
if(!$tid) redirect(lang('global_sql_keyid_invalid','tid'));
$TO->refund_tuan($tid);
redirect('global_op_succeed', cpurl($module,'tuan','detail',array('tid'=>$tid)));
break;
case 'return_balance':
$tid = _post('tid', null, MF_INT_KEY);
if(!$tid) redirect(lang('global_sql_keyid_invalid','tid'));
$TO->return_balance($tid);
redirect('global_op_succeed', cpurl($module,'tuan','detail',array('tid'=>$tid)));
break;
case 'update_real_price':
$tid = _get('tid', null, MF_INT_KEY);
$O =& $_G['loader']->model('tuan:order'); //update_real_price
$O->update_real_price($tid);
redirect('global_op_succeed', cpurl($module,'tuan','detail',array('tid'=>$tid)));
break;
default:
$op = 'list';
$status = $_GET['status'] = _get('status', 'payed', MF_TEXT);
$tid = _get('tid',null,MF_INT_KEY);
if(empty($tid)) redirect(lang('global_sql_keyid_invalid','tid'));
$T =& $_G['loader']->model(':tuan');
if(!$tuan = $T->read($tid)) redirect('tuan_empty');
$where = array();
$where['o.status'] = $status;
$where['o.tid'] = $tid;
$orderby = $status == 1 ? array('exchangetime'=>'DESC') : array('dateline'=>'DESC');
$offset = 20;
$start = get_start($_GET['page'], $offset);
$select = 'o.*';
list($total, $list) = $TO->find($select, $where, $orderby, $start, $offset, TRUE);
if($total) $multipage = multi($total, $offset, $_GET['page'], cpurl($module,$act,'list',$_GET));
$admin->tplname = cptpl('order_list', MOD_FLAG);
}
?><file_sep>/core/modules/tuan/inc/review_task.php
<?php
/**
* 团购点评任务类
*
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
class task_tuan_review {
var $flag = 'tuan:review';
var $title = '团购点评任务类';
var $copyright = 'MouferStudio';
var $version = '1.0';
var $info = array();
var $install = false;
var $ttid = 0;
function __construct() {
$this->title = lang($this->title);
}
function progress(& $task_detail) {
global $_G;
$db =& $_G['db'];
$taskid = $task_detail['taskid'];
$db->from('dbpre_mytask');
$db->where('uid',$_G['user']->uid);
$db->where('taskid',$taskid);
$mytask = $db->get_one();
if(!$mytask) return 0;
$db->from('dbpre_tuan_order');
$db->where('status', 'payed');
$db->where('uid', $_G['user']->uid);
$db->where_more('dateline', $mytask['applytime']);
if(!$order = $db->get_one()) return 0;
$T =& $_G['loader']->model(':tuan');
$tuan = $T->read($order['tid']);
if(!$tuan || !$tuan['sid']) return 0;
$R =& $_G['loader']->model(':review');
$exists = $R->reviewed('item_subject', $tuan['sid']);
return $exists ? 100 : 0;
}
function apply($taskid) {}
function delete($taskid) {}
function install() {}
function unstall() {}
}
?><file_sep>/templates/item/vip/footer.php
<?exit?>
<div id="footer">
<h3>
<!--{eval $main_menus = $_CFG['main_menuid'] ? $_G['loader']->variable('menu_' . $_CFG['main_menuid']) : '';}-->
<!--{loop $main_menus $val}-->
<a href="{url $val[url]}"{if $val[target]} target="$val[target]"{/if}>$val[title]</a>|
<!--{/loop}--></h3>
<p>
<!--{eval $foot_menus = $_CFG['foot_menuid'] ? $_G['loader']->variable('menu_' . $_CFG['foot_menuid']) : '';}-->
<!--{loop $foot_menus $val}-->
<a href="{url $val[url]}"{if $val[target]} target="$val[target]"{/if}>$val[title]</a>|
<!--{/loop}-->
<script language="JavaScript" type="text/javascript" src="http://js.users.51.la/3606430.js"></script>
<noscript><a href="http://www.51.la/?3606430" target="_blank"><img alt="我要啦免费统计" src="http://img.users.51.la/3606430.asp" style="border:none" /></a></noscript>|
<script type="text/javascript">
var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://");
document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3F7c6cc6cdc95f507d99c047cc46ec2980' type='text/javascript'%3E%3C/script%3E"));
</script></p>
<p><font color="#CC0000">COPYRIGHT © 2010 Dingzhou.Biz™</font> <a href="{URLROOT}" target="_blank">$_CFG[sitename]</a> 版权所有
<!--{if $_CFG['icpno']}--><a href="http://www.miibeian.gov.cn/" target="_blank">$_CFG[icpno]</a><!--{/if}--></p>
<p>网站运营维护: $_CFG[sitename] 本站QQ群<font color="#CC0000">19552945 23960016</font></p>
</div>
</div>
<!-- JiaThis Button BEGIN -->
<script type="text/javascript" src="http://v2.jiathis.com/code_mini/jiathis_r.js?type=left&btn=l2.gif" charset="utf-8"></script>
<!-- JiaThis Button END -->
</body>
</html><file_sep>/core/modules/about/admin/templates/save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/validator.js"></script>
<div id="body">
<form method="post" action="<?=cpurl($module,$act,'save',array('sign' => $_GET['sign']))?>" enctype="multipart/form-data" onsubmit="return validator(this);">
<div class="space">
<div class="subtitle">增加/编辑单页面</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1"><strong>城市属性:</strong>选择所属地区,选择“全局”表示可显示在所有城市分站内</td>
<td>
<select name="city_id" id="city_id">
<?=form_city($detail['city_id'], TRUE, !$admin->is_founder);?>
</select>
</td>
</tr>
<tr>
<td class="altbg1" width="25%"><strong>名称:<span class="font_1">*</span></strong></td>
<td width="75%"><input name="pname" type="text" class="txtbox3" value="<?=$detail['pname']?>" validator="{'empty':'N','errmsg':'请填写单页面名称。'}" /></td>
</tr>
<tr>
<td class="altbg1"><strong>标识:<span class="font_1">*</span></strong>在前台访问时进行判断的标识,例如:若是关于我们,前台用about标识来访问关于我们的页面,那么该处填写about。</td>
<td><input type="tetx" name="mark" class="txtbox3" value="<?=$detail['mark']?>" validator="{'empty':'N','errmsg':'请填写单页面标识。'}" /></td>
</tr>
<tr>
<td class="altbg1"><strong>页面组标识:<span class="font_1">*</span></strong>前台调用时的区别标识,若向要新建立组,那么直接填写你要建立的组名即可。</td>
<td width="*">
<input type="text" name="groupname" id="groupname" value="<?=$detail['groupname']?>" class="txtbox4" />
<select onchange="$('#groupname').val($(this).val());">
<option value="">==已存在的组=</option>
<?=form_page_group($detail['groupname'])?>
</select>
</td>
</tr>
<tr>
<td class="altbg1"><strong>模版名称:<span class="font_1">*</span></strong>单页面所使用的模版,不要填写模版后缀,即无需填写.htm或者.html,若用默认模版则填写about。</td>
<td><input type="tetx" name="templates" class="txtbox3" value="<?=$detail['templates']?>" validator="{'empty':'N','errmsg':'请填写单页面所使用的模版。'}" /></td>
</tr>
<tr>
<td class="altbg1"><strong>状态:<span class="font_1">*</span></strong>选择“停用”将不再前台显示。</td>
<td><?=form_radio('enabled',array('Y'=>'启用','N'=>'停用'),$detail['enabled']?$detail['enabled']:'Y')?></td>
</tr>
<tr>
<td class="altbg1"><strong>单页面内容:</strong></td>
<td><?=$edit_html?></td>
</tr>
</table>
<div class="subtitle">SEO设置</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1"><strong>Title标题:</strong></td>
<td><input type="tetx" name="title" class="txtbox" value="<?=$detail['title']?>" /></td>
</tr>
<tr>
<td class="altbg1"><strong>Keywords:</strong></td>
<td><input type="tetx" name="keywords" class="txtbox" value="<?=$detail['keywords']?>" /></td>
</tr>
<tr>
<td class="altbg1"><strong>Description:</strong></td>
<td><input type="tetx" name="description" class="txtbox" value="<?=$detail['description']?>" /></td>
</tr>
</table>
<center>
<input type="hidden" name="do" value="<?=$op?>" />
<?if($op=='edit'):?>
<input type="hidden" name="apid" value="<?=$detail['apid']?>" />
<?endif;?>
<input type="hidden" name="forward" value="<?=get_forward()?>" />
<?=form_submit('dosubmit',lang('admincp_submit'),'yes','btn')?>
<input type="button" class="btn" value="<?=lang('admincp_return')?>" onclick="document.location='<?=cpurl($module,$act)?>';" />
</center>
</div>
</form>
</div><file_sep>/core/modules/party/install/config.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
// 设置模块的默认配置信息
$moduleconfig = array(
'meta_keywords' => 'Keywords',
'meta_description' => 'Description',
'party_check' => '0',
'party_thumb_w' => '200',
'party_thumb_h' => '150',
'pic_check' => '0',
);
?><file_sep>/core/modules/tuan/admin/templates/wish_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript">
var g;
function reload() {
var obj = document.getElementById('reload');
var btn = document.getElementById('switch');
if(obj.innerHTML.match(/^<.+href=.+>/)) {
g = obj.innerHTML;
obj.innerHTML = '<input type="file" name="picture" size="20">';
btn.innerHTML = '取消上传';
} else {
obj.innerHTML = g;
btn.innerHTML = '重新上传';
}
}
</script>
<div id="body">
<form method="post" action="<?=cpurl($module,$act,'save')?>" name="myform" enctype="multipart/form-data">
<div class="space">
<div class="subtitle">自助团购编辑</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<?if($admin->is_founder):?>
<tr>
<td align="right" class="altbg1">城市</td>
<td>
<select name="city_id">
<?=form_city($_GET['city_id'])?>
</select>
</td>
</tr>
<?else:?>
<input type="hidden" name="city_id" value="<?=$detail['city_id']?>">
<?endif;?>
<tr>
<td width="100" align="right" class="altbg1"><span class="font_1">*</span>名称</td>
<td width="*"><input type="textbox" name="title" value="<?=$detail['title']?>" class="txtbox2"></td>
</tr>
<tr>
<td align="right" class="altbg1"><span class="font_1">*</span>期望价</td>
<td><input type="textbox" name="price" value="<?=$detail['price']?>" class="txtbox4"> 元</td>
</tr>
<tr>
<td class="altbg1" align="right">团购封面:</td>
<td colspan="3">
<?if(!$detail['thumb']):?>
<input type="file" name="picture" size="20" />
<?else:?>
<span id="reload"><a href="<?=$detail['picture']?>" target="_blank" src="<?=$detail['thumb']?>" onmouseover="tip_start(this);"><?=$detail['thumb']?></a></span>
[<a href="javascript:reload();" id="switch">重新上传</a>]
<?endif;?>
</td>
</tr>
<tr>
<td align="right" valign="top" class="altbg1"><span class="font_1">*</span>详细说明</td>
<td><textarea name="content" rows="8" cols="50"><?=$detail['content']?></textarea></td>
</tr>
</table>
</div>
<center>
<input type="hidden" name="do" value="<?=$op?>" />
<?if($op=='edit'):?>
<input type="hidden" name="twid" value="<?=$detail['twid']?>" />
<?endif;?>
<input type="hidden" name="forward" value="<?=get_forward()?>" />
<?=form_submit('dosubmit',lang('admincp_submit'),'yes','btn')?>
<?=form_button_return(lang('admincp_return'),'btn')?>
</center>
</form>
</div><file_sep>/core/modules/tuan/admin/templates/tuan_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript">
loadscript('mdialog');
function start_send_mail(tid) {
if (!is_numeric(tid)) {
alert('无效的tid');
return;
}
var html = '<p><input id="send_btn" type="button" value="开始发送" onclick="send_mail('+tid+',1,1);" />';
html += '<span id="send_status">' + ' 等待发送.' + '</span></p>';
dlgOpen('发送邮件', html, 320, 100);
}
var next_stop = false;
function send_mail(tid,page) {
$('#send_btn').hide();
$('#send_status').html('正在发送['+page+']...');
$.post("<?=URLROOT.'index.php?m=tuan&act=email&op=send&page='?>"+page, {tid:tid, in_ajax:1}, function(result) {
if(result.match(/^[0-9]+,[0-9]+$/)) {
var d = result.split(",");
send_mail(d[0], d[1]);
} else if(result == 'completed') {
$('#send_status').html('邮件已全部发送完毕!');
} else if (result.match(/\{\s+caption:".*",message:".*".*\s*\}/)) {
myAlert(result);
} else {
alert('AJAX解析错误.');
return;
}
});
}
</script>
<div id="body">
<form method="get" action="<?=SELF?>">
<input type="hidden" name="module" value="<?=$module?>" />
<input type="hidden" name="act" value="<?=$act?>" />
<input type="hidden" name="op" value="<?=$op?>" />
<div class="space">
<div class="subtitle">团购筛选</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100" class="altbg1">团购类型</td>
<td width="350">
<select name="mode">
<option value="">==全部==</option>
<option value="normal"<?=_get('mode')=='normal'?' selected':''?>>常规团</option>
<option value="average"<?=_get('mode')=='average'?' selected':''?>>平摊团</option>
<option value="wholesale"<?=_get('mode')=='wholesale'?' selected':''?>>批发团</option>
</select>
<select name="catid">
<option value="">==全部==</option>
<?=form_tuan_category(_get('catid'));?>
</select>
</td>
<td width="100" class="altbg1">活动城市</td>
<td width="*">
<?if($admin->is_founder):?>
<select name="city_id" onchange="select_city(this,'aid');">
<option value="">全部</option>
<?=form_city($_GET['city_id'])?>
</select>
<?else:?>
<?=$_CITY['name']?>
<?endif;?>
</td>
</tr>
<tr>
<td class="altbg1">团购标题</td>
<td><input type="text" name="subject" class="txtbox2" value="<?=$_GET['subject']?>" /></td>
<td class="altbg1">团购状态</td>
<td><?=form_radio('status',lang('tuan_status'),$_GET['status']?$_GET['status']:'new')?></td>
</tr>
<tr>
<td class="altbg1">结果排序</td>
<td colspan="3">
<select name="orderby">
<option value="listorder"<?=$_GET['orderby']=='listorder'?' selected="selected"':''?>>按顺序排序</option>
<option value="tid"<?=$_GET['orderby']=='tid'?' selected="selected"':''?>>ID排序</option>
<option value="goods_sell"<?=$_GET['orderby']=='goods_sell'?' selected="selected"':''?>>销售量</option>
<option value="price"<?=$_GET['orderby']=='price'?' selected="selected"':''?>>销售价格</option>
</select>
<select name="ordersc">
<option value="DESC"<?=$_GET['ordersc']=='DESC'?' selected="selected"':''?>>递减</option>
<option value="ASC"<?=$_GET['ordersc']=='ASC'?' selected="selected"':''?>>递增</option>
</select>
<select name="offset">
<option value="20"<?=$_GET['offset']=='20'?' selected="selected"':''?>>每页显示20个</option>
<option value="50"<?=$_GET['offset']=='50'?' selected="selected"':''?>>每页显示50个</option>
<option value="100"<?=$_GET['offset']=='100'?' selected="selected"':''?>>每页显示100个</option>
</select>
<button type="submit" value="yes" name="dosubmit" class="btn2">筛选</button>
</td>
</tr>
</table>
</div>
</form>
<form method="post" action="<?=cpurl($module,$act)?>" name="myform">
<div class="space">
<div class="subtitle">团购管理</div>
<ul class="cptab">
<?foreach(lang('tuan_status') as $k => $v):?>
<li<?=$_GET['status']==$k?' class="selected"':''?>><a href="<?=cpurl($module,$act,'list',array('status'=>$k))?>"><?=$v?></a></li>
<?endforeach;?>
<li<?if($op=='checklist')echo' class="selected"';?>><a href="<?=cpurl($module,$act,'checklist')?>">未审核(<?=$check_count?>)</a></li>
<li><a id="create_tuan" rel="create_tuan_menu" href="<?=cpurl($module,$act,'add')?>" onfocus="this.blur()"><span class="font_1">新建团购</span></a></li>
</ul>
<ul id="create_tuan_menu" class="dropdown-menu">
<?$modes = array('normal'=>'常规团购','average'=>'平摊团购','wholesale'=>'批发团购','forestall'=>'抢鲜团购');?>
<?foreach($modes as $key=>$val):?>
<li><a href="<?=cpurl($module,$act,'add',array('mode'=>$key))?>"><?=$val?></a></li>
<?endforeach;?>
</ul>
<script type="text/javascript">
$("#create_tuan").powerFloat();
</script>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y">
<tr class="altbg1">
<td width="60">排序</td>
<td width="100">图片</td>
<td width="*">团购项目</td>
<td width="160">价格/销售</td>
<td width="120">团购时间</td>
<td width="130">操作</td>
</tr>
<?if($total):?>
<?while($val=$list->fetch_array()) {?>
<tr>
<td><input type="text" name="tuan[<?=$val[tid]?>][listorder]" value="<?=$val[listorder]?>" class="txtbox5" /></td>
<td><img src="<?=URLROOT.'/'.$val['thumb']?>" width="95" /></td>
<td>
<div><a href="<?=url("tuan/detail/id/$val[tid]")?>" target="_blank"><?=$val['subject']?></a></div>
<div>
<span class="font_2">[<?=template_print('modoer','area',array('aid'=>$val['city_id']))?>]</span>
<span class="font_2">[<?=lang('tuan_mode_'.$val['mode'])?>]</span>
<span class="font_2">[<?=$category[$val['catid']]['name']?>]</span>
<?if($val['uid']>0):?><span class="font_1">[商家活动]</span><?endif;?>
</div>
</td>
<td>
<div>市场价:¥<?=$val['market_price']?></div>
<?if($val['status']=='succeeded'&&$val['mode']!='normal'):?>
<div>下单价:¥<?=$val['price']?></div>
<?if($val['mode']=='forestall'):?>
<div class="font_1">抢鲜团无统一价格</div>
<?else:?>
<div>最终价:¥<strong><?=$val['real_price']?></strong></div>
<?endif;?>
<?if($val['real_price']!=$val['price']):?>
<div class="font_1">存在差价,需退还</div>
<?endif;?>
<?else:?>
<div>团购价:¥<strong><?=$val['price']?></strong></div>
<?endif;?>
<div><?=$val['peoples_sell']?> 人购买, <?=$val['goods_sell']?> 件销售</div>
</td>
<td>
<div>开始:<?=date('Y-m-d',$val['starttime'])?></div>
<div>结束:<?=date('Y-m-d',$val['endtime'])?></div>
<?if($status=='succeeded'):?>
<div>成团:<?=date('m-d H:i',$val['succeedtime'])?></div>
<?endif;?>
</td>
<td>
<div>
<a href="<?=cpurl($module,'order','', array('tid'=>$val['tid']))?>">订单</a>
<a href="<?=cpurl($module,$act,'detail', array('tid'=>$val['tid']))?>">详情</a>
<a href="<?=cpurl($module,$act,'edit', array('tid'=>$val['tid']))?>">编辑</a>
<a href="<?=cpurl($module,$act,'delete', array('tid'=>$val['tid']))?>" onclick="return confirm('您确定要删除本团购信息以及可能存在的订单和团购券信息吗?');">删除</a></div>
<?if($op!='checklist'):?>
<div><a href="javascript:;" onclick="start_send_mail(<?=$val['tid']?>);">邮件发送订阅用户</a></div>
<?endif;?>
</td>
</tr>
<?}?>
<?else:?>
<tr><td colspan="10">暂无信息</td></tr>
<?endif;?>
</table>
</div>
<div><?=$multipage?></div>
<center>
<input type="hidden" name="op" value="update" />
<input type="hidden" name="dosubmit" value="yes" />
<?if($total):?>
<button type="button" class="btn" onclick="easy_submit('myform','update',null);">更新排序</button>
<?endif;?>
</center>
</form>
</div><file_sep>/core/modules/coupon/list.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
define ( 'SCRIPTNAV', 'coupon' );
$CO = $_G ['loader']->model ( ':coupon' );
$I = & $_G ['loader']->model ( 'item:subject' );
$urlpath = array ();
$urlpath [] = url_path ( $MOD ['name'], url ( "coupon/index" ) );
$where = array ();
// 按商家展示 优惠信息
if (is_numeric ( $_GET ['sid'] ) && $_GET ['sid'] > 0) {
$sid = ( int ) $_GET ['sid'];
// 取得主题信息
if (! $subject = $I->read ( $sid ))
redirect ( 'item_empty' );
$subject_field_table_tr = $I->display_sidefield ( $subject );
$where ['c.sid'] = $sid;
$urlpath [] = url_path ( trim ( $subject ['name'] . $subject ['subname'] ), url ( "coupon/list/sid/$sid" ) );
// 其他模块和功能的链接
$links = $_G ['hook']->hook ( 'subject_detail_link', $subject, TRUE );
define ( 'SUB_NAVSCRIPT', 'coupon' );
}
// 按类别展示 优惠信息
$category = $_G ['loader']->variable ( 'category', MOD_FLAG );
if (is_numeric ( $_GET ['catid'] ) && $_GET ['catid'] > 0) {
$catid = ( int ) $_GET ['catid'];
$where ['c.catid'] = $catid;
$urlpath [] = url_path ( $category [$catid] [name], url ( "coupon/list/catid/$catid" ) );
}
// 正在进行和既将开始
if ($_GET ['f']) {
$qz = $_GET ['f'];
if ($qz == '2') {
$stime = date ( "Y-m-d", strtotime ( "+1day" ) );
$etime = date ( "Y-m-d", strtotime ( "+20day" ) );
$ttt = explode ( '-', $stime );
$starttime = mktime ( 0, 0, 0, $ttt [1], $ttt [2], $ttt [0] );
$ttt = explode ( '-', $etime );
$endtime = mktime ( 0, 0, 0, $ttt [1], $ttt [2], $ttt [0] );
$where ['starttime'] = array (
'where_between_and',
array (
$starttime,
$endtime
)
);
}
// $urlpath[] = url_path($qz, url("coupon/list/catid/$catid/f/$qz"));
}
$where ['c.status'] = 1;
$offset = $MOD ['listnum'] > 0 ? $MOD ['listnum'] : 10;
$start = get_start ( $_GET ['page'], $offset );
$select = 'c.couponid,c.catid,c.sid,c.subject,c.starttime,c.endtime,c.des,c.comments,c.pageview,c.effect1,c.sname,c.picture';
$orders = array (
'couponid' => 'asc',
'effect1' => 'DESC',
'pageview' => 'DESC',
'dateline' => 'DESC',
'comments' => 'DESC'
);
//排序字段
$_GET ['order'] = isset ( $_GET ['order'] ) && in_array ( $_GET ['order'], array_keys ( $orders ) ) ? $_GET ['order'] : 'couponid';
list ( $total, $list ) = $CO->find ( $select, $where, array (
'c.' . $_GET ['order'] => $orders [$_GET ['order']]
), $start, $offset, TRUE, 's.name,s.subname,s.reviews,s.fullname,s.thumb,s.avgprice' );
if ($total)
$multipage = multi ( $total, $offset, $_GET ['page'], url ( 'coupon/list/sid/' . $sid . '/catid/' . $catid . '/order/' . $_GET ['order'] . '/page/_PAGE_' ) );
// 给选中变色
$active = array ();
$catid > 0 && $active ['catid'] [$catid] = ' class="selected"';
$_GET ['order'] && $active ['order'] [$_GET ['order']] = ' class="selected"';
// 页面标题信息
$_HEAD ['keywords'] = ($subject ? ($subject [name] . ',' . $subject [subname] . ',') : '') . $MOD ['meta_keywords'];
$_HEAD ['description'] = $MOD ['meta_description'];
if ($subject) {
$scategory = $I->get_category ( $subject ['catid'] );
if (! $subject ['templateid'] && $scategory ['config'] ['templateid'] > 0) {
$subject ['templateid'] = $scategory ['config'] ['templateid'];
}
}
if ($subject && $subject ['templateid']) {
include template ( 'coupon_list', 'item', $subject ['templateid'] );
} else {
include template ( 'coupon_list' );
}
function parsesname($sid) {
global $I;
$str = '';
$sids = explode ( ",", $sid );
foreach ( $sids as $ss ) {
if (! empty ( $ss )) {
$val = $I->read_bysid ( $ss );
$sname = $val ['fullname'];
$sid = $val ['sid'];
$str = $str . " <a href=\"item/detail/id/$sid\">$sname</a>";
}
}
return $str;
}
//计算优惠商家数量
function getnums($sid) {
$str = 0;
$sids = explode ( ",", $sid );
foreach ($sids as $ss) {
if(!empty($ss)) $str++;
}
return $str;
}
//获得商家信息
function getsubject($sid) {
global $I;
$mysubjects=array();
$sids = explode ( ",", $sid );
if (! empty ( $sids[0] )) {
$var = $I->read_bysid ( $sids[0] );
$mysubjects['thumb']= $var ['thumb'];
$mysubjects['avgprice']= $var ['avgprice'];
$mysubjects['mytags']=$I->get_mytag ( $var ['c_tags'] );
}
return $mysubjects;
}
// 倒记时
function jishi($day) {
$d1 = date ( 'Y-m-d H:i:s', $day );
$d2 = date ( 'Y-m-d H:i:s' );
if ($d1 < $d2)
return '已结束';
else {
$dd = floor ( (strtotime ( $d1 ) - strtotime ( $d2 )) / 3600 / 24 );
$hh = round ( (strtotime ( $d1 ) - strtotime ( $d2 )) % 86400 / 3600 );
return '还剩' . $dd . '天' . $hh . '小时';
}
}
?>
<file_sep>/templates/item/vip/review.php
<?exit?>
<!--{eval
$_HEAD['title'] = 大家对 . $detail[name] . $detail[subname] . 的评论;
}-->
<!--{template 'header', 'item', $detail[templateid]}-->
<link href="{URLROOT}/img/vipfiles/css/shopEx_$detail[c_vipstyle].css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
loadscript('swfobject');
$(document).ready(function() {
if(!$.browser.msie && !$.browser.safari) {
var d = $("#thumb");
var dh = parseInt(d.css("height").replace("px",''));
var ih = parseInt(d.find("img").css("height").replace("px",''));
if(dh - ih < 3) return;
var top = Math.ceil((dh - ih) / 2);
d.find("img").css("margin-top",top+"px");
}
<!--{if $MOD['show_thumb'] && $detail['pictures']}-->
get_pictures($sid);
<!--{/if}-->
get_membereffect($sid, $modelid);
});
</script>
<body>
<div class="wrap">
<div id="header">
<div id="crumb">
<p id="crumbL"><a href="{url modoer/index}">首页</a> » {print implode(' » ', $urlpath)} » $detail[name] $detail[subname]
<p id="crumbR"><a href="javascript:post_log($detail[sid]);">补充信息</a> | <a href="{url item/member/ac/subject_add/subbranch_sid/$detail[sid]}">增加分店</a> | <a href="{url member/index}">管理本店</a></p>
</div>
<div id="shopBanner">
<h1>$detail[name] $detail[subname]</h1>
<p>
<!--{if $detail[c_add]}-->
<B>地址:</B></LABEL>$detail[c_add]
<!--{/if}-->
<!--{if $detail[c_tel]}-->
<B>电话:</B></LABEL>$detail[c_tel]</p>
<!--{/if}-->
<div class="headerPic">
<img src="{if $detail[c_vipbanner]}$detail[c_vipbanner]{else}{URLROOT}img/haibao/nonbanner.png{/if}" alt="$detail[name] $detail[subname]店铺海报" width="950" height="150"/>
</div>
</div>
<div id="nav">
<ul>
<!--
<li><a href="#"><span>Array</span></a></li>
<li><a href="#"><span></span></a></li>
<li class="special"><a href="#"><span>导航栏介绍</span></a></li>
-->
<li><a href="{url item/detail/id/$detail[sid]}"><span>首页</span></a></li>
<li><a href="{url article/list/sid/$sid}"><span>店铺资讯</span></a> </li>
<li><a href="{url fenlei/list/sid/$sid}"><span>诚聘英才</span></a> </li>
<li><a href="{url product/list/sid/$sid}"><span>产品展厅</span></a> </li>
<li><a href="{url coupon/list/sid/$sid}"><span>优惠打折</span></a> </li>
<li><a href="{url item/pic/sid/$detail[sid]}"><span>商家相册</span></a> </li>
<li><a href="{url item/vipabout/id/$detail[sid]}"><span>关于我们</span></a></li>
<li class="current" ><a href="{url item/vipreview/id/$detail[sid]}"><span>会员点评</span></a></li>
<li><a href="{url item/vipguestbook/id/$detail[sid]}"><span>留言板</span></a></li>
</ul>
</div>
</div>
<div id="smartAd"><img src="{if $detail[c_vipbanner2]}$detail[c_vipbanner2]{else}{URLROOT}img/haibao/non.png{/if}" alt="$detail[name] $detail[subname]店铺海报"/></a><br />
</div>
<div id="mainBody">
<div id="mainBodyL">
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>【$detail[name] $detail[subname]】</h2>
<p class="deafBoxTitMore"><a href="{url item/vipabout/id/$detail[sid]}">更多</a></p>
</div>
<div class="deafBoxCon">
<dl>
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td valign="top">
<a href="{url item/pic/sid/$detail[sid]}"><img src="{URLROOT}/{if $detail[thumb]}$detail[thumb]{else}static/images/noimg.gif{/if}" alt="$detail[name]" width="110" height="80" /></a>
</td>
<td valign="top">
<!--{loop $reviewpot $val}-->$val[name]:<img src="{URLROOT}/img/vipfiles/img/z{print cfloat($detail[$val[flag]])}.gif" alt="{print cfloat($detail[$val[flag]])} 分" /><br /><!--{/loop}-->
综合:<img src="{URLROOT}/img/vipfiles/img/z{print cfloat($detail[avgsort])}.gif" alt="{print cfloat($detail[avgsort])} 分" />
</td>
</tr>
</table>
<p> </p>
<!--{if $detail[finer]}-->
店铺级别:<img src="{URLROOT}/img/vipfiles/img/vip$detail[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<p> </p>
<table class="custom_field" border="0" cellspacing="0" cellpadding="0">
$detail_custom_field
</table>
</dl>
</div>
</div>
<div id="position" class="deafBox">
<div class="deafBoxTit">
<h2>商户所在位置</h2>
</div>
<div class="deafBoxCon">
<!--{eval $mapparam = array(
'width' => '270',
'height' => '265',
'title' => $subject[name] . $subject[subname],
'show' => $detail[mappoint]?1:0,
);}-->
<iframe id="item_map" src="{url index/map/width/270/height/150/title/$mapparam[title]/p/$detail[mappoint]/show/$mapparam[show]}" frameborder="0" scrolling="no"></iframe>
<div align="center"> <span><!--{if !$detail['mappoint']}--><a href="javascript:post_map($detail[sid], $detail[pid]);">地图未标注,我来标注</a><!--{else}--><a href="javascript:show_bigmap();">查看大图</a> <a href="javascript:post_map($detail[sid], $detail[pid]);">报错</a><!--{/if}--></span></div>
<script type="text/javascript">
function show_bigmap() {
var src = "{url index/map/width/600/height/400/title/$mapparam[title]/p/$detail[mappoint]/show/$mapparam[show]}";
var html = '<iframe src="' + src + '" frameborder="0" scrolling="no" width="100%" height="400" id="ifupmap_map"></iframe>';
dlgOpen('查看大图', html, 600, 450);
}
</script>
</div>
</div>
</div>
<div id="chaBodyR">
<div id="chaBodyRTit">
<h2>会员点评</h2>
<p><a style="color:#FF3300;" href="{url item/member/ac/review_add/sid/$sid}" onClick="return post_review($sid);"><b>我要点评</b></a></p>
</div>
<div class="deafBoxCon">
<div class="winFloat">
<!--{if !$_G[in_ajax]}-->
<!--{if $detail[firstuid]}-->
<em>第一个点评:<span class="member-ico"><a href="{url space/index/uid/$detail[firstname]}" target="_blank">$detail[firstname]</a></span></em>
<!--{/if}-->
<div class="clear"></div>
<div id="display" style="margin-top:10px">
<!--{/if}-->
<!--{if $detail[reviews] || $total}-->
<!--{eval $index=1;}-->
<!--{dbres $reviews $val}-->
<div class="vipreview">
<div class="member m_w_item">
<!--{if $val[uid]}-->
<a href="{url space/index/uid/$val[uid]}"><img src="{print get_face($val[uid])}" class="face" alt="$val[username]"></a>
<!--{else}-->
<img src="{print get_face($val[uid])}" class="face">
<!--{/if}-->
<ul>
<!--{if $val[uid]}-->
<li>{print:member group(groupid/$val[groupid])}</li>
<li>积分:<span>$val[point]</span></li>
<!--{else}-->
<li>游客</li>
<!--{/if}-->
</ul>
</div>
<div class="field f_w_item">
<div class="feed">
<!--{if $val[uid]}-->
<span class="member-ico"> <a href="{url space/index/uid/$val[uid]}">$val[username]</a></span> ( <a href="javascript:send_message($val[uid]);">发短信</a>, <a href="javascript:add_friend($val[uid]);">加好友</a> )
<!--{else}-->
<span class="font_3">游客({print preg_replace("/^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/","\\1.\\2.*.*", $val[ip])})</span>
<!--{/if}-->
在 {date $val[posttime], 'w2style'} 进行了点评
<em>
<span class="respond-ico"><a href="javascript:get_respond('$val[rid]');">回应</a></span>(<span class="font_2" id="respond_$val[rid]">$val[responds]</span>条)
<span class="flower-ico"><a href="javascript:add_flower($val[rid]);">鲜花</a>(<a href="javascript:get_flower($val[rid]);"><span id="flower_$val[rid]" class="font_2">$val[flowers]</span>朵</a>)</span>
<a href="javascript:post_report($val[rid]);">举报</a>
</em>
</div>
<div class="info">
<ul class="score">
<!--{loop $reviewpot $_val}-->
<li>$_val[name]</li><li class="start{print cfloat($val[$_val[flag]])}"></li>
<!--{/loop}-->
</ul>
<div class="clear"></div>
<!--{if $val[pictures]}-->
<div class="pictures">
<!--{eval $val[pictures] = unserialize($val[pictures]);}-->
<!--{loop $val[pictures] $pic}-->
<a href="{URLROOT}/$pic[picture]"><img src="{URLROOT}/$pic[thumb]" onMouseOver="tip_start(this);" /></a>
<!--{/loop}-->
</div>
<!--{/if}-->
<div style="min-height:68px;">
<p>{print nl2br($val[content])}</p>
<ul class="params">
<!--{if $val[price] && $catcfg['useprice']}-->
<li>$catcfg[useprice_title]: <span class="font_2">$val[price]{$catcfg[useprice_unit]}</span></li>
<!--{/if}-->
<!--{eval $detail_tags = $val['taggroup'] ? @unserialize($val['taggroup']) : array();}-->
<!--{loop $taggroups $_key $_val}-->
<!--{if $detail_tags[$_key]}-->
<li>$_val[name]:
<!--{loop $detail_tags[$_key] $tagid $tagname}-->
<a href="{url item/tag/tagname/$tagname}">$tagname</a>
<!--{/loop}-->
</li>
<!--{/if}-->
<!--{/loop}-->
</ul>
</div>
<div id="flowers_$val[rid]"></div>
<div id="responds_$val[rid]"></div>
</div>
</div>
<div class="clear"></div>
</div>
<!--{if $index==1}-->
<div id="adv_1"></div>
<!--{/if}-->
<!--{eval $index++;}-->
<!--{/dbres}-->
<!--{if $multipage}-->
<div class="multipage">$multipage</div>
<!--{/if}-->
<!--{else}-->
<div class="messageborder"><span class="msg-ico">还没有点评,做第一个点评者?<span class="font_12"><a href="{url item/member/ac/review_add/sid/$sid}" onClick="return post_review($sid);">点击这里立即发布点评</a></span></span></div>
<!--{/if}-->
<!--{if !$_G[in_ajax]}-->
<!--{/if}-->
</div>
</div>
</div>
<div class="clear"></div>
</div>
<!--{template 'footer', 'item', $detail[templateid]}--><file_sep>/core/modules/about/admin/templates/config.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<?=form_begin(cpurl($module,$act))?>
<div class="space">
<div class="subtitle"><?=$MOD['name']?> 模块配置</div>
<ul class="cptab">
<li class="selected" id="btn_config1"><a href="#" onclick="tabSelect(1,'config');" onfocus="this.blur()">功能设置</a></li>
</ul>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" id="config1">
<tr>
<td class="altbg1" width="45%"><strong>默认显示页面:</strong>前台默认显示的访问页面。</span></td>
<td width="*">
<select name="modcfg[page]">
<option value="">默认显示页面</option>
<?=form_about_page($modcfg['page']);?>
</select>
</td>
</tr>
<tr>
<td class="altbg1"><strong>启用单页面内容过滤功能:</strong>对单页面内容进行词语过滤。<br />
<span class="font_1">过滤词库请在 网站管理=>词语过滤管理 中进行设置。</span></td>
<td><?=form_bool('modcfg[post_filter]', $modcfg['post_filter'])?></td>
</tr>
<tr>
<td class="altbg1" width="45%"><strong>关于我们的页面组:</strong>默认做为底部关于我们等页面的页面组。</span></td>
<td width="*">
<select name="modcfg[groupname]">
<option value="">默认页面组</option>
<?=form_page_group($modcfg['groupname']);?>
</select>
</td>
</tr>
</table>
</div>
<center><?=form_submit('dosubmit',lang('admincp_submit'),'yes','btn')?></center>
<?=form_end()?>
</div><file_sep>/core/modules/fenlei/admin/templates/category_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="post" name="myform" action="<?=cpurl($module,$act,'save')?>&">
<input type="hidden" name="catid" value="<?=$catid?>" />
<div class="space">
<div class="subtitle">增加/编辑分类</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1" width="45%"><strong>所属分类:</strong>选择子分类的父类。<span class="font_1">此项填写后将无法再次改动</span></td>
<td width="*">
<select name="category[pid]"<?if($op=='edit')echo' disabled';?>>
<option value="0">作为根目录</option>
<?=form_fenlei_category(0,$pid)?>
</select>
</td>
</tr>
<tr>
<td class="altbg1"><strong>分类名称:</strong></td>
<td><input type="text" name="category[name]" class="txtbox2" value="<?=$detail['name']?>" /></td>
</tr>
<tr>
<td class="altbg1"><strong>排序:</strong></td>
<td><input type="text" name="category[listorder]" class="txtbox4" value="<?=$detail['listorder']?>" /></td>
</tr>
<tr>
<td class="altbg1"><strong>列表页模板:</strong>定义自己设计的分类列表页模版,不需要填写模版后缀,例如fenlei_list<br />留空表示使用默认</td>
<td><input type="text" name="category[list_tpl]" class="txtbox2" value="<?=$detail['list_tpl']?>" /></td>
</tr>
</table>
<center>
<input type="hidden" name="forward" value="<?=get_forward()?>" />
<button type="submit" name="dosubmit" value="yes" class="btn" /> 提交 </button>
<button type="button" class="btn" onclick="history.go(-1);" /> 返回 </button>
</center>
</div>
</form>
</div><file_sep>/core/modules/item/wmlist.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
// 实例化主题类
$D = & $_G ['loader']->model ( 'item:takeout' );
//地理信息
$aid = ( int ) $_GET ['aid'];
// 载入地区
$area = $_G ['loader']->variable ( 'area_' . $_CITY ['aid'], null, false );
// 地区名称
$name = $area [$aid] ['name'];
// 查询的数组
$order_arr = array (
'listorder' => array ('s.c_listorder' => 'ASC'),
'addtime' => array ('addtime' => 'DESC'),
'pageviews' => array ('pageviews' => 'DESC')
);
$orderby='finer';
//查询条件
$where = array ();
$where['city_id'] = array(8);
$where['td.tagname'] = $name;
$where['status'] = array('where_not_equal',array('0'));
$num = 15;
$start = get_start ( $_GET ['page'], $num );
$select="sf.sid,sf.content,sf.c_dianhua,sf.c_dizhi,sf.c_yunye,sf.c_minprice,sf.c_sendprice,sf.c_minprice,sf.c_range,sf.c_jianjie,s.aid,s.pid,s.catid,s.name,s.subname,s.best,s.finer,s.map_lng,s.map_lat,s.fullname,s.status,s.pageviews";
list ( $total, $list ) = $D->find ($select, $where, $start, $num);
if ($total) {
$multipage = multi ( $total, $num, $_GET ['page'], url ( "item/wmlist/catid/$catid/aid/$aid/order/$order/type/$type/att/$atturl/num/$num/total/$total/wfpage/$wf_page/page/_PAGE_" ) );
}
$active = array ();
$active ['type'] [$type] = ' class="selected"';
$active ['num'] [$num] = ' class="selected"';
$active ['orderby'] [$orderby] = ' class="selected"';
// 最近的浏览COOKIE
include template ( 'item_waimai_list' );
// 解析Tags
function get_mytag($val) {
global $I;
return $I->get_mytag ( $val );
}
// 解析Att
function get_myatt($val) {
global $I;
return $I->get_myatt ( $val );
}
?><file_sep>/core/modules/tuan/helper/display.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class display_tuan {
//取得分类的名称或其它
//参数 catid,keyname
function category($params) {
extract($params);
if(!$keyname) $keyname = 'name';
if(!$catid) return '';
$loader =& _G('loader');
$category = $loader->variable('category','tuan');
if(!isset($category[$catid][$keyname])) return '';
return $category[$catid][$keyname];
}
// 计算出最终价格
// $total_price,$peoples_sell,$people_min
function average_price($params) {
extract($params);
if(!isset($total_price)||!isset($peoples_sell)) return '';
if(!$peoples_sell) $peoples_sell = (int)$peoples_min;
return round($total_price / $peoples_sell, 2);
}
// 计算出最终价格
// $prices,$goods_sell
function wholesale_price($params) {
extract($params);
if(!$prices||!isset($goods_sell)) return '';
$loader =& _G('loader');
$real_price = 0;
$T =& $loader->model(':tuan');
$prices = $T->parse_prices($prices);
foreach($prices as $num => $price) {
if(!$goods_sell) {
$real_price = $price;
break;
}
// 找到对应批发的价格
if($num >= $goods_sell) $real_price = $price;
}
return $real_price;
}
function forestall_price($params) {
extract($params);
if(!$prices||!isset($peoples_sell)||!isset($price)) return '';
$loader =& _G('loader');
$real_price = $price;
$T =& $loader->model(':tuan');
$prices = $T->forestall_parse_prices($prices);
foreach($prices as $num => $price) {
if(!$peoples_sell) {
$real_price = $price;
break;
}
// 找到对应批发的价格
if($peoples_sell+1 <=$num) {
$real_price = $price;
break;
}
}
return $real_price;
}
}
?><file_sep>/core/modules/tuan/admin/cjdata.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$Site =& $_G['loader']->model('tuan:cjdata');
$op = _input('op');
switch($op) {
case 'new':
$admin->tplname = cptpl('cjdata_save', MOD_FLAG);
break;
case 'edit':
$id = (int) $_GET['id'];
if(!$detail = $Site->read($id)) redirect('cjdata_empty');
$admin->tplname = cptpl('cjdata_save', MOD_FLAG);
break;
case 'save':
if($_POST['do']=='edit') {
if(!$id = (int)$_POST['id']) redirect(lang('global_sql_keyid_invalid','id'));
$forward = get_forward(cpurl($module,$act,'list'),1);
if(empty($forward )||strpos($forward,'cpmenu')) $def_url = cpurl($module,$act,'list');
} else {
$id = null;
$forward = cpurl($module,$act,'list');
}
$post = $Site->get_post($_POST);
$Site->save($post, $id);
redirect('global_op_succeed', $forward);
break;
case 'delete':
$Site->delete($_GET['id']);
redirect('global_op_succeed_delete', cpurl($module,$act));
break;
case 'spider':
set_time_limit(30);
$siteid=$_POST ['ids'];
$Site->spider($siteid);
//开始采集时间
$starttime=microtime();
if($siteid>0)
{
include ROOT_PATH.'/models/attach.php';
$site=$site_mod->GetOne('and id='.$siteid);
$attach=new attach($site);
//repurl:要采集的网址
//形如:http://www.meituan.com/api/v2/wuxi/deal
$myurl=str_replace('limengqi2','?',str_replace('limengqiurl1','&',$_REQUEST['repurl']));
//根据规则解析接口数据
$tempdata=$attach->parse_group($myurl);
//将数据插入临时表
if($id=$attach->insert_temp_table($tempdata))
{
if($id)
{
exit('{status:"success",siteid:"'.$site['id'].'",result:"采集成功",starttime:"'.$starttime.'",lasttime:"'.microtime().'"}');
}
else
{
exit('{status:"failed",siteid:"'.$site['id'].'",result:"入库失败"}');
}
}
else
{
exit('{status:"failed",siteid:"'.$site['id'].'",result:"采集失败"}');
}
}
break;
default:
$op = 'list';
$offset = 40;
$start = get_start($_GET['page'], $offset);
list($total, $list) = $Site->find('*', $where, 'sort', $start, $offset, TRUE);
if($total) {
$multipage = multi($total, $offset, $_GET['page'], cpurl($module, $act, 'list'));
}
$admin->tplname = cptpl('cjdata_list', MOD_FLAG);
}
?><file_sep>/img/vipfiles/js/common.js
//标签切换开始//
function setTab(area,id) {
var tabArea=document.getElementById(area);
var contents=tabArea.childNodes;
for(i=0; i<contents.length; i++) {
if(contents[i].className=='tabcontent'){contents[i].style.display='none';}
}
document.getElementById(id).style.display='';
var tabs=document.getElementById(area+'tabs').getElementsByTagName('a');
for(i=0; i<tabs.length; i++) { tabs[i].className='tab'; }
document.getElementById(id+'tab').className='tab curtab';
document.getElementById(id+'tab').blur();
}
//标签切换结束//
function ViewLen(){
var content = document.form1.lwcontent.value;
var sLen=content.length
if(sLen==0)
{
alert("留言不能为空!");
return false;
}
return true;
}
//-->
function addrows(id,rowsnum)
{
try{
document.getElementById(id).rows = document.getElementById(id).rows + rowsnum;
}catch(ex){
}
}
function selecttag(tagname) {
try {
if (document.getElementById("tag").value.indexOf(tagname) >= 0 ){
try {
document.getElementById("tag").value = document.getElementById("tag").value.replace(","+tagname,"");
} catch(e){}
try {
document.getElementById("tag").value = document.getElementById("tag").value.replace(tagname,"");
} catch(e){}
} else {
var value = document.getElementById("tag").value ;
var partner = "" ;
try {
partner = value.substring(value.length-1,value.length);
} catch(e){}
if (partner=="," || partner=="??") {
document.getElementById("tag").value = document.getElementById("tag").value + tagname ;
} else {
if (value !=null && value != "")
document.getElementById("tag").value = document.getElementById("tag").value +"," + tagname ;
else
document.getElementById("tag").value = document.getElementById("tag").value + tagname ;
}
}
} catch(e){}
}
function count_rmb(){
var people=document.getElementById("consumptionNumber").value;
var money=document.getElementById("consumptionTotal").value;
if(people!=0){
if(money!=0){
var count=money/people;
var strcount=""+count;
if(isNaN(count)||count<1 || people.indexOf(".") > 0){
document.getElementById("rjxf").innerHTML="<span><font color=\"red\">  (人均消费书写错误,请重新填写哦!)</font></span>";
return;
}
offset = strcount.indexOf(".", 0);
if(offset != -1)
{
for(var i=0;i<strcount.length;i++){
if(strcount.charCodeAt(i)==46){
strcount=strcount.substring(0,i+2);
}
}
}
document.getElementById("rjxf").innerHTML="<span class=\"G\">(人均:"+strcount+"元)</span>";
}
}
}
function validate(formData, jqForm, options) {
var serving = $('input[@name=serving]').fieldValue();
var taste = $('input[@name=taste]').fieldValue();
var price = $('input[@name=price]').fieldValue();
var environment = $('input[@name=environment]').fieldValue();
//var feeling = $('input[@name=feeling]').fieldValue();
var feeling=$('#feeling').text();
if(serving[0]==0)
{
alertmsg='<font color=red>请选择服务值!</font><br>';
document.getElementById("loading_tag").style.display="";
$('#loading_tag').html(alertmsg);
return false;
}
if(taste[0]==0)
{
alertmsg='<font color=red>请选择口味或质量值!</font><br>';
document.getElementById("loading_tag").style.display="";
$('#loading_tag').html(alertmsg);
return false;
}
if(environment[0]==0)
{
alertmsg='<font color=red>请选择环境值!</font><br>';
document.getElementById("loading_tag").style.display="";
$('#loading_tag').html(alertmsg);
return false;
}
if(price[0]==0)
{
alertmsg='<font color=red>请选择性价比值!</font><br>';
document.getElementById("loading_tag").style.display="";
$('#loading_tag').html(alertmsg);
return false;
}
if((feeling.length<10)&&(feeling.length>0))
{
alertmsg="<font color=red>消费感受字数不能小于10个!</font>";
document.getElementById("loading_tag").style.display="";
$('#loading_tag').html(alertmsg);
return false;
}
return true;
}
function confirmAct(usertype)
{
if(usertype==2)
{
//confirm('您是商户,不能参加点评!');
alert('您是商户,不能参加点评!');
return false;
}else
return true;
}
function confirmTextarea()
{
var content=document.getElementById('content').value;
var len=content.length;
//alert(len);
if(len==0)
{
alert("回应内容不能为空!");
return false;
}else
return true;
//document.form1.submit();
}
<file_sep>/core/modules/weixin/common.php
<?php
define('MOD_FLAG', 'weixin');
define('MOD_ROOT', MUDDER_MODULE . MOD_FLAG . DS);
if(!$_CITY) $_CITY = get_default_city();
if(!$_G['mod'] = read_cache(MUDDER_CACHE . MOD_FLAG.'_config.php')) {
if(isset($_G['modules'][MOD_FLAG])) {
$C =& $_G['loader']->model('config');
$C->write_cache(MOD_FLAG);
@include MOD_ROOT . 'inc' . DS . 'cache.php';
show_error('global_cache_module_succeed');
}
if(empty($_G['mod'])) {
redirect('global_module_not_install');
}
}
if(!$_G['modules'][MOD_FLAG]) redirect('global_module_disable');
$_G['mod'] = array_merge($_G['mod'], $_G['modules'][MOD_FLAG]);
$MOD =& $_G['mod'];
echo "song";
if(!defined('IN_ADMIN')) {
include MOD_ROOT . 'wxProcess.php';
}
?>
<file_sep>/core/modules/tuan/model/spider_class.php
<?php
class spider {
/**
* 初始化
* @param string $content
* @param array $site
*/
var $curl = 'null';
var $site = 'null';
public function spider($site) {
$this->site = $site;
//初始化采集类
$curlfile = 'core' . DS . 'modules' . DS . 'tuan' . DS . 'model' . DS . 'curl_class.php';
include MUDDER_ROOT . $curlfile;
$this->curl = new curl ();
}
/*
* 根据API规则解析采集回来的数据
* @content:采集的HTML页面内容
* @apirule:接口规则对应的规则PHP文件
*
*/
public function parse_rule($content, $apirule) {
$temp_rule = explode ( '=', $apirule );
$rule = $temp_rule [1];
//response-deals-data
$tmp = explode ( '-', $temp_rule [0] );
//处理采集的页面文字内容
$content = trim ( $content );
$content = str_replace ( "\n", "", $content );
$content = str_replace ( "\t", "", $content );
$content = str_replace ( "&", "shift7", $content );
//将采集的内容构造成XML文档
$node = new SimpleXMLElement ( $content );
unset ( $tmp [0] );
foreach ( $tmp as $r ) {
$node = $node->$r;
}
//解析XML文档
$data = array ();
$total = count ( $node );
if ($total <= 0) {
return false;
}
for($i = 0; $i < $total; $i ++) {
//subject: limengqikey-deal-deal_title
$fields = explode ( ',', $rule );
//提取字段名称
foreach ( $fields as $row ) {
$tmp = explode ( ':', $row );
$local_field_name = trim($tmp [0]); //subject
$local_field_struct = trim($tmp [1]); //limengqikey-deal-deal_title
$struct = str_replace ( 'limengqikey', '(string)$node[' . $i . ']', $local_field_struct );
$struct = '$tmp_data = ' . str_replace ( '-', '->', $struct ) . ';';
//把字符串按照 PHP 代码来计算
eval ( $struct );
$data [$i] [$local_field_name] = str_replace ( 'shift7', '&', $tmp_data );
}
}
return $data;
}
/**
* 根据规则解析接口数据
*
*/
public function parse_group($siteapi = '') {
$content = '';
$data = array ();
$citys = false;
if (! empty ( $siteapi )) {
//获得采集数据
$content = $this->curl->get ( $siteapi );
} else {
return false;
}
//根据接口规则名称加载规则内容
$apikey = $this->site ['apikey'];
$files = 'core' . DS . 'modules' . DS . 'tuan' . DS . 'model' . DS . 'crule' . DS . $apikey . '.php';
include MUDDER_ROOT . $files;
if (! empty ( $rule )) {
//返回信息数组
$mydata = $this->parse_rule ( $content, $rule );
//采集时有城市限制
//单个城市全部采集
//不使用采集的排序方法
if (! empty ( $this->site ['limitcity'] )) {
$limitcity = '-'.$this->site ['limitcity'];
foreach ( $mydata as $i => $v ) {
$v ['cityname'] = $this->charset_encode ( $v ['cityname'], 'gbk' );
if (strpos ( $limitcity, $v ['cityname'] )) {
$data [$i] = $this->process_fields ( $v );
if (empty ( $data [$i] ['subject'] ) || $data [$i] ['lasttime'] < time ()) {
unset ( $data [$i] );
}
}
}
}
}
return $data;
}
/**
*
*处理解析后的字段数据
* @param array $data
*
*/
private function process_fields($data = array()) {
$data ['subject'] = $this->global_addslashes ( str_replace ( "\n", "", $this->charset_encode ( $data ['subject'], 'gbk', 'utf-8' ) ) );
$data ['groupsite'] = $this->site ['sitename'];
$data ['bizname']=$this->charset_encode ( $data ['bizname'], 'gbk', 'utf-8' );
$data ['shopname']=$this->charset_encode ( $data ['shopname'], 'gbk', 'utf-8' );
$data ['catname']=$this->charset_encode ( $data ['catname'], 'gbk', 'utf-8' );
$data ['sortorder'] = 0;
$data ['shortsubject'] = '';
$data ['cityname'] = '无锡';
$data ['cityid'] = 'wuxi';
if (isset ( $data ['starttime'] )) {
if (strlen ( $data ['starttime'] ) == 14) {
$data ['starttime'] = mysql_to_unix ( $data ['starttime'] );
} else if (stripos ( $data ['starttime'], '+' ) !== false) {
$data ['starttime'] = strtotime ( $data ['starttime'] );
} else if (stripos ( $data ['starttime'], '-' ) !== false && strlen ( $data ['starttime'] ) == 19) {
$data ['starttime'] = mysql_to_unix ( $data ['starttime'] );
}
}
if (isset ( $data ['lasttime'] )) {
$data ['lasttime'] = trim ( $data ['lasttime'] );
if (strlen ( $data ['lasttime'] ) == 14) {
$data ['lasttime'] = mysql_to_unix ( $data ['lasttime'] );
} else if (stripos ( $data ['lasttime'], '+' ) !== false) {
$data ['lasttime'] = strtotime ( $data ['lasttime'] );
} else if (stripos ( $data ['lasttime'], '-' ) !== false && strlen ( $data ['lasttime'] ) == 19) {
$data ['lasttime'] = mysql_to_unix ( $data ['lasttime'] );
}
}
if (empty ( $data ['nowpeople'] )) {
$data ['nowpeople'] = 0;
}
$data ['oldprice'] = floatval ( $data ['oldprice'] );
$data ['nowprice'] = floatval ( $data ['nowprice'] );
if (! isset ( $data ['discount'] )) {
if ($data ['oldprice'] == 0 || $data ['nowprice'] == 0) {
$data ['discount'] = $data ['oldprice'];
} else {
$data ['discount'] = round ( ($data ['nowprice'] * 100 / $data ['oldprice']) / 10, 1 );
}
}
$data ['siteid'] = $this->site ['id'];
$data ['groupkey'] = md5 ( trim ( strip_tags ( $data ['subject'] ) ) . intval ( $data ['siteid'] ) . $data ['cityid'] );
$data ['updatetime'] = time ();
return $data;
}
//实现多种字符编码方式
function charset_encode($input, $_output_charset = 'utf-8', $_input_charset = "utf-8") {
$output = $input;
if (! isset ( $_output_charset ))
$_output_charset = $GLOBALS ['charset'];
if ($_input_charset == $_output_charset || $input == null) {
$output = $input;
} elseif (function_exists ( "mb_convert_encoding" )) {
$output = mb_convert_encoding ( $input, $_output_charset, $_input_charset );
} elseif (function_exists ( "iconv" )) {
$output = iconv ( $_input_charset, $_output_charset, $input );
}
return $output;
}
function global_addslashes($string, $force = 1) {
if ($force) {
$string = $this->stripslashes_deep ( $string );
if (is_array ( $string )) {
foreach ( $string as $key => $val ) {
$string [$key] = global_addslashes ( $val, $force );
}
} else {
$string = addslashes ( $string );
}
} else {
$string = stripslashes_deep ( $string );
}
return $string;
}
function stripslashes_deep($value) {
if (get_magic_quotes_gpc ()) {
$value = is_array ( $value ) ? array_map ( 'stripslashes_deep', $value ) : stripslashes ( $value );
}
return str_replace ( '\\', '', $value );
}
}
?>
<file_sep>/core/modules/discussion/assistant/topic.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
$op = _input('op');
$TP = $_G['loader']->model('discussion:topic');
switch($op) {
case 'post':
$post = $TP->get_post($_POST);
$tpid = _post('tpid',null,MF_INT_KEY);
if(!$tpid) $tpid = null;
if($MOD['topic_seccode']&&$tpid==null) check_seccode($_POST['seccode']);
$tpid = $TP->save($post, $tpid);
if(RETURN_EVENT_ID=='CHECK') {
redirect('global_op_succeed_check',url("discussion/topic/id/$tpid"));
} else {
if(DEBUG||defined('IN_AJAX')) redirect('global_op_succeed',url("discussion/topic/id/$tpid"));
location(url("discussion/topic/id/$tpid"));
}
break;
case 'edit':
$tpid = _input('tpid', null, MF_INT_KEY);
$detail = $TP->read($tpid);
if(empty($detail)) redirect('discussion_topic_empty');
if($detail['uid']!=$user->uid) redirect('global_op_access');
//表情
$smilies = array();
for ($i=1; $i <= 30; $i++) $smilies[$i] = "$i";
$tplname = 'topic_save';
break;
case 'delete':
$tpid = _input('tpid', null, MF_INT_KEY);
$detail = $TP->read($tpid);
$TP->delete($tpid);
location(url("discussion/list/sid/$detail[sid]"));
break;
default:
redirect('global_op_unknow');
}
?><file_sep>/core/modules/tuan/install/update.php.bak
<?php
!defined('IN_MUDDER') && exit('Access Denied');
class model_update extends ms_model {
public $flag = 'tuan';
public $moduleid = 0;
public $setp = 0;
public $start = 0;
public $index = 0;
public $params = array();
public $progress = 0;
public $total_setp = 1;
public $next_setp = false;
private $old_ver = '';
private $new_ver = '1.2.5';
public function __construct($moduleid,$old_ver) {
parent::__construct();
$this->loader->helper('sql');
$this->moduleid = $moduleid;
$this->old_ver = $old_ver;
$this->_check_version();
$this->step = (int) _get('step');
$this->step = $this->step < 1 || !$this->step ? 1 : $this->step;
$this->start = (int) _get('start');
$this->start = $this->start < 0 || !$this->start ? 0 : $this->start;
$this->index = (int) _get('index');
$this->index = $this->index < 0 || !$this->index ? 0 : $this->index;
}
public function updating() {
$method = '_step_' . $this->step;
if(method_exists($this, $method)) {
$this->$method();
} else {
echo sprintf('The required method "%s" does not exist for %s.', $method, get_class($this));
exit;
}
return $this;
}
public function completed() {
$this->params['moduleid'] = $this->moduleid;
$this->params['step'] = $this->step;
if($this->next_setp) {
$this->start = $this->index = 0;
}
$this->params['start'] = $this->start;
$this->params['index'] = $this->index;
$this->progress = round($this->step / $this->total_setp, 2);
if($this->progress>1) $this->progress = 1;
return $this->step > $this->total_setp;
}
private function _step_1() {
$array = array(
array('tuan', 'mode', 'change', "mode mode ENUM('normal','average','wholesale','forestall') NOT NULL DEFAULT 'normal'"),
array('tuan_coupon', 'sms_error', 'add', "sms_error SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0' AFTER sms_sendtime"),
);
if($detail = $array[$this->index]) {
sql_alter_field($detail[0], $detail[1], $detail[2], $detail[3]);
}
$this->index++;
$total = count($array);
if($this->index >= $total) {
$this->next_setp = true;
$this->step++;
}
}
private function _check_version() {
if($this->old_ver < '1.1') {
echo 'Please first upgrade your module(tuan) to version 1.1.';
exit;
}
if($this->old_ver < '1.2') {
echo 'Please first upgrade your module(tuan) to version 1.2.';
exit;
}
}
}
?><file_sep>/core/modules/tuan/help.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'tuan');
$_HEAD['keywords'] = $MOD['meta_keywords'];
$_HEAD['description'] = $MOD['meta_description'];
include template('tuan_help');
?><file_sep>/core/modules/about/inc/cache.php
<?php
/**
* @author 轩<<EMAIL>>
* @copyright (c)2009-2011 风格店铺
* @copyright 风格店铺(www.cmsky.org)
*/
!defined('IN_MUDDER') && exit('Access Denied');
inc_cache_about();
function inc_cache_about() {
$loader =& _G('loader');
$tmp =& $loader->model('config');
$tmp->write_cache('about');
$cachelist = array('about');
foreach ($cachelist as $value) {
$tmp =& $loader->model('about:'.$value);
$tmp->write_cache();
}
}
?><file_sep>/core/modules/about/helper/form.php
<?php
/**
* @author 轩<<EMAIL>>
* @copyright (c)2009-2011 风格店铺
* @copyright 风格店铺(www.cmsky.org)
*/
function form_about_page($select = '') {
$loader =& _G('loader');
if(!$page =& $loader->variable('page', 'about')) return;
$list = array();
foreach($page as $val) {
if($val['enabled']=='Y') $list[$val['mark']] = $val['pname'];
}
$loader->helper('form');
return form_option($list,$select);
}
function form_page_group($select='') {
$loader =& _G('loader');
$AP =& $loader->model('about:about');
if(!$groups = $AP->group_list()) return;
foreach(array_keys($groups) as $val) {
$select_arr[$val] = $val;
}
$loader->helper('form');
return form_option($select_arr,$select);
}
?><file_sep>/templates/item/vip/index.php
<?exit?>
<!--{template 'header', 'item', $detail[templateid]}-->
<script type="text/javascript">
loadscript('swfobject');
$(document).ready(function() {
if(!$.browser.msie && !$.browser.safari) {
var d = $("#thumb");
var dh = parseInt(d.css("height").replace("px",''));
var ih = parseInt(d.find("img").css("height").replace("px",''));
if(dh - ih < 3) return;
var top = Math.ceil((dh - ih) / 2);
d.find("img").css("margin-top",top+"px");
}
<!--{if $MOD['show_thumb'] && $detail['pictures']}-->
get_pictures($sid);
<!--{/if}-->
get_membereffect($sid, $modelid);
});
</script>
<link href="{URLROOT}/img/vipfiles/css/shopEx_$detail[c_vipstyle].css" rel="stylesheet" type="text/css" />
<style type="text/css">
.picshow { z-index:444; position:relative; background-color:#e4f2fa; width: 100%; height: 250px}
.picshow_main { position: relative; width: 600px; height: 300px}
.picshow_main .imgbig { filter: progid:dximagetransform.microsoft.wipe(gradientsize=1.0,wipestyle=4, motion=forward); width: 600px; height: 300px}
.picshow_change {position: absolute; text-align: left; bottom: 0px; height: 30px; right: 0px; left: 510px;}
.picshow_change img {width:15px; height: 15px}
.picshow_change a { border: 1px solid; display: block; float: left; margin-right: 5px; -display: inline}
a.axx { border-color: #555}
a.axx:hover {border-color: #000}
a.axx img { filter: alpha(opacity=40); opacity: 0.4; -moz-opacity: 0.4}
a.axx:hover img {filter: alpha(opacity=100); opacity: 1.0; -moz-opacity: 1.0}
a.bxx { border-color: #000}
a.bxx:hover {border-color: #000}
img{
border:0px}
</style>
<body>
<div class="wrap">
<div id="header">
<div id="crumb">
<p id="crumbL"><a href="{url modoer/index}">首页</a> » {print implode(' » ', $urlpath)} » $detail[name] $detail[subname]
<p id="crumbR"><a href="javascript:post_log($detail[sid]);">补充信息</a> | <a href="{url item/member/ac/subject_add/subbranch_sid/$detail[sid]}">增加分店</a> | <a href="{url member/index}">管理本店</a></p>
</div>
<div id="shopBanner">
<h1>$detail[name] $detail[subname]</h1>
<p>
<!--{if $detail[c_add]}-->
<B>地址:</B></LABEL>$detail[c_add]
<!--{/if}-->
<!--{if $detail[c_tel]}-->
<B>电话:</B></LABEL>$detail[c_tel]</p>
<!--{/if}-->
<div class="headerPic">
<img src="{if $detail[c_vipbanner]}$detail[c_vipbanner]{else}{URLROOT}/img/haibao/nonbanner.png{/if}" alt="$detail[name] $detail[subname]店铺海报" width="950" height="150"/>
</div>
</div>
<div id="nav">
<ul>
<li class="current" ><a href="{url item/detail/id/$detail[sid]}"><span>首页</span></a></li>
<li><a href="{url article/list/sid/$sid}"><span>店铺资讯</span></a> </li>
<li><a href="{url fenlei/list/sid/$sid}"><span>诚聘英才</span></a> </li>
<li><a href="{url product/list/sid/$sid}"><span>产品展厅</span></a> </li>
<li><a href="{url coupon/list/sid/$sid}"><span>优惠打折</span></a> </li>
<li><a href="{url item/pic/sid/$detail[sid]}"><span>商家相册</span></a> </li>
<li><a href="{url item/vipabout/id/$detail[sid]}"><span>关于我们</span></a></li>
<li><a href="{url item/vipreview/id/$detail[sid]}"><span>会员点评</span></a></li>
<li><a href="{url item/vipguestbook/id/$detail[sid]}"><span>留言板</span></a></li>
</ul>
</div>
</div>
<div id="smartAd"><img src="{if $detail[c_vipbanner2]}$detail[c_vipbanner2]{else}{URLROOT}/img/haibao/non.png{/if}" alt="$detail[name] $detail[subname]店铺海报"/></a><br />
</div>
<div id="mainBody">
<div id="mainBodyL">
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>【$detail[name] $detail[subname]】</h2>
<p class="deafBoxTitMore"><a href="{url item/vipabout/id/$detail[sid]}">更多</a></p>
</div>
<div class="deafBoxCon">
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td valign="top">
<a href="{url item/pic/sid/$detail[sid]}"><img src="{URLROOT}/{if $detail[thumb]}$detail[thumb]{else}static/images/noimg.gif{/if}" alt="$detail[name]" width="110" height="80" /></a>
</td>
<td valign="top">
<!--{loop $reviewpot $val}-->$val[name]:<img src="{URLROOT}/img/vipfiles/img/z{print cfloat($detail[$val[flag]])}.gif" alt="{print cfloat($detail[$val[flag]])} 分" /><br /><!--{/loop}-->
综合:<img src="{URLROOT}/img/vipfiles/img/z{print cfloat($detail[avgsort])}.gif" alt="{print cfloat($detail[avgsort])} 分" />
</td>
</tr>
</table>
<p> </p>
<!--{if $detail[finer]}-->
店铺级别:<img src="{URLROOT}/img/vipfiles/img/vip$detail[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<p> </p>
<table class="custom_field" border="0" cellspacing="0" cellpadding="0">
$detail_custom_field
</table>
</div>
</div>
<div id="coupons" class="deafBox">
<div class="deafBoxTit">
<h2><a href="{url coupon/list/sid/$sid}">优惠券</a></h2>
<p class="deafBoxTitMore"><a href="{url coupon/list/sid/$sid}" target="_blank">更多</a></p>
</div>
<div class="deafBoxCon">
<div class="couponOne">
<!--{get:coupon val=list_subject(sid/$sid/orderby/dateline DESC/rows/2)}-->
<h3><a href="{url coupon/detail/id/$val[couponid]}" title="$val[subject]">{sublen $val[subject],12}</a></h3>
<!--{/get}-->
</div>
<ul class="couponBtn">
<li class="couponBtnPrint"><a href="{url coupon/list/sid/$sid}">打印</a></li>
</ul>
</div>
</div>
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>本店资讯</h2>
<p class="deafBoxTitMore"><a href="{url article/list/sid/$sid}}" target="_blank">更多</a></p>
</div>
<div class="deafBoxCon">
<ul class="rail-list">
<!--{get:article val=getlist(sid/$sid/orderby/dateline DESC/rows/5)}-->
<li><cite>{date $val[dateline],'m-d'}</cite><a href="{url article/detail/id/$val[articleid]}" title="$val[subject]">{sublen $val[subject],16}</a></li>
<!--{getempty(val)}-->
<li>暂无信息</li>
<!--{/get}-->
</ul>
</div>
</div>
<!--{if $catcfg[use_subbranch]}-->
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>分店</h2>
</div>
<div class="deafBoxCon">
<!--{eval
$name = _T($detail[name]);
$city_id = $_CITY[aid];
}-->
<!--{datacallname:主题_vip_分店}-->
</div>
</div>
<!--{/if}-->
<div id="position" class="deafBox">
<div class="deafBoxTit">
<h2>商户所在位置</h2>
</div>
<div class="deafBoxCon">
<!--{eval $mapparam = array(
'width' => '270',
'height' => '265',
'title' => $subject[name] . $subject[subname],
'show' => $detail[mappoint]?1:0,
);}-->
<iframe id="item_map" src="{url index/map/width/280/height/150/title/$mapparam[title]/p/$detail[mappoint]/show/$mapparam[show]}" frameborder="0" scrolling="no"></iframe>
<div align="center"> <span><!--{if !$detail['mappoint']}--><a href="javascript:post_map($detail[sid], $detail[pid]);">地图未标注,我来标注</a><!--{else}--><a href="javascript:show_bigmap();">查看大图</a> <a href="javascript:post_map($detail[sid], $detail[pid]);">报错</a><!--{/if}--></span></div>
<script type="text/javascript">
function show_bigmap() {
var src = "{url index/map/width/600/height/400/title/$mapparam[title]/p/$detail[mappoint]/show/$mapparam[show]}";
var html = '<iframe src="' + src + '" frameborder="0" scrolling="no" width="100%" height="400" id="ifupmap_map"></iframe>';
dlgOpen('查看大图', html, 600, 450);
}
</script>
</div>
</div>
</div>
<div id="mainBodyR">
<div id="advan" class="deafBox">
<div class="deafBoxTit">
<h3 class="tabs" id="advantabs">
<a class="tab curtab" id="aadvantab" onMouseOver="javascript:setTab('advan','aadvan')"><span>橱窗推荐</span></a>
<a class="tab" id="cadvantab" onMouseOver="javascript:setTab('advan','cadvan')"><span>商家视频</span></a>
<a class="tab" id="dadvantab" onMouseOver="javascript:setTab('advan','dadvan')"><span>全景逛店</span></a>
</h3>
</div>
<div class="tabcontent" id="aadvan">
<div id="slide">
<div id="picFlow">
<SCRIPT language=javascript>
//图片滚动展示 Start
var counts = 3;
//大图//
img1 = new Image();
img1.src = '$detail[c_vipredian]';
img2 = new Image();
img2.src = '$detail[c_vipredian2]';
img3 = new Image();
img3.src = '$detail[c_vipredian3]';
var smallImg = new Array();
//小图
smallImg[0] = 'img/vipfiles/img/index_adb1.gif';
smallImg[1] = 'img/vipfiles/img/index_adb2.gif';
smallImg[2] = 'img/vipfiles/img/index_adb3.gif';
//链接地址
url1 = new Image();
url1.src = ' $_CFG[siteurl]';
url2 = new Image();
url2.src = ' $_CFG[siteurl]';
url3 = new Image();
url3.src = ' $_CFG[siteurl]';
//alt值
alt1 = new Image();
alt1.alt = '$detail[name] $detail[subname] ';
alt2 = new Image();
alt2.alt = '$detail[name] $detail[subname] ';
alt3 = new Image();
alt3.alt = '$detail[name] $detail[subname] ';
////欢迎来到标准之路.
var nn = 1;
var key = 0;
function change_img() {
if (key == 0) {
key = 1;
} else if (document.all) {
document.getElementById("pic").filters[0].Apply();
document.getElementById("pic").filters[0].Play(duration = 2);
}
eval('document.getElementById("pic").src=img' + nn + '.src');
eval('document.getElementById("url").href=url' + nn + '.src');
eval('document.getElementById("pic").alt=alt' + nn + '.alt');
if (nn == 1) {
document.getElementById("url").target = "_blank";
document.getElementById("url").style.cursor = "pointer";
} else {
document.getElementById("url").target = "_blank"
document.getElementById("url").style.cursor = "pointer"
}
for ( var i = 1; i <= counts; i++) {
document.getElementById("xxjdjj" + i).className = 'axx';
}
document.getElementById("xxjdjj" + nn).className = 'bxx';
nn++;
if (nn > counts) {
nn = 1;
}
tt = setTimeout('change_img()', 7000);
}
function changeimg(n) {
nn = n;
window.clearInterval(tt);
change_img();
}
function ImageShow() {
document.write('<div class="picshow_main">');
document.write('<div><a id="url"><img id="pic" class="imgbig" /></a></div>');
document.write('<div class="picshow_change">');
for ( var i = 0; i < counts; i++) {
document.write('<a href="javascript:changeimg(' + (i + 1)
+ ');" id="xxjdjj' + (i + 1)
+ '" class="axx" target="_self"><img src="' + smallImg[i]
+ '"></a>');
}
document.write('</div></div>');
change_img();
}
//图片滚动展示 End
</SCRIPT>
<SCRIPT language="javascript" type="text/javascript">
ImageShow();
</SCRIPT>
</div>
</div>
</div>
<div class="tabcontent" id="badvan" style="display: none">
<div id="view360">
<iframe src="#" height="100%" width="100%" scrolling="no" frameborder="0"></iframe>
</div>
</div>
<div class="tabcontent" id="cadvan" style="display: none">
<div id="video">
<div class="mainrail" style="text-align:center;" id="video_foo">
<!--{if $detail[video]}-->
<div class="mainrail" style="text-align:center;" id="video_foo"></div>
<script type="text/javascript">
$(document).ready(function() {
var so = new SWFObject("$detail[video]", 'video1', 440, 350, 7, '#FFF');
so.addParam("allowScriptAccess", "always");
so.addParam("allowFullScreen", "true");
so.addParam("wmode", "transparent");
so.write("video_foo");
});
</script>
<!--{else}-->
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="440" height="350">
<param name="movie" value="{URLROOT}/{$_G[tplurl]}ads/flvplayer.swf">
<param name="quality" value="high">
<param name="allowFullScreen" value="true" />
<param name="FlashVars" value="vcastr_file={URLROOT}/{$_G[tplurl]}ads/1.flv|{URLROOT}/{$_G[tplurl]}ads/2.flv{URLROOT}/{$_G[tplurl]}ads/3.flv&vcastr_title=视频广告招商|视频广告招商|定州百姓网&BarColor=0xFFffff&BarPosition=1&IsShowBar=3&BarTransparent=10&LogoText=Dingzhou.Biz&IsAutoPlay=0&IsContinue=1" />
</object>
<!--{/if}-->
</div>
</div>
</div>
<div class="tabcontent" id="dadvan" style="display: none">
<div id="video">
<!--{if $detail[c_qj]}-->
<object id="video" name="video" width="440" height="350">
<param name="movie" value="$detail[c_qj]"></param>
<param name="allowScriptAccess" value="always"></param>
<param name="allowFullScreen" value="true"></param>
<param name="wmode" value="transparent"></param>
<embed src="$detail[c_qj]" type="application/x-shockwave-flash" width="480" height="397" allowFullScreen="true" wmode="transparent" allowScriptAccess="always"></embed>
</object>
<!--{else}-->
<object id="video" name="video" width="440" height="350">
<param name="movie" value="{URLROOT}/img/vipfiles/img/360swf.swf" type="application/x-shockwave-flash"></param>
<param name="allowScriptAccess" value="always"></param>
<param name="allowFullScreen" value="true"></param>
<param name="wmode" value="transparent"></param>
<embed src="{URLROOT}/img/vipfiles/img/360swf.swf" type="application/x-shockwave-flash" width="440" height="350" allowFullScreen="true" wmode="transparent" allowScriptAccess="always"></embed>
</object>
<!--{/if}-->
</div>
</div>
</div>
<!--{if $_G['modules']['product'] && $detail['products']}-->
<div id="mediaNews" class="deafBox">
<div class="deafBoxTit">
<h2>店铺产品</h2>
<p class="deafBoxTitMore"> <a href="{url article/list/sid/$sid}">更多</a></p>
</div>
<div class="deafBoxCon">
<div class="winFloat">
<div id="mediaNewsL"><div class="shopAcPic">
<!--{datacallname:主题产品_vip_pic}-->
</div> </div>
<div id="mediaNewsR">
<ul>
<!--{datacallname:主题产品_vip_li}-->
</ul>
</div>
</div>
</div>
</div>
<!--{/if}-->
<div id="mediaNews" class="deafBox">
<div class="deafBoxTit">
<h2>商家相册</h2>
<p class="deafBoxTitMore"> <a href="{url item/pic/sid/$detail[sid]}">查看全部</a></p>
</div><div class="deafBoxCon">
<div class="winFloat">
<div class="listCon">
<ul id="roll">
{get:modoer val=table(table/dbpre_pictures/select/*/where/sid=$detail[sid] and status=1/orderby/addtime DESC/rows/8/cachetime/10)}
<div class="photoTwo">
<div class="photoTwoPic"><a href="$val[filename]" src="$val[thumb]" target="_blank" onmouseover="tip_start(this,732);"><img src="$val[thumb]" alt="<!--{if $val[comments]}-->说明:$val[comments]<!--{else}-->商家:$detail[name] $detail[subname]<!--{/if}-->上传:<!--{if $val[uid]==0}-->$val[username]<!--{else}-->$val[username]<!--{/if}--> 日期:{date $val[addtime],'y-m-d'}" width="120" height="90"/></a></div>
<h3>{sublen $detail[name],8,'...'}
<p>上传:<!--{if $val[uid]==0}-->$val[username]<!--{else}-->$val[username]<!--{/if}--></p></h3>
<p></p>
</div>
{/get} <ul>
<link rel="stylesheet" type="text/css" href="img/vipfiles/css/lightbox.css" />
<script type="text/javascript" src="img/vipfiles/css/lightbox.js"></script>
<script type="text/javascript">
$(function() { $('#roll a').lightBox(); });
</script>
</div>
</div>
<p class="photoMore"><a href="{url item/member/ac/pic_upload/sid/$sid}">上传图片</a></p>
</div>
</div>
<div id="mediaNews" class="deafBox">
<div class="deafBoxTit">
<h2>会员点评</h2>
<p class="deafBoxTitMore"> <a href="{url review/member/ac/add/type/item_subject/id/$sid}" onClick="return post_review($sid)">我要点评</a></p>
</div><div class="deafBoxCon">
<div class="winFloat">
<!--{if !$_G[in_ajax]}-->
<!--{if $detail[firstuid]}-->
<em>第一个点评:<span class="member-ico"><a href="{url space/index/uid/$detail[firstname]}" target="_blank">$detail[firstname]</a></span></em>
<!--{/if}-->
<div class="clear"></div>
<div id="display" style="margin-top:10px">
<!--{/if}-->
<!--{if $detail[reviews] || $total}-->
<!--{eval $index=1;}-->
<!--{dbres $reviews $val}-->
<div class="vipreview">
<div class="member m_w_item">
<!--{if $val[uid]}-->
<a href="{url space/index/uid/$val[uid]}"><img src="{print get_face($val[uid])}" class="face" alt="$val[username]"></a>
<!--{else}-->
<img src="{print get_face($val[uid])}" class="face">
<!--{/if}-->
<ul>
<!--{if $val[uid]}-->
<li>{print:member group(groupid/$val[groupid])}</li>
<li>积分:<span>$val[point]</span></li>
<!--{else}-->
<li>游客</li>
<!--{/if}-->
</ul>
</div>
<div class="field f_w_item">
<div class="feed">
<!--{if $val[uid]}-->
<span class="member-ico"> <a href="{url space/index/uid/$val[uid]}">$val[username]</a></span> ( <a href="javascript:send_message($val[uid]);">发短信</a>, <a href="javascript:add_friend($val[uid]);">加好友</a> )
<!--{else}-->
<span class="font_3">游客({print preg_replace("/^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$/","\\1.\\2.*.*", $val[ip])})</span>
<!--{/if}-->
在{date $val[posttime], 'w2style'}进行了点评
<em>
<span class="respond-ico"><a href="javascript:get_respond('$val[rid]');">回应</a></span>(<span class="font_2" id="respond_$val[rid]">$val[responds]</span>条)
<span class="flower-ico"><a href="javascript:add_flower($val[rid]);">鲜花</a>(<a href="javascript:get_flower($val[rid]);"><span id="flower_$val[rid]" class="font_2">$val[flowers]</span>朵</a>)</span>
<a href="javascript:post_report($val[rid]);">举报</a>
</em>
</div>
<div class="info">
<ul class="score">
<!--{loop $reviewpot $_val}-->
<li>$_val[name]</li><li class="start{print cfloat($val[$_val[flag]])}"></li>
<!--{/loop}-->
</ul>
<div class="clear"></div>
<!--{if $val[pictures]}-->
<div class="pictures">
<!--{eval $val[pictures] = unserialize($val[pictures]);}-->
<!--{loop $val[pictures] $pic}-->
<a href="{URLROOT}/$pic[picture]"><img src="{URLROOT}/$pic[thumb]" onMouseOver="tip_start(this);" /></a>
<!--{/loop}-->
</div>
<!--{/if}-->
<div style="min-height:68px;">
<p>{print nl2br($val[content])}</p>
<ul class="params">
<!--{if $val[price] && $catcfg['useprice']}-->
<li>$catcfg[useprice_title]: <span class="font_2">$val[price]{$catcfg[useprice_unit]}</span></li>
<!--{/if}-->
<!--{eval $detail_tags = $val['taggroup'] ? @unserialize($val['taggroup']) : array();}-->
<!--{loop $taggroups $_key $_val}-->
<!--{if $detail_tags[$_key]}-->
<li>$_val[name]:
<!--{loop $detail_tags[$_key] $tagid $tagname}-->
<a href="{url item/tag/tagname/$tagname}">$tagname</a>
<!--{/loop}-->
</li>
<!--{/if}-->
<!--{/loop}-->
</ul>
</div>
<div id="flowers_$val[rid]"></div>
<div id="responds_$val[rid]"></div>
</div>
</div>
<div class="clear"></div>
</div>
<!--{if $index==1}-->
<div id="adv_1"></div>
<!--{/if}-->
<!--{eval $index++;}-->
<!--{/dbres}-->
<!--{if $multipage}-->
<div class="multipage">$multipage</div>
<!--{/if}-->
<!--{else}-->
<div class="messageborder"><span class="msg-ico">还没有点评,做第一个点评者?<span class="font_12"><a href="{url item/member/ac/review_add/sid/$sid}" onClick="return post_review($sid);">点击这里立即发布点评</a></span></span></div>
<!--{/if}-->
<!--{if !$_G[in_ajax]}-->
<!--{/if}-->
</div>
</div>
</div>
</div>
</div>
<!--{template 'footer', 'item', $detail[templateid]}-->
<file_sep>/core/modules/fenlei/install/module_uninstall.sql
DROP TABLE IF EXISTS modoer_fenlei_category;
DROP TABLE IF EXISTS modoer_fenlei;<file_sep>/core/admin/templates/cpfooter.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="footer">
<small>Powered by modoer</small><br />
<small><?=$sitedebug?></small>
</div>
<?=$DEBUG?>
</body>
</html><file_sep>/templates/item/vip/fenlei_detailbak.php
<?exit?>
<!--{eval
$_HEAD['title'] = $detail[subject];
}-->
<!--{template 'header', 'item', $detail[templateid]}-->
<script type="text/javascript">
function copyToClipboard(txt) {
if(window.clipboardData) {
window.clipboardData.clearData();
window.clipboardData.setData("Text", txt);
} else if(navigator.userAgent.indexOf("Opera") != -1) {
window.location = txt;
} else if (window.netscape) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
} catch (e) {
alert("被浏览器拒绝!\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");
return;
}
var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
if (!clip)
return;
var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
if (!trans)
return;
trans.addDataFlavor('text/unicode');
var str = new Object();
var len = new Object();
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
var copytext = txt;
str.data = copytext;
trans.setTransferData("text/unicode",str,copytext.length*2);
var clipid = Components.interfaces.nsIClipboard;
if (!clip)
return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
alert("已复制到剪贴板。");
}
function AddFavorite(sURL, sTitle) {
try {
window.external.addFavorite(sURL, sTitle);
} catch (e) {
try {
window.sidebar.addPanel(sTitle, sURL, "");
} catch (e) {
alert("加入收藏失败,请使用Ctrl+D进行添加");
}
}
}
</script>
<div id="body">
<div class="link_path">
<em><span class="review-ico"><a href="{url fenlei/member/ac/manage/op/add}"><b>发布信息</b></a></span></em>
<div class="home-ico"><a href="{url modoer/index}">$_CITY[name]</a> » {print implode(' » ', $urlpath)}
</div> </div>
<div id="fenlei_right">
<div class="mainrail rail-border-3">
<h3 class="rail-h-3 rail-h-bg-3">组织者信息</h3>
<table class="sponsor-table">
<tr>
<td class="face" valign="top"><img src="{print get_face($detail[uid])}" title="$detail[uid]" /></td>
<td class="sponsor" valign="top">
<ul>
<!--{if $detail[uid]}-->
<li><a href="{url space/index/uid/$detail[uid]}">$detail[username]</a></li>
{get:member val=detail(uid/$detail[uid])}
<li>会员组:{print:member group(groupid/$val[groupid])}</li>
{/get}
<!--{else}-->
<li><span class="font_1"><b>网站发布的信息</b></span></li>
<!--{/if}-->
<li>联系人:$detail[linkman]</li>
</ul>
</td>
</tr>
</table>
</div>
<!--{if $subject}-->
<script type="text/javascript">loadscript('item');</script>
<div class="mainrail rail-border-3">
<h2 class="rail-h-2"><b><a href="{url item/detail/id/$subject[sid]}"><span class="font_2">$subject[name] $subject[subname]</span></a></b></h2>
<div class="subject">
<!--{eval $itemcfg=$_G['loader']->variable('config','item');}-->
<p class="start start{print get_star($subject[avgsort],$itemcfg[scoretype])}"></p>
<table class="subject_field_list" border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2"><span class="font_2">$subject[reviews]</span>点评,
<span class="font_2">$subject[guestbooks]</span>留言,
<span class="font_2">$subject[pageviews]</span>浏览</td>
</tr>
$subject_field_table_tr
</table>
<a class="abtn1" href="{url review/member/ac/add/type/item_subject/id/$subject[sid]}"><span>我要点评</span></a>
<a class="abtn2" href="javascript:add_favorite($subject[sid]);"><span>收藏</span></a>
<a class="abtn2" href="{url item/detail/id/$subject[sid]/view/guestbook}#guestbook"><span>留言</span></a>
<div class="clear"></div>
</div>
</div>
<div class="mainrail rail-border-3">
<em><a href="{url fenlei/list/sid/$detail[sid]}">更多</a></em>
<h3 class="rail-h-3 rail-h-bg-3">主题其他信息</h3>
<ul class="rail-list">
{get:fenlei val=getlist(sid/$detail[sid]/row/10)}
<li><cite>{date $val[dateline],'m-d'}</cite><a href="{url fenlei/detail/id/$val[fid]}">{sublen $val[subject],20}</a></li>
{/get}
</ul>
</div>
<!--{/if}-->
<!--{if $detail[uid]}-->
<div class="mainrail rail-border-3">
<h3 class="rail-h-3 rail-h-bg-3">会员发布的其他信息</h3>
<ul class="rail-list">
{get:fenlei val=getlist(uid/$detail[uid]/row/10)}
<li><cite>{date $val[dateline],'m-d'}</cite><a href="{url fenlei/detail/id/$val[fid]}">{sublen $val[subject],20}</a></li>
{/get}
</ul>
</div>
<!--{/if}-->
<!--{if $detail[mappoint]}-->
<div class="mainrail">
<!--{eval $mapparam = array(
'width' => '300',
'height' => '245',
'title' => $detail[subject],
'p' => $detail[mappoint],
'show' => $detail[mappoint]?1:0,
);}-->
<iframe src="{URLROOT}/index.php?act=map&{print url_implode($mapparam)}" frameborder="0" scrolling="no" height="245" width="300"></iframe>
</div>
<!--{/if}-->
</div>
<div id="fenlei_left">
<div class="mainrail fenlei">
<div class="field">
<div class="head">
<!--{if $detail[endtime]<=$_G['timestamp']}-->
<em><span class="font_1"><strong>信息已过期</strong></span></em>
<!--{/if}-->
<h3>$detail[subject]</h3>
<div class="op">
发布者:<a href="{url space/index/suid/$val[uid]}">$detail[username]</a>
发布时间:{date $detail[dateline],'Y-m-d H:i'}
过期时间:{date $detail[endtime],'Y-m-d'}
<a href="#" onclick="AddFavorite(window.location.href,'$detail[subject]')">收藏</a>
<a href="#" onclick="copyToClipboard(window.location.href);">分享</a>
<a href="#" onclick="window.print();">打印</a></span>
</div>
</div>
<!--{if $detail_custom_field}-->
<table width="100%" border="0" cellspacing="0" cellpadding="0">
$detail_custom_field
</table>
<!--{/if}-->
</div>
<div class="info">{print nl2br($detail[content])}</div>
<!--{if $detail[thumb]}-->
<div class="pics"><a href="{URLROOT}/{print str_replace('thumb_', '', $detail[thumb])}" target="_blank"><img src="{URLROOT}/{$detail[thumb]}" /></a></div>
<!--{/if}-->
<div class="contcat">
<ul>
<li>联 系 人:$detail[linkman]</li>
<li>联系电话:$detail[contact]</li>
<li>电子邮箱:$detail[email]</li>
<li>QQ/MSN:$detail[im]</li>
<li>联系地址:$detail[address]</li>
</ul>
<div class="waring"><center>免责声明:本站只提供信息交流平台,各交易者自己审辨真假,本站不承担由此引起的法律责任。</center></div>
</div>
</div>
<!--
<div class="mainrail rail-border-3">
<h3 class="rail-h-3 rail-h-bg-3">会员评论</h3>
<table style="margin-top:10px" width="100%" class="post table">
<tr>
<td width="100" align="right" valign="top">评论内容:</td>
<td width="*"><textarea name="content" style="width:95%;height:80px;"></textarea></td>
</tr>
<tr><td> </td><td><input type="submit" value="发布评论" class="button" /></td></tr>
</table>
<div class="fenlei comment">
<div></div>
</div>
</div>
-->
</div>
<div class="clear"></div>
</div>
<!--{template 'footer', 'item', $detail[templateid]}--><file_sep>/core/modules/mobile/assistant/index.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
include mobile_template('member_index');<file_sep>/core/modules/party/admin/templates/picture_check.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="post" name="myform" action="<?=cpurl($module,$act)?>&">
<div class="space">
<div class="subtitle">图片审核</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" id="config1" trmouse="Y">
<tr class="altbg1">
<td width="25">选</td>
<td width="*">图片</td>
<td width="150">名称</td>
<td width="150">上传用户</td>
<td width="150">活动名称</td>
</tr>
<?if($total):?>
<?while($val = $list->fetch_array()):?>
<tr>
<td><input type="checkbox" name="picids[]" value="<?=$val['picid']?>" /></td>
<td><a href="<?=$val['pic']?>" target="_blank"><img src="<?=$val['thumb']?>" width="80" /></a></td>
<td><?=$val['title']?></td>
<td><a href="<?=url("space/index/uid/$val[uid]")?>" target="_blank"><?=$val['username']?></a></td>
<td><a href="<?=url("party/detail/id/$val[partyid]")?>" target="_blank"><?=$val['subject']?></a></td>
</tr>
<?endwhile;?>
<tr class="altbg1">
<td colspan="2" class="altbg1">
<button type="button" onclick="checkbox_checked('picids[]');" class="btn2">全选</button>
<td colspan="3" style="text-align:right;"><?=$multipage?></td>
</tr>
<?else:?>
<td colspan="9">暂无信息。</td>
<?endif;?>
</table>
</div>
<center>
<?if($total):?>
<input type="hidden" name="dosubmit" value="yes" />
<input type="hidden" name="op" value="checkup" />
<button type="button" class="btn" onclick="easy_submit('myform','checkup','picids[]')">审核所选</button>
<button type="button" class="btn" onclick="easy_submit('myform','delete','picids[]')">删除所选</button>
<?endif;?>
</center>
</form>
</div><file_sep>/core/modules/tuan/admin/templates/order_detail.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="post" action="<?=cpurl($module,$act,'good_status')?>" name="myform">
<div class="space">
<div class="subtitle">订单处理</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y">
<tr>
<td width="120" class="altbg1">团购项目:</td>
<td width="*"><a href="<?=url("tuan/detail/id/$tuan[tid]")?>" target="_blank"><?=$tuan[subject]?></a></td>
</tr>
<tr>
<td class="altbg1">购买数量:</td>
<td><?=$order[num]?></td>
</tr>
<tr>
<td class="altbg1">总价:</td>
<td><?=$order[price]?></td>
</tr>
<tr>
<td class="altbg1">收货人:</td>
<td><?=$order[contact][linkman]?></td>
</tr>
<tr>
<td class="altbg1">电话号码:</td>
<td><?=$order[mobile]?></td>
</tr>
<tr>
<td class="altbg1">收货地址:</td>
<td><?=$order[contact][address]?></td>
</tr>
<tr>
<td class="altbg1">邮政编码:</td>
<td><?=$order[contact][postcode]?></td>
</tr>
<tr>
<td class="altbg1">买家备注:</td>
<td><?=nl2br($order[contact][des])?></td>
</tr>
<tr>
<td class="altbg1">发货状态:</td>
<td>
<select name="good_status">
<?=form_tuan_good_status($order['good_status'])?>
</select>
</td>
</tr>
<tr>
<td class="altbg1">物流单位:</td>
<td>
<select name="express[name]">
<?=form_tuan_express($order['express']['name'])?>
</select>
</td>
</tr>
<tr>
<td class="altbg1">快递单号:</td>
<td>
<input type="text" name="express[number]" value="<?=$order['express']['number']?>" class="txtbox3" />
</td>
</tr>
</table>
</div>
<center>
<input type="hidden" name="forward" value="<?=get_forward()?>" />
<input type="hidden" name="oid" value="<?=$oid?>" />
<?=form_submit('dosubmit',lang('admincp_submit'),'yes','btn')?>
<?=form_button_return(lang('admincp_return'),'btn')?>
</center>
</form>
</div><file_sep>/core/model/zidian_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_zidian extends ms_model {
var $table = 'dbpre_zidian';
var $key = 'id';
function __construct() {
parent::__construct();
}
function msm_zidian() {
$this->__construct();
}
function init_field() {
$this->add_field('varname,vartype');
}
function save($post) {
$id = parent::save($post, null);
return $id;
}
function read($aid,$select='*') {
$result = parent::read($aid);
return $result;
}
function delete($catids,$delete_coupon = TRUE) {
$ids = parent::get_keyids($catids);
if(!$delete_coupon) return;
$cop =& $this->loader->model(':coupon');
$cop->delete_catids($ids);
unset($cop);
parent::delete($ids);
}
function update($post) {
if(!$post || !is_array($post)) redirect('global_op_unselect');
foreach($post as $catid => $val) {
$this->db->from($this->table);
$this->db->set($val);
$this->db->where('catid',$catid);
$this->db->update();
}
$this->write_cache();
}
function getlist($vartype,$keyword) {
$result = array();
$this->db->from($this->table);
$this->db->where('vartype', $vartype);
$this->db->where_like('varname', "%{$keyword}%");
$this->db->limit(0, 5);
if(!$row = $this->db->get()) {
return $result;
}
//直接将元素封装到数组里
while($value = $row->fetch_array()) {
$result[] = $value;
}
return $result;
}
function getlist1($vartype,$keyword) {
$result = array();
$this->db->from($this->table);
$this->db->where('vartype', $vartype);
$this->db->where_like('varname', "%{$keyword}%");
$this->db->limit(0, 5);
if(!$row = $this->db->get()) {
return $result;
}
//直接将元素封装到数组里
while($value = $row->fetch_array()) {
$result[] = $value;
}
return $result;
}
function write_cache_home() {
$js_data = "var homes = {};";
$js_data .="homes.results = [";
$this->db->from($this->table);
$this->db->where('vartype', 'home');
if($r = $this->db->get()) {
while($v=$r->fetch_array()) {
$js_data .='{id:'.$v['id'].',name:"'.$v['varname'].'",type:"'.$v['vartype'].'"},';
}
$js_data = substr($js_data, 0, -1);
$r->free_result();
}
$js_data .="];";
$js_data .="homes.total = homes.results.length;";
echo "song";
write_cache('homes', $js_data, $this->model_flag, 'js');
echo "ddddd";
}
function write_cache_work() {
$js_data = "var works = {};";
$js_data .="works.results = [";
$this->db->from($this->table);
$this->db->where('vartype', 'work');
if($r = $this->db->get()) {
while($v=$r->fetch_array()) {
$js_data .='{id:'.$v['id'].',name:"'.$v['varname'].'",type:"'.$v['vartype'].'"},';
}
$js_data = substr($js_data, 0, -1);
$r->free_result();
}
$js_data .="];";
$js_data .="works.total = works.results.length;";
write_cache('works', $js_data, $this->model_flag, 'js');
}
function check_post(& $post, $edit = false) {
//if(!$post['name']) redirect('couponcp_match_name_empty');
}
}
?>
<file_sep>/core/modules/modoer/item/admin/templates/subject_list_easy.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/autocomplete/jquery.autocomplete.min.js"></script>
<link rel="Stylesheet" href="./static/javascript/autocomplete/jquery.autocomplete.css" />
<style type="text/css">
.img img { max-width:80px; max-height:60px; border:1px solid #ccc; padding:1px;
_width:expression(this.width > 80 ? 80 : true); _height:expression(this.height > 60 ? 60 : true); }
</style>
<div id="body">
<form method="get" action="<?=SELF?>">
<input type="hidden" name="module" value="item" />
<input type="hidden" name="act" value="subject_list_easy" />
<input type="hidden" name="op" value="<?=$op?>" />
<div class="space">
<div class="subtitle">查询商家</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1">商家关键字</td>
<td>
<input id="keyword" type="text" name="keyword" value="" class="txtbox" />
<script type="text/javascript">
//var url='item/ajax/do/subject/op/search1';
var url="index.php?m=item&act=ajax&do=subject&op=search1";
//var url="index.php?m=item&act=ajax&do=test";
$().ready(function() {
$("#keyword").autocomplete(url, {
max: 12,
minChars: 1,
width: 400,
scrollHeight: 300,
matchContains: true,
autoFill: false,
formatItem: function(row, i, max, value) {
return value.split('-')[1];
},
formatResult: function(row, value) {
return value.split('-')[1];
}
});
$("#keyword").result(function(event, data, formatted) {
$("#sid").val(data[0].split('-')[0] );
});
});
</script>
</td>
<td><input type="submit" value="查询"/></td>
</tr>
</table>
</div>
</form>
<form method="post" name="myform" action="<?=cpurl($module,$act,'',array('pid'=>$pid))?>">
<div class="space">
<div class="subtitle">商家管理</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y" >
<tr class="altbg1">
<td width="25">选择</td>
<td width="100">商家名称</td>
<td width="100">分店名称</td>
</tr>
<?if($total):?>
<?while($val=$list->fetch_array()):?>
<tr>
<td><input type="checkbox" name="sids[]" value="<?=$val['sid']?>" /></td>
<td><?=$val['name']?></td>
<td><?=$val['subname']?></td>
</tr>
<?endwhile;?>
<tr>
<td colspan="12" class="altbg1">
<button type="button" onclick="checkbox_checked('sids[]');" class="btn2">全选</button>
</td>
</tr>
<?else:?>
<tr>
<td colspan="15">暂无信息!</td>
</tr>
<?endif;?>
</table>
</div>
<?if($total):?>
<div class="multipage"><?=$multipage?></div>
<center>
<input type="hidden" name="dosubmit" value="yes" />
<button type="button" class="btn" onclick="easy_submit('myform','select',null)">确定</button>
<button type="button" class="btn" onclick="">返回</button>
</center>
<?endif;?>
</form>
</div><file_sep>/core/modules/tuan/admin/templates/config.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<?=form_begin(cpurl($module,$act))?>
<div class="space">
<div class="subtitle"><?=$MOD['name']?> 模块配置</div>
<ul class="cptab">
<li class="selected" id="btn_config1"><a href="#" onclick="tabSelect(1,'config');" onfocus="this.blur()">功能设置</a></li>
<li id="btn_config2"><a href="#" onclick="tabSelect(2,'config');" onfocus="this.blur()">手机短信设置</a></li>
<li id="btn_config3"><a href="#" onclick="tabSelect(3,'config');" onfocus="this.blur()">搜索引擎优化</a></li>
</ul>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" id="config1">
<tr>
<td class="altbg1" width="45%"><strong>团购首页显示模式:</strong>设置团购首页的显示类型,默认为:今日团购</td>
<td width="*"><?=form_select('modcfg[index_type]', array('detail'=>'今日团购','list'=>'进行中的团购'), $modcfg['index_type'])?></td>
</tr>
<tr>
<td class="altbg1" width="45%"><strong>使用抵金积分字段:</strong>会员可在下单时,通过积分来折换现金,请选择字段,并设置抵换率(大于0的整数)</td>
<td width="*">
<select name="modcfg[ex_pointtype]">
<option value="">不使用本功能</option>
<?=form_member_pointgroup($modcfg['ex_pointtype'])?>
</select>
<input type="text" name="modcfg[ex_rate]" class="txtbox5" value="<?=$modcfg['ex_rate']>0?$modcfg['ex_rate']:10?>">
折换 <span class="font_1">1</span>元
</td>
</tr>
<tr>
<td class="altbg1"><strong>退款时同时退还抵金积分:</strong>在退款的时候,如果用户存在积分抵换现金支付,则同时返还积分,反之则只退还现金</td>
<td><?=form_bool('modcfg[refund_point]', $modcfg['refund_point'])?></td>
</tr>
<tr>
<td class="altbg1" width="45%"><strong>本单答疑是否显示全部评论和回复:</strong>本次团购中的本单答疑,是否显示团购整站的回复数据?</td>
<td width="*"><?=form_bool('modcfg[discuss_all]', $modcfg['discuss_all'])?></td>
</tr>
<tr>
<td class="altbg1"><strong>团购列表页单页显示:</strong>列表页每页显示团购数量</td>
<td><?=form_input('modcfg[list_num]', ($modcfg['list_num']>0?$modcfg['list_num']:10), 'txtbox4')?></td>
</tr>
<tr>
<td class="altbg1"><strong>邮件群发间隔数量:</strong>默认为10份,不宜过多。</td>
<td><input type="text" name="modcfg[mail_num]" value="<?=$modcfg['mail_num']>0?$modcfg['mail_num']:10?>" class="txtbox4" /></td>
</tr>
<tr>
<td class="altbg1"><strong>发货物流:</strong>例如EMS,顺丰快递;多个请用逗号“,”分隔。</td>
<td><?=form_textarea('modcfg[express]',_T($modcfg['express']))?></td>
</tr>
<tr>
<td class="altbg1"><strong>订单线下支付说明:</strong>用户下单时,可以看到线下支付的具体方式,告之买家记录订单号,汇款方式和确认支付电话等信息;本文本框支持HTML代码显示。</td>
<td><?=form_textarea('modcfg[localpay_des]',_T($modcfg['localpay_des']))?></td>
</tr>
<?if($apis):?>
<tr>
<td class="altbg1"><strong>团购导航API:</strong>列举可用的团购导航API</td>
<td>
<?foreach($apis as $k):?>
<div><?=$k?>:<a href="<?=url("tuan/api/n/$k",'',1,true)?>" target="_blank"><?=url("tuan/api/n/$k",'',1,true)?></a></div>
<?endforeach;?>
</td>
</tr>
<?endif;?>
</table>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" id="config2" style="display:none;">
<tr>
<td class="altbg1" width="45%"><strong>启用手机短信发送团购券:</strong>开启本功能后,团购成功后系统将自动将团购券发送给用户。</td>
<td width="*"><?=form_bool('modcfg[send_sms]', $modcfg['send_sms'])?></td>
</tr>
<tr>
<td class="altbg1"><strong>手机号必填:</strong>会员下单时,要求必须填写手机号。</td>
<td><?=form_bool('modcfg[need_mobile]', $modcfg['need_mobile'])?></td>
</tr>
<tr>
<td class="altbg1"><strong>手机号码自定义验证:</strong>不同国家和地区手机号码形式不同,因此需要自定义验证格式,由正则表达式进行验证,中国大陆地区,默认是:<span class="font_1">/^[0-9]{11}$/</span></td>
<td><input type="text" name="modcfg[mobile_preg]" value="<?=$modcfg['mobile_preg']?$modcfg['mobile_preg']:"/^[0-9]{11}$/"?>" class="txtbox3" /></td>
</tr>
<tr>
<td class="altbg1"><strong>会员自助发送团购券短信间隔:</strong>限制会员在我的助手自助发送团购券信息到手机的重复发送间隔,建议大于60秒,避免短信余额被浪费。</td>
<td><?=form_input('modcfg[sms_interval]',$modcfg['sms_interval'],'txtbox5')?> 秒</td>
</tr>
<tr>
<td class="altbg1"><strong>短信接口商:</strong>选择短信发送的接口商。</td>
<td>短信接口设置请前往“短信发送”模块进行配置。</td>
</tr>
</table>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" id="config3" style="display:none;">
<tr>
<td class="altbg1" width="45%"><strong>Meta Keywords:</strong>Keywords 项出现在页面头部的 Meta 标签中,用于记录本页面的关键字,多个关键字间请用半角逗号 "," 隔开</td>
<td width="*"><input type="text" name="modcfg[meta_keywords]" value="<?=$modcfg['meta_keywords']?>" class="txtbox" /></td>
</tr>
<tr>
<td class="altbg1"><strong>Meta Description:</strong>Description 出现在页面头部的 Meta 标签中,用于记录本页面的概要与描述。</td>
<td><input type="text" name="modcfg[meta_description]" value="<?=$modcfg['meta_description']?>" class="txtbox" /></td>
</tr>
</table>
</div>
<center><?=form_submit('dosubmit',lang('admincp_submit'),'yes','btn')?></center>
<?=form_end()?>
</div><file_sep>/core/modules/item/model/subjectpost_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
$_G ['loader']->model ( 'item:itembase', FALSE );
class msm_item_subjectpost extends msm_item_itembase {
var $table = 'dbpre_subjectpost';
var $key = 'id';
function __construct() {
parent::__construct ();
$this->init_field ();
}
function msm_item_subjectpost() {
$this->__construct ();
}
function init_field() {
$this->add_field ( 'id,sname,username,picture1,picture2,picture3,picture4,dateline' );
$this->add_field_fun ( 'id', 'intval' );
$this->add_field_fun ( 'username', '_T' );
}
function find($select, $where, $start, $offset, $total = TRUE) {
$this->db->from ( $this->table );
$this->db->where ( $where );
$result = array (0,'');
if ($total) {
if (! $result [0] = $this->db->count ()) {
return $result;
}
$this->db->sql_roll_back ( 'from,where' );
}
$this->db->select ( $select ? $select : '*' );
$this->db->order_by ( 'dateline', 'DESC' );
$this->db->limit ( $start, $offset );
$result [1] = $this->db->get ();
return $result;
}
function save() {
$post = $this->get_post ( $_POST );
if ($this->global ['user']->isLogin) {
$post ['username'] = $this->global ['user']->username;
}
$post ['dateline'] = $this->global ['timestamp'];
$id = parent::save ( $post, null, FALSE );
return $id;
}
function check_post(& $post, $isedit = FALSE) {
if (! $post ['upcontent']) {
// redirect('item_log_empty_content');
}
}
function delete($ids) {
if (is_numeric ( $ids ) && $ids > 0)
$ids = array ($ids);
if (empty ( $ids ) || ! is_array ( $ids ))
redirect ( 'global_op_unselect' );
$this->db->from ( $this->table );
$this->db->where_in ( 'id', $ids );
$this->db->delete ();
}
}
?><file_sep>/static/javascript/FlexBox/js/fbdata.js
var fbdata = {};
fbdata.results = [
{id:'AF',name:'找商家'},
{id:'AL',name:'找美食'},
{id:'DZ',name:'找优惠'},
{id:'DZ',name:'找外卖'},
{id:'ZW',name:'找团购'}
];
fbdata.total = fbdata.results.length;<file_sep>/core/modules/party/helper/query.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
class query_party {
//获取分类
function category($params) {
$loader =& _G('loader');
$category = $loader->variable('category','party');
$result = '';
!$params['pid'] && $params['pid'] = 0;
if($params['pid'] && $params['parent']) {
$params['pid'] = (int) $category[$params['pid']]['pid'];
}
foreach($category as $key => $val) {
if($val['pid'] == $params['pid']) {
$result[$key] = $val;
}
}
return $result;
}
//获取列表
function getlist($params) {
extract(query_default($params));
$loader =& _G('loader');
if(isset($aid) && is_numeric($aid)) {
$AREA =& $_G['loader']->model('area');
$aids = $AREA->get_sub_aids($aid);
unset($AREA);
}
$P =& $loader->model(':party');
$P->db->from($P->table);
$P->db->select($select?$select:'partyid,subject,sid,aid,catid,flag,pageview,uid,username,dateline,num,begintime,endtime,thumb');
if($sid > 0) $P->db->where('sid',$sid);
if(is_numeric($uid) && $uid >= 0) $P->db->where('uid',$uid);
if($city_id) $P->db->where('city_id',explode(',',$city_id));
if(isset($aids)) $P->db->where('aid', $aids);
if($catid > 0) $P->db->where('catid', $catid);
if($flag > 0) $P->db->where('flag', $flag);
if($finer > 0) $P->db->where('finer', 1);
if($month=='NOW') $month = date('n', $P->global['timestamp']);
/*
if($month >= 1 && $month <= 12) {
$P->db->where_between_and('joinendtime' , );
}
*/
$P->db->where('status', 1);
$orderby && $orderby = 'flag,dateline DESC';
$P->db->order_by($orderby);
$P->db->limit($start, $rows);
if(!$r=$P->db->get()) { return null; }
$result = array();
while($v = $r->fetch_array()) {
$result[] = $v;
}
$r->free_result();
return $result;
}
//获得加入
function joins($params) {
extract(query_default($params));
$loader =& _G('loader');
$A =& $loader->model('party:apply');
$A->db->select($select?$select:'pa.partyid,pa.uid,pa.username,pa.dateline');
if($party_select) $A->db->select($party_select);
$A->db->join($A->table, 'pa.partyid', 'dbpre_party', 'p.partyid');
if($city_id > 0) $A->db->where('city_id', $city_id);
if($sid > 0) $A->db->where('sid', $sid);
if($partyid > 0) $A->db->where('pa.partyid', $partyid);
$orderby && $orderby = 'flag,dateline DESC';
$A->db->order_by($orderby);
$A->db->limit($start, $rows);
if(!$r=$A->db->get()) { return null; }
$result = array();
while($v = $r->fetch_array()) {
$result[] = $v;
}
$r->free_result();
return $result;
}
}
?><file_sep>/core/modules/tuan/admin/tgsite.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$Site =& $_G['loader']->model('tuan:tgsite');
$op = _input('op');
switch($op) {
case 'new':
$admin->tplname = cptpl('tgsite_save', MOD_FLAG);
break;
case 'edit':
$id = (int) $_GET['id'];
if(!$detail = $Site->read($id)) redirect('tgsite_empty');
$admin->tplname = cptpl('tgsite_save', MOD_FLAG);
break;
case 'save':
if($_POST['do']=='edit') {
if(!$id = (int)$_POST['id']) redirect(lang('global_sql_keyid_invalid','id'));
$forward = get_forward(cpurl($module,$act,'list'),1);
if(empty($forward )||strpos($forward,'cpmenu')) $def_url = cpurl($module,$act,'list');
} else {
$id = null;
$forward = cpurl($module,$act,'list');
}
$post = $Site->get_post($_POST);
$Site->save($post, $id);
redirect('global_op_succeed', $forward);
break;
case 'delete':
$Site->delete($_GET['id']);
redirect('global_op_succeed_delete', cpurl($module,$act));
break;
case 'spider':
set_time_limit(30);
$siteid=$_POST ['ids'];
//开始采集时间
$starttime=microtime();
//采集工作
$id=$Site->crawler($siteid);
$forward = get_forward(cpurl($module,'tempurl','list'),1);
redirect('global_op_succeed', $forward);
break;
default:
$op = 'list';
$offset = 40;
$start = get_start($_GET['page'], $offset);
list($total, $list) = $Site->find('*', $where, 'sort', $start, $offset, TRUE);
if($total) {
$multipage = multi($total, $offset, $_GET['page'], cpurl($module, $act, 'list'));
}
$admin->tplname = cptpl('tgsite_list', MOD_FLAG);
}
?><file_sep>/core/modules/party/admin/templates/picture_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="get" action="<?=SELF?>">
<input type="hidden" name="module" value="<?=$module?>" />
<input type="hidden" name="act" value="<?=$act?>" />
<input type="hidden" name="op" value="<?=$op?>" />
<div class="space">
<div class="subtitle">图片筛选</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1">活动标题</td>
<td colspan="3"><input type="text" name="title" class="txtbox" value="<?=$_GET['title']?>" /></td>
</tr>
<tr>
<td width="100" class="altbg1">上传用户</td>
<td width="350"><input type="text" name="username" class="txtbox3" value="<?=$_GET['username']?>" /></td>
<td width="100" class="altbg1">活动ID(partyid)</td>
<td width="*"><input type="text" name="partyid" class="txtbox3" value="<?=$_GET['partyid']?>" /></td>
</tr>
<tr>
<td class="altbg1">发布时间</td>
<td colspan="3"><input type="text" name="starttime" class="txtbox3" value="<?=$_GET['starttime']?>" /> ~ <input type="text" name="endtime" class="txtbox3" value="<?=$_GET['endtime']?>" /> (YYYY-MM-DD)</td>
</tr>
<tr>
<td class="altbg1">结果排序</td>
<td colspan="3">
<select name="orderby">
<option value="picid"<?=$_GET['orderby']=='picid'?' selected="selected"':''?>>ID排序</option>
<option value="dateline"<?=$_GET['orderby']=='dateline'?' selected="selected"':''?>>发布时间</option>
</select>
<select name="ordersc">
<option value="DESC"<?=$_GET['ordersc']=='DESC'?' selected="selected"':''?>>递减</option>
<option value="ASC"<?=$_GET['ordersc']=='ASC'?' selected="selected"':''?>>递增</option>
</select>
<select name="offset">
<option value="20"<?=$_GET['offset']=='20'?' selected="selected"':''?>>每页显示20个</option>
<option value="50"<?=$_GET['offset']=='50'?' selected="selected"':''?>>每页显示50个</option>
<option value="100"<?=$_GET['offset']=='100'?' selected="selected"':''?>>每页显示100个</option>
</select>
<button type="submit" value="yes" name="dosubmit" class="btn2">筛选</button>
</td>
</tr>
</table>
</div>
</form>
<form method="post" name="myform" action="<?=cpurl($module,$act)?>&">
<div class="space">
<div class="subtitle">图片管理</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" id="config1" trmouse="Y">
<tr class="altbg1">
<td width="25">选</td>
<td width="*">图片</td>
<td width="150">名称</td>
<td width="150">上传用户</td>
<td width="200">活动名称</td>
</tr>
<?if($total):?>
<?while($val = $list->fetch_array()):?>
<tr>
<td><input type="checkbox" name="picids[]" value="<?=$val['picid']?>" /></td>
<td><a href="<?=$val['pic']?>" target="_blank"><img src="<?=$val['thumb']?>" width="80" /></a></td>
<td><?=$val['title']?></td>
<td><a href="<?=url("space/index/uid/$val[uid]")?>" target="_blank"><?=$val['username']?></a></td>
<td><a href="<?=url("party/detail/id/$val[partyid]")?>" target="_blank"><?=$val['subject']?></a></td>
</tr>
<?endwhile;?>
<tr class="altbg1">
<td colspan="2" class="altbg1">
<button type="button" onclick="checkbox_checked('picids[]');" class="btn2">全选</button>
<td colspan="3" style="text-align:right;"><?=$multipage?></td>
</tr>
<?else:?>
<td colspan="5">暂无信息。</td>
<?endif;?>
</table>
</div>
<center>
<?if($total):?>
<input type="hidden" name="dosubmit" value="yes" />
<input type="hidden" name="op" value="update" />
<button type="button" class="btn" onclick="easy_submit('myform','delete','picids[]')">删除所选</button>
<?endif;?>
</center>
</form>
</div><file_sep>/core/modules/weixin/wxProcess.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'weixin');
$options = array(
'token'=>'<PASSWORD>' //填写你设定的key
);
$menu = '谢谢关注【阿果生活网】官方微信:【无锡特惠券】!发送菜单序号或关键词【如:万达 火锅】获取你想要的信息吧!
0.阿果生活网首页;
1.附近优惠;
2.附近商家;
3.热门分类;
4.热门商圈;
';
//*你也可以点击左下角的【加号】,然后点击【位置】,拖动地图到你想要查询的地点,然后发给我,我就会给你查询当地优惠啦!
//*你还可以发送‘搜’+关键词来搜索相关内容,如‘搜火锅’、‘搜新区 自助’
$base_url = 'http://'.MUDDER_DOMAIN;
include MOD_ROOT . 'model/wechat.class.php';
$weObj = new Wechat($options);
$echosrt = $weObj->valid();
$type = $weObj->getRev()->getRevType();
$userId = $weObj->getRev()->getRevFrom();
$userStamp = '&userWxId='.$userId;
$queryString = '';
$newsMenu[0] = array (
'Title' => '无锡特惠券增刊发布',
'Description' =>'无锡特惠券',
'PicUrl' => $base_url.'/uploads/weixin/qzk.png',
'Url' => $base_url.'/article.php?act=mobile&do=detail&id=58'.$userStamp);
$newsMenu[1] = array (
'Title' => '☆无锡特惠券☆
《无锡特惠券》介绍和使用指南',
'Description' =>'无锡特惠券介绍',
'PicUrl' => $base_url.'/templates/mobile/img/quan.jpg',
'Url' => $base_url.'/article.php?act=mobile&do=detail&id=53'.$userStamp);
$newsMenu[2] = array (
'Title' => '☆《无锡特惠券》目录☆
快速查询你附近可以使用本《券》的商家',
'Description' =>'无锡特惠券目录',
'PicUrl' => $base_url.'/templates/mobile/img/about.jpg',
'Url' => $base_url.'/item.php?act=mobile&do=list&px=distance'.$userStamp);
$newsMenu[3] = array (
'Title' => '☆免费领取地点☆
关注微信即可免费领取《无锡特惠券一本》',
'Description' =>'时惠',
'PicUrl' => $base_url.'/templates/mobile/img/miao.jpg',
'Url' => $base_url.'/item.php?act=mobile&do=list&f=10'.$userStamp);
$newsMenu[4] = array (
'Title' => '☆使用指南☆
阿果生活网微信公众平台使用指南',
'Description' =>'使用指南',
'PicUrl' => $base_url.'/templates/mobile/img/zhao.jpg',
'Url' => $base_url.'/article.php?act=mobile&do=detail&id=56'.$userStamp);
// $newsMenu[3] = array (
// 'Title' => '【会员专享】
// ☆加入阿果会员,量身定制优惠',
// 'Description' =>'会员专享,特惠定制',
// 'PicUrl' => $base_url.'/templates/mobile/img/goodfood.jpg',
// 'Url' => $base_url.'/coupon.php?act=mobile&do=list&f=2'.$userStamp);
// $newsMenu[4] = array (
// 'Title' => '☆加入我们☆
// 赶快来成为阿果网区域代理吧',
// 'Description' =>'加入我们,寻找代理',
// 'PicUrl' => $base_url.'/templates/mobile/img/zhao.jpg',
// 'Url' => $base_url.'/item.php?act=mobile&do=list&f=12'.$userStamp);
// $newsMenu[4] = array (
// 'Title' => '☆关于阿果☆
// 无锡本地的‘吃喝玩乐’特惠平台',
// 'Description' =>'关于我们',
// 'PicUrl' => $base_url.'/templates/mobile/img/about.jpg',
// 'Url' => $base_url.'/item.php?act=mobile&do=list&f=10'.$userStamp);
//$weObj->text($userId.'###'.strlen($userId))->reply();
switch($type) {
case Wechat::MSGTYPE_TEXT:
//$weObj->text("hello, I'm wechat")->reply();
$rev_msg = trim($weObj->getRevContent());
switch($rev_msg){
case $queryString:
include MOD_ROOT . 'activity.php';
exit;
break;
case '帮助':
case '菜单':
case 'menu':
case 'm':
case 'M':
case 'h':
case 'help':
$weObj->news($newsMenu)->reply();
break;
default:
// $weObj->text(MOD_ROOT)->reply();
include MOD_ROOT . 'wordsProcess.php';
//$weObj->text($rev_msg.$searchedNews)->reply();
exit;
break;
}
case Wechat::MSGTYPE_EVENT:
$event = $weObj->getRevEvent();
if ($event['event'] == 'subscribe') {
// include MOD_ROOT . 'activity.php';
$weObj->news($newsMenu)->reply();
}
break;
case Wechat::MSGTYPE_LOCATION:
$location = $weObj->getRevGeo();
$lng = $location['x'];
$lat = $location['y'];
// $weObj->text($lng)->reply();
$rev_msg = 'locationsearch';
include MOD_ROOT . 'wordsProcess.php';
// $newsdata[0] = array('Title'=>'附近优惠',
// 'Description'=>'点击查看你身边的优惠!',
// 'PicUrl'=>$base_url.'/templates/mobile/img/weixinintrologo.jpg',
// 'Url'=>$base_url.'/item.php?act=mobile&do=list&px=distance'.$userStamp);
// $weObj->news($newsdata)->reply();
exit;
break;
case Wechat::MSGTYPE_IMAGE:
break;
default:
$weObj->news($newsMenu)->reply();
}
?><file_sep>/core/modules/tuan/admin/templates/discuss_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="post" id="myform" action="<?=cpurl($module,$act)?>" name="myform">
<div class="space">
<div class="subtitle">用户答疑</div>
<ul class="cptab">
<li<?=!$_GET['status']?' class="selected"':''?>><a href="<?=cpurl($module,$act,'list',array('status'=>'0'))?>">未审核</a></li>
<li<?=$_GET['status']=='1'?' class="selected"':''?>><a href="<?=cpurl($module,$act,'list',array('status'=>'1'))?>">已审核</a></li>
</ul>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y">
<tr class="altbg1">
<td width="25">删?</td>
<td width="80">会员</td>
<td width="200">团购项目</td>
<td width="*">答疑</td>
<td width="120">日期</td>
<td width="120">操作</td>
</tr>
<?if($total):?>
<?while($val=$list->fetch_array()) {?>
<tr>
<td><input type="checkbox" name="ids[]" value="<?=$val['id']?>" /></td>
<td><a href="<?=url("space/index/uid/$val[uid]")?>" target="_blank"><?=$val['username']?></a></td>
<td><a href="<?=url("tuan/detail/id/$val[tid]")?>" target="_blank"><?=$val['subject']?></a><br /><span class="font_2">[<?=template_print('modoer','area',array('aid'=>$val['city_id']))?>]</span></td>
<td><?=$val['content']?><br /><p class="font_3"><?=$val['reply']?></td>
<td><?=date('Y-m-d H:i', $val['dateline'])?></td>
<td><a href="<?=cpurl($module,$act,'edit', array('id'=>$val['id']))?>">回复</a></td>
</tr>
<?}?>
<tr class="altbg1">
<td colspan="2"><button type="button" class="btn2" onclick="checkbox_checked('ids[]');">全选</button></td>
<td colspan="4"><?=$multipage?></td>
</tr>
<?else:?>
<tr>
<td colspan="5">暂无信息</td>
</tr>
<?endif;?>
</table>
</div>
<center>
<input type="hidden" name="op" value="update" />
<input type="hidden" name="dosubmit" value="yes" />
<button type="button" class="btn" onclick="easy_submit('myform','delete','ids[]')">删除所选</button>
</center>
</form>
</div><file_sep>/core/modules/tuan/helper/query.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
class query_tuan {
//get标签调用函数
//song.2013 edit
function category($params=null) {
extract($params);
$loader =& _G('loader');
$pid = (int) $pid;
$category = $loader->variable('category','tuan');
$result = ''; $index = 0;
foreach($category as $key => $val) {
if($val['pid'] == $pid) {
if($num>0 && ++$index > $num) break;
//if($usearea && !$val['usearea']) continue;
$result[] = $val;
}
}
/*
$db =& _G('db');
$db->from('dbpre_tuan_category');
$db->order_by('listorder');
$result = array();
if($r = $db->get()) {
while($v=$r->fetch_array()) {
if($v['pid'] == $pid && $v['enabled']) {
$result[$v['catid']] = $v;
}
}
$r->free_result();
}
*/
return $result;
}
function getlist($params) {
extract($params);
$loader =& _G('loader');
if(!$list = $loader->variable('list','link')) return array();
if(!in_array($type,array('char','logo'))) $type = 'char';
return $list[$type];
}
function discuss($params) {
extract($params);
$loader =& _G('loader');
$db =& _G('db');
$db->select($select?$select:'*');
$db->from('dbpre_tuan_discuss');
if($tid > 0) $db->where('tid', $tid);
$db->where('status', 1);
$orderby && $db->order_by($orderby);
$db->limit($start, $rows);
if(!$r=$db->get()) { return null; }
$result = array();
while($v = $r->fetch_array()) {
$result[] = $v;
}
$r->free_result();
return $result;
}
}
?><file_sep>/core/modules/tuan/admin/tempurl.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$Site =& $_G['loader']->model('tuan:tempurl');
$op = _input('op');
switch($op) {
case 'new':
$_G['loader']->helper('form','item');
$admin->tplname = cptpl('tempurl_save', MOD_FLAG);
break;
case 'edit':
$id = (int) $_GET['id'];
if(!$detail = $Site->read($id)) redirect('tempurl_empty');
$detail['starttime'] = date('Y-m-d', $detail['starttime']);
$detail['lasttime'] = date('Y-m-d', $detail['lasttime']);
if($detail['keyword']=='') $detail['keyword']=$detail['bizname'];
$_G['loader']->helper('form','item');
$admin->tplname = cptpl('tempurl_save', MOD_FLAG);
break;
case 'save':
if($_POST['do']=='edit') {
if(!$id = (int)$_POST['id']) redirect(lang('global_sql_keyid_invalid','id'));
$forward = get_forward(cpurl($module,$act,'list'),1);
if(empty($forward )||strpos($forward,'cpmenu')) $def_url = cpurl($module,$act,'list');
} else {
$id = null;
$forward = cpurl($module,$act,'list');
}
$post = $Site->get_post($_POST);
$Site->save($post, $id);
redirect('global_op_succeed', $forward);
break;
case 'delete':
$Site->delete($_GET['id']);
redirect('global_op_succeed_delete', cpurl($module,$act));
break;
default:
$op = 'list';
$offset = 20;
$start = get_start($_GET['page'], $offset);
list($total, $list) = $Site->find('*', $where, 'sortorder', $start, $offset, TRUE);
if($total) {
$multipage = multi($total, $offset, $_GET['page'], cpurl($module, $act, 'list'));
}
$admin->tplname = cptpl('tempurl_list', MOD_FLAG);
}
?><file_sep>/core/modules/item/mobile/pictures.php
<?php
$albumid = _input('albumid',null,MF_INT_KEY);
$A =& $_G['loader']->model('item:album');
if(!$album = $A->read($albumid)) redirect('item_album_empty');
$P =& $_G['loader']->model('item:picture');
$where = array();
$where['albumid'] = $albumid;
list($total, $list) = $P->find('*', $where, array('addtime'=>'DESC'), 0, 0, 1);
if(!$total) redirect('item_picture_empty');
include mobile_template('item_pictures');
?><file_sep>/core/modules/tuan/admin/templates/tempurl_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/jquery.js"></script>
<script type="text/javascript" src="./static/javascript/autocomplete/jquery.autocomplete.min.js"></script>
<script type="text/javascript" src="./static/javascript/My97DatePicker/WdatePicker.js"></script>
<link rel="Stylesheet" href="./static/javascript/autocomplete/jquery.autocomplete.css"/>
<script type="text/javascript">
var g;
function reload() {
var obj = document.getElementById('reload');
var btn = document.getElementById('switch');
if (obj.innerHTML.match(/^<.+href=.+>/)) {
g = obj.innerHTML;
obj.innerHTML = '<input type="file" name="picture" size="20">';
btn.innerHTML = '取消上传';
} else {
obj.innerHTML = g;
btn.innerHTML = '重新上传';
}
}
function check_submit() {
//if($('[name=sid]').val()=="") {
//alert('选择优惠券所属商铺。');
//return false;
//}
return true;
}
</script>
<div id="body">
<form method="post" action="<?=cpurl($module,$act,'save')?>" name="myform"
enctype="multipart/form-data" onsubmit="return check_submit();">
<input id="sid" type="hidden" name="sid" value="" />
<div class="space">
<div class="subtitle">
编辑团购信息
</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1" align="right" width="15%">
团购项目:
</td>
<td width="75%" class="altbg1">
<input type="text" id="subject" value="<?=$detail['subject'];?>" name="subject"
class="txtbox">
</td>
</tr>
<tr>
<td class="altbg1" align="right">
短标题:
</td>
<td>
<input type="text" size="30" value="<?=$detail['shortsubject'];?>" id="shortsubject"
name="shortsubject" class="txtbox">
</td>
</tr>
<tr>
<td class="altbg1" align="right" width="15%">
商家名称:
</td>
<td width="75%" class="altbg1">
<input type="text" id="shopname" value="<?=$detail['shopname'];?>" name="shopname"
class="txtbox">
</td>
</tr>
<tr>
<td class="altbg1" align="right">
开始日期:
</td>
<td>
<input type="text" value="<?= $detail['starttime'];?>"
id="starttime" name="starttime" class="txtbox" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})">
</td>
</tr>
<tr>
<td class="altbg1" align="right">
结束日期:
</td>
<td>
<input type="text" value="<?= $detail['lasttime'];?>"
id="lasttime" name="lasttime" class="txtbox" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})">
</td>
</tr>
<tr>
<td class="altbg1" align="right">
所属网站:
</td>
<td>
<select name="siteid" id="siteid">
<option value="0">
请选择网站
</option>
<?=form_tuan_tgsite($detail[ 'siteid'])?>
</select>
</tr>
<tr>
<td class="altbg1" align="right">
所属区划:
</td>
<td>
<select name="areaid" id="areaid">
<option value="0">
请选择城市
</option>
<?=form_tuan_sonarea(8,$detail[ 'areaid'])?>
</select>
</td>
</tr>
<tr>
<td class="altbg1" align="right">
所属分类:
</td>
<td>
<select name="big_catelist">
<option value="0">
请选择分类
</option>
<?=form_item_category_main($detail[ 'big_catelist'])?>
</select>
</td>
</tr>
<tr>
<td class="altbg1" align="right">
缩略图:
</td>
<td colspan="3">
<?if(!$detail['thumb']):?>
<input type="file" name="picture" size="20" validator="{'empty':'N','errmsg':'未设置团购封面。'}" />
<?else:?>
<span id="reload">
<a href="<?=$detail['thumb']?>" target="_blank" src="<?=$detail['thumb']?>" onmouseover="tip_start(this);">
<?=$detail['thumb']?>
</a>
</span>
[<a href="javascript:reload();" id="switch">重新上传</a>]
<?endif;?>
</td>
</tr>
<tr>
<td class="altbg1" align="right">
访问地址:
</td>
<td>
<input type="text" id="url" value="<?=$detail['url'];?>" name="url" class="txtbox">
</td>
</tr>
<tr>
<td class="altbg1" align="right">
原价:
</td>
<td>
<input type="text" size="30" id="oldprice" value="<?=$detail['oldprice'];?>"
name="oldprice" class="txtbox">
</td>
</tr>
<tr>
<td class="altbg1" align="right">
现价:
</td>
<td>
<input type="text" size="30" id="nowprice" value="<?=$detail['nowprice'];?>"
name="nowprice" class="txtbox">
</td>
</tr>
<tr>
<td class="altbg1" align="right">
当前购买人数:
</td>
<td>
<input type="text" size="30" id="nowpeople" value="<?=$detail['nowpeople'];?>"
name="nowpeople" class="txtbox">
</td>
</tr>
<tr>
<td class="altbg1" align="right">
人气:
</td>
<td>
<input type="text" size="30" id="hits" value="<?=$detail['hits'];?>" name="hits"
class="txtbox">
</td>
</tr>
<tr>
<td class="altbg1" align="right">
标签:
</td>
<td>
<input type="text" size="30" id="keyword" value="<?=$detail['keyword'];?>"
name="keyword" class="txtbox">
</td>
</tr>
<tr>
<td class="altbg1" align="right">
排序:
</td>
<td>
<input type="text" size="30" id="sortorder" value="<?=$detail['sortorder'];?>"
name="sortorder" class="txtbox">
</td>
</tr>
<tr>
<td class="altbg1" align="right">
通过审核?:
</td>
<td>
<input type="radio" checked="" value="1" name="ispassed">
通过
<input type="radio" value="0" name="ispassed">
不通过
</td>
</tr>
<tr>
<td class="altbg1" align="right">
是否推荐?:
</td>
<td>
<input type="radio" checked="" value="1" name="recommend">
通过
<input type="radio" value="0" name="recommend">
不通过
</td>
</tr>
</table>
<center>
<?if($op=='edit' ):?>
<input type="hidden" name="id" value="<?=$id?>" />
<?endif;?>
<input type="hidden" name="do" value="<?=$op?>" />
<button type="submit" name="dosubmit" value="yes" class="btn" />
提交
</button>
<button type="button" class="btn" value="yes" onclick="history.go(-1);">
返回
</button>
</center>
</div>
</form>
</div>
<script type="text/javascript">
var url="index.php?m=item&act=ajax&do=subject&op=search1";
$().ready(function() {
$("#shopname").autocomplete(url, {
max: 12,
minChars: 1,
width: 400,
scrollHeight: 300,
matchContains: true,
autoFill: false,
formatItem: function(row, i, max, value) {
return value.split('-')[1];
},
formatResult: function(row, value) {
return value.split('-')[1];
}
});
});
</script>
<file_sep>/core/modules/member/mobile/zidian.php
<?php
$zd = $_G ['loader']->model ( 'zidian' );
echo "缓存成功";
?>
<file_sep>/static/javascript/ask.js
/**
* @author 轩<<EMAIL>>
* @copyright 风格店铺(www.cmsky.org)
*/
function ask_select_category(select,id,all) {
var catid = $(select).val();
var cat = $('#catid').empty();
if(!all) all = false;
if(all) {
cat.append("<option value='0'>==全部==</option>");
}
if(!catid) return;
$.each( ask_category_sub[catid], function(i, n){
if(typeof(n)!='undefined') cat.append("<option value='"+i+"'>"+n+"</option>");
});
}
function ask_goodrate(id) {
var ask_max_size=13588;
if (!is_numeric(id)) {
alert('无效的ID');
return;
}
$.post(Url('ask/detail/id/'+id), {op:"goodrate",in_ajax:1}, function(result) {
if (result.match(/\{\s+caption:".*",message:".*".*\s*\}/)) {
myAlert(result);
} else if(result == 'OK') {
$('#goodrate_num').text(parseInt($('#goodrate_num').text())+1);
$('#rate_click').html('谢谢支持');
$('#rate_click2').html('谢谢支持');
} else {
$('#rate_click').html('谢谢支持');
$('#rate_click2').html('谢谢支持');
}
});
}
function ask_badrate(id) {
if (!is_numeric(id)) {
alert('无效的ID');
return;
}
$.post(Url('ask/detail/id/'+id), {op:"badrate",in_ajax:1}, function(result) {
if (result.match(/\{\s+caption:".*",message:".*".*\s*\}/)) {
myAlert(result);
} else if(result == 'OK') {
$('#badrate_num').text(parseInt($('#badrate_num').text())+1);
$('#rate_click').html('谢谢支持');
$('#rate_click2').html('谢谢支持');
} else {
$('#rate_click').html('谢谢支持');
$('#rate_click2').html('谢谢支持');
}
});
}
//补充问题
function ask_extra(askid) {
if (!is_numeric(askid)) {
alert('无效的ID');
return;
}
$.post(Url('ask/member/ac/ask/op/extra/in_ajax/1'),
{ askid:askid },
function(result) {
if(result == null) {
alert('信息读取失败,可能网络忙碌,请稍后尝试。');
} else if (result.match(/\{\s+caption:".*",message:".*".*\s*\}/)) {
myAlert(result);
} else {
dlgOpen('问题补充', result, 400, 250);
}
});
}
function ask_up_reward(askid) {
if (!is_numeric(askid)) {
alert('无效的ID');
return;
}
$.post(Url('ask/member/ac/ask/op/reward/in_ajax/1'),
{ askid:askid },
function(result) {
if(result == null) {
alert('信息读取失败,可能网络忙碌,请稍后尝试。');
} else if (result.match(/\{\s+caption:".*",message:".*".*\s*\}/)) {
myAlert(result);
} else {
dlgOpen('提高悬赏', result, 400, 110);
}
});
}
function ask_close(askid, no_cfm) {
if(!is_numeric(askid)) { alert('无效的ID'); return; }
if(!no_cfm && !confirm('您确定要关闭这个问题吗?')) return;
$.post(Url('ask/member/ac/ask/op/close_ask'),
{ askid:askid,in_ajax:1,empty:getRandom()},
function(result) {
if(result == null) {
alert('信息读取失败,可能网络忙碌,请稍后尝试。');
} else if (result.match(/\{\s+caption:".*",message:".*".*\s*\}/)) {
myAlert(result);
} else if(result=='OK') {
msgOpen('问题已成功关闭!', 200, 60);
}
});
}
function ask_psup_answer(answerid) {
if (!is_numeric(answerid)) {
alert('无效的ID');
return;
}
$.post(Url('ask/member/ac/answer/op/psup/in_ajax/1'),
{ answerid:answerid },
function(result) {
if(result == null) {
alert('信息读取失败,可能网络忙碌,请稍后尝试。');
} else if (result.match(/\{\s+caption:".*",message:".*".*\s*\}/)) {
myAlert(result);
} else {
dlgOpen('采纳为答案', result, 400, 250);
}
});
}
function ask_edit_answer(answerid) {
if (!is_numeric(answerid)) {
alert('无效的ID');
return;
}
$.post(Url('ask/member/ac/answer/op/edit/in_ajax/1'),
{ answerid:answerid },
function(result) {
if(result == null) {
alert('信息读取失败,可能网络忙碌,请稍后尝试。');
} else if (result.match(/\{\s+caption:".*",message:".*".*\s*\}/)) {
myAlert(result);
} else {
dlgOpen('修改回答', result, 400, 250);
}
});
}<file_sep>/core/modules/article/mobile/detail.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'article');
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'article');
if(!$articleid = (int)$_GET['id']) redirect(lang('global_sql_keyid_invalid', 'id'));
$A =& $_G['loader']->model(MOD_FLAG.':article');
if((!$detail = $A->read($articleid)) || $detail['status']!=1) redirect('article_empty');
//判断是否当前内容所属当前城市,不是则跳转
if(check_jump_city($detail['city_id'])) location(url("city:$detail[city_id]/article/mobile/do/detail/id/$articleid"));
//更新浏览量
$A->pageview($articleid);
//手动分页
/*
$CP =& $_G['loader']->lib('cutpage');
$CP->pagestr = $detail['content'];
//$CP->page_word = $MOD['page_word']>500?$MOD['page_word']:500;
$CP->manual_cut();
$total = $CP->sum_page;
$detail['content'] = $CP->pagearr[$_GET['page']-1];
$total>1 && $multipage = multi($total, 1, $_GET['page'], url("city:$detail[city_id]/article/mobile/do/detail/id/$articleid/page/_PAGE_"));
*/
$numScale = 50;
$tpl = 'article_detail';
if (($_GET['id']=='57') && $_GET['userWxId']) {
$wxid = $_GET['userWxId'];
$M = $_G['loader']->model('member:member');
$user = $M->read1($wxid);
if ($user) {
$regIndex = $user['point6'];
$winIndex = floor($regIndex/$numScale);
$cardLeft = 35 - $winIndex;
$confirmCode = $user['mobile'];
$feedbacktitle = '成功参加活动';
$feedbackmsg = '您已成功参加活动,您的排序为:'.$regIndex;
}
$tpl = 'article_detail_activity';
}
if (strposex($_SERVER['HTTP_REFERER'],'sendsms')){
$header_forward = url("coupon/mobile/do/list/catid/$detail[catid]");
} elseif($_SERVER['HTTP_REFERER']) {
$header_forward = $_SERVER['HTTP_REFERER'];
}
include mobile_template($tpl);<file_sep>/core/modules/tuan/mobile/detail.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'tuan');
if(isset($_GET['id'])) $tid = (int) $_GET['id'];
if(!$tid) redirect(lang('global_sql_keyid_invalid','id'));
$T = & $_G ['loader']->model ( 'tuan:tuandh' );
$detail = $T->read($tid);
/*
$I =& $_G['loader']->model('item:subject');
if(!$subject = $I->read($detail['sid'])) redirect('item_empty');
*/
include mobile_template('tuan_detail');
?>
<file_sep>/templates/main/thms_old/template.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
return array (
'footer.htm' => '网站底部模板',
'index.htm' => '网站首页模板',
);
?><file_sep>/templates/mobile1/js/fixedpos.js
//alert(11111);
var android2_3up = navigator.userAgent.match(/Android [2-9].[3-9][.\d]*/);
var ios5up = navigator.userAgent.match(/OS [5-9]_\d[_\d]*/);
var isMobile = navigator.userAgent.match(/AppleWebKit.*Mobile.*/);
//alert(22222);
if (isMobile && !ios5up || !android2_3up) {
//alert(3333);
var p = document.getElementById('fixed');
p.style.display = 'absolute';
function handler(event) {
//var top = window.innerHeight + document.body.scrollTop - 50;
p.style.bottom = '0' + 'px';
p.style.opacity = 1;
}
function touchstart(event) {
p.style.opacity = 0;
}
function touchend(event) {
p.style.opacity = 1;
}
document.addEventListener('scroll',handler,false);
document.addEventListener('touchstart',touchstart,false);
document.addEventListener('touchend',touchend,false);
}<file_sep>/templates/item/sjstyle/contact.php
<?exit?>
<!--{eval
$_HEAD['title'] = $detail[name] . $detail[subname] . 的联系方式和地图位置;
}-->
{template vip2_header}
<script type="text/javascript">
loadscript('swfobject');
$(document).ready(function() {
if(!$.browser.msie && !$.browser.safari) {
var d = $("#thumb");
var dh = parseInt(d.css("height").replace("px",''));
var ih = parseInt(d.find("img").css("height").replace("px",''));
if(dh - ih < 3) return;
var top = Math.ceil((dh - ih) / 2);
d.find("img").css("margin-top",top+"px");
}
<!--{if $MOD['show_thumb'] && $detail['pictures']}-->
get_pictures($sid);
<!--{/if}-->
get_membereffect($sid, $modelid);
});
</script>
<link href="{URLROOT}/img/shop/$detail[c_sjstyle]/style.css" rel="stylesheet" type="text/css" />
<!--头开始-->
<div class="header">
<div class="headerinfo">$detail[name] $detail[subname]</div>
<div class="headermeun">
<ul>
<li><div><a href="{url item/detail/id/$detail[sid]}">首页</a> </div></li>
<li><div><a href="{url item/vipabout/id/$detail[sid]}">店铺介绍</a> </div></li>
<li><div><a href="{url article/list/sid/$sid}">店铺动态</a> </div></li>
<li><div><a href="{url item/pic/sid/$detail[sid]}">店铺展示</a> </div></li>
<li><div><a href="{url product/list/sid/$sid}">产品展厅</a> </div></li>
<li><div><a href="{url coupon/list/sid/$sid}">优惠打折</a> </div></li>
<li><div><a href="{url item/vipvideo/id/$detail[sid]}">视频展播</a> </div></li>
<li class="in"><div><a href="{url item/vipcontact/id/$detail[sid]}">联系方式</a> </div></li>
</ul>
</div>
</div>
<!--头结束-->
<!--头部flash-->
<!--{if $detail[c_pictop1]}-->
<div style="margin:0 auto; width:976px;">
<SCRIPT src="{URLROOT}/img/shop/js/swfobject_source.js" type=text/javascript></SCRIPT>
<DIV id=flashFCI><A href="#" arget=_blank><IMG alt="" border=0></A></DIV>
<SCRIPT type=text/javascript>
var s1 = new SWFObject("{URLROOT}/img/shop/js/focusFlash_fp.swf", "mymovie1", "976", "150", "5", "#ffffff");
s1.addParam("wmode", "transparent");
s1.addParam("AllowscriptAccess", "sameDomain");
s1.addVariable("bigSrc", "$detail[c_pictop1]{if $detail[c_pictop2]}|$detail[c_pictop2]{/if}{if $detail[c_pictop3]}|$detail[c_pictop3]{/if}");
s1.addVariable("smallSrc", "|$detail[c_pictop1]|||");
s1.addVariable("href", "||");
s1.addVariable("txt", "||");
s1.addVariable("width", "976");
s1.addVariable("height", "150");
s1.write("flashFCI");
</SCRIPT>
</div>
<!--{/if}-->
<!--end头部flash-->
<div class="content">
<div class="pagejc">
<div class="col1">
<div class="titles">
<div class="fl">基本信息</div>
<div class="fr"></div>
<div class="clear"></div>
</div>
<div class="neirongs" style="padding:10px;">
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td valign="top">
<a href="{url item/pic/sid/$detail[sid]}"><img src="{URLROOT}/{if $detail[thumb]}$detail[thumb]{else}static/images/noimg.gif{/if}" alt="$detail[name]" width="110" height="80" /></a>
</td>
<td valign="top">
<!--{loop $reviewpot $val}-->$val[name]:<img src="{URLROOT}/img/shop/eshop/z{print cfloat($detail[$val[flag]])}.gif" alt="{print cfloat($detail[$val[flag]])} 分" /><br /><!--{/loop}-->
综合:<img src="{URLROOT}/img/shop/eshop/z{print cfloat($detail[avgsort])}.gif" alt="{print cfloat($detail[avgsort])} 分" />
</td>
</tr>
</table>
<div class="lefttitle">$detail[name]</div>
<div class="leftnr">
管 理 者:
<!--{if $detail[owner]}-->
<a href="{url space/index/username/$detail[owner]}" target="_blank">$detail[owner]</a>
<!--{elseif $catcfg[subject_apply]}-->
<a href="{url item/member/ac/subject_apply/sid/$detail[sid]}"><font color="#cc0000"><b>认领$model[item_name]</b></font></a>
<!--{/if}-->
<!--{if $catcfg[use_subbranch]}-->
<a href="{url item/member/ac/subject_add/subbranch_sid/$detail[sid]}">添加分店</a>
<!--{/if}--><br />
<!--{if $detail[finer]}-->
店铺级别:<img src="{URLROOT}/img/shop/eshop/vip$detail[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<table class="custom_field" border="0" cellspacing="0" cellpadding="0">
$detail_custom_field
</table>
</div>
</div>
<div class="mq"></div>
</div> <!--col1end-->
<div class="col2">
<!--{if $detail[content]}-->
<div class="titleb"><div class="fl">联系方式</div></div>
<style type="text/css"> #item_map { height:500px; *width:100%; _width:99%; }</style>
<div class="neirongb" style="padding-top:10px;">
<!--{if $model[usearea]}-->
<!--{eval $mapparam = array(
'title' => $detail[name] . $detail[subname],
'show' => $detail[mappoint]?1:0,
);}-->
<iframe src="{url index/map/width/700/height/500/title/$mapparam[title]/p/$detail[mappoint]/show/$mapparam[show]}" frameborder="0" scrolling="no" width="100%" height="500" id="item_map"></iframe>
<div style="text-align:center;">
<!--{if !$detail['mappoint']}-->
<a href="javascript:post_map($detail[sid], $detail[pid]);">地图未标注,我来标注</a>
<!--{else}-->
<a href="javascript:show_bigmap();">查看大图</a>
<a href="javascript:post_map($detail[sid], $detail[pid]);">报错</a>
<!--{/if}-->
</div>
<script type="text/javascript">
function show_bigmap() {
var src = "{url index/map/width/600/height/400/title/$mapparam[title]/p/$detail[mappoint]/show/$mapparam[show]}";
var html = '<iframe src="' + src + '" frameborder="0" scrolling="no" width="100%" height="400" id="ifupmap_map"></iframe>';
dlgOpen('查看大图', html, 600, 450);
}
</script>
<!--{/if}-->
</div>
<!--{/if}-->
</div><!--col2-->
<div class="clear"></div>
</div><!--pagejc-->
</div><!--content-->
</div><!--wrapper-->
{template vip2_footer}
<file_sep>/templates/mobile2/js/common.js
// 判断字符串是否为数字
function is_numeric(num) {
var patn = /^[0-9]+$/;
return patn.test(num);
}
//获取相对路径
function getUrl() {
if(arguments.length == 0) {
return typeof(mod)=='undefined' ? '' : '';
}
var flag = arguments[0];
var fullurl = arguments[4];
var crmod = modules[flag];
var url = !fullurl ? (urlroot+'/') : siteurl;
if(flag == 'modoer') {
url += 'index.php?m=index';
} else if(typeof(crmod)=='undefined') {
url += '';
} else {
url += 'index.php?m='+flag;
}
if(typeof(arguments[1])=='string') {
url += '&act='+arguments[1];
} else {
return url;
}
var param = arguments[2];
var type = typeof(param);
if(type=='object') {
var split = '?';
for (var i=0; i<param.length; i++) {
url += split + param[i];
split = '&';
}
} else if(type=='string') {
url += '&' + param;
}
if(typeof(arguments[3])=='string') {
url += '#' + arguments[3];
}
if(fullurl) url = siteurl + url;
return url;
}
// url标签格式转换成链接
function Url(url_format, anchor, full_url) {
if(url_format == '') return getUrl('');
var urlarr = url_format.split('/');
var flag = urlarr[0];
if(!urlarr[1]) return getUrl(flag);
var act = urlarr[1];
if(urlarr.length <= 2) return getUrl(flag, act);
var param = split = '';
for (var i=2; i<urlarr.length; i++) {
param += split + urlarr[i] + '=' + urlarr[++i];
split = '&';
}
return getUrl(flag, act, param, anchor, full_url);
}
//判断是否返回信息
function is_message(str) {
return str.match(/\{\s+caption:".*",message:".*".*\s*\}/);
}
//取随机值
function getRandom() {
return Math.floor(Math.random()*1000+1);
}
//提示对话框
function myAlert(data) {
var mymsg = eval('('+data+')'); //JSON转换
mymsg.message = mymsg.message.replace('ERROR:','');
if(mymsg.extra == 'login') {
/*
if(window.confirm(mymsg.caption + ',需要“登录”后才能继续。点击“确定”,登录网站。')) {
window.location.href = mymsg.url;
}
*/
dialog_login();
} else if(mymsg.extra == 'dlg') {
dlgOpen(mymsg.caption, mymsg.message.replace("{LF}","\r\n"), 400, 300, true);
} else if(mymsg.extra == 'msg') {
msgOpen(mymsg.caption, mymsg.message.replace("{LF}","\r\n"));
} else if (mymsg.extra == 'location') {
document.location = mymsg.message;
} else {
alert(mymsg.message);
}
}
//显示验证码
function show_seccode() {
var id= (arguments[0]) ? arguments[0] : 'seccode';
if($('#'+id).html()!='') return;
var sec = $('#'+id).empty();
var img = $('<img />')
.css({weight:"80px", height:"25px", cursor:"pointer"})
.attr("title",'点击更新验证码')
.click(function() {
this.src= Url('modoer/seccode/x/'+getRandom());
$('#'+id).show();
});
sec.append(img);
img.click();
}
function common_ajax_next_page(boxid,pageid) {
if(!ajax_loading) return;
ajax_loading = false;
var nexturl = $('#multipage').find('[nextpage="Y"]').attr('href');
$('#multipage').remove();
if(!nexturl) {
$('#'+pageid).remove();
return;
}
$('#'+pageid).find('a').text('正在加载...请稍后');
$.post(nexturl, { 'in_ajax':1, 'waterfall':'Y' },
function(result) {
if(result == null) {
$('#'+pageid).find('a').text('信息读取失败,请稍后尝试。');
} else if (is_message(result)) {
myAlert(result);
} else if(result != '') {
$('#'+boxid).append(result);
if($('#multipage').find('[nextpage="Y"]')[0]) {
ajax_loading = true;
$('#'+pageid).find('a').text('加载更多...');
} else {
$('#'+pageid).remove();
}
$('#'+boxid).append($('#nextpage'));
$('#'+boxid).listview('refresh');
}
});
}
function common_picture_nav(fx) {
var current = null;
var show = false;
$('.album_picture').find('li').each(function(i) {
if($(this).attr('show')!='N') {
current = $(this);
}
});
if(current[0]) {
if(fx == 'N') {
show = current.next();
if(!show[0]) {
show = $(".album_picture>li:first");
}
} else {
show = current.prev();
if(!show[0]) {
show = $(".album_picture>li:last");
}
}
} else {
show = $(".album_picture>li:first");
}
current.attr('show','N').hide();
show.attr('show','Y').show();
}
//js跳转,同时解决ie丢失referfer
function jslocation (url) {
while (url.indexOf('&') > 0) {
url = url.replace('&', '&');
}
document.location = url;
}
function pageBack() {
var a = window.location.href;
if (/#top/.test(a)) {
window.history.go( - 2);
window.location.load(window.location.href)
} else {
window.history.back();
window.location.load(window.location.href)
}
}
function createPicMove(a, b, c) {
var g = function(j) {
return "string" == typeof j ? document.getElementById(j) : j
};
var d = function(j, l) {
for (var k in l) {
j[k] = l[k]
}
return j
};
var f = function(j) {
return j.currentStyle || document.defaultView.getComputedStyle(j, null)
};
var i = function(l, j) {
var k = Array.prototype.slice.call(arguments).slice(2);
return function() {
return j.apply(l, k.concat(Array.prototype.slice.call(arguments)))
}
};
var e = {
Quart: {
easeOut: function(k, j, m, l) {
return - m * ((k = k / l - 1) * k * k * k - 1) + j
}
},
Back: {
easeOut: function(k, j, n, m, l) {
if (l == undefined) {
l = 1.70158
}
return n * ((k = k / m - 1) * k * ((l + 1) * k + l) + 1) + j
}
},
Bounce: {
easeOut: function(k, j, m, l) {
if ((k /= l) < (1 / 2.75)) {
return m * (7.5625 * k * k) + j
} else {
if (k < (2 / 2.75)) {
return m * (7.5625 * (k -= (1.5 / 2.75)) * k + 0.75) + j
} else {
if (k < (2.5 / 2.75)) {
return m * (7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375) + j
} else {
return m * (7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375) + j
}
}
}
}
}
};
var h = function(k, n, m, l) {
this._slider = g(n);
this._container = g(k);
this._timer = null;
this._count = Math.abs(m);
this._target = 0;
this._t = this._b = this._c = 0;
this.Index = 0;
this.SetOptions(l);
this.Auto = !!this.options.Auto;
this.Duration = Math.abs(this.options.Duration);
this.Time = Math.abs(this.options.Time);
this.Pause = Math.abs(this.options.Pause);
this.Tween = this.options.Tween;
this.onStart = this.options.onStart;
this.onFinish = this.options.onFinish;
var j = !!this.options.Vertical;
this._css = j ? "top": "left";
var o = f(this._container).position;
o == "relative" || o == "absolute" || (this._container.style.position = "relative");
this._container.style.overflow = "hidden";
this._slider.style.position = "absolute";
this.Change = this.options.Change ? this.options.Change: this._slider[j ? "offsetHeight": "offsetWidth"] / this._count
};
h.prototype = {
SetOptions: function(j) {
this.options = {
Vertical: true,
Auto: true,
Change: 0,
Duration: 50,
Time: 10,
Pause: 4000,
onStart: function() {},
onFinish: function() {},
Tween: e.Quart.easeOut
};
d(this.options, j || {})
},
Run: function(j) {
j == undefined && (j = this.Index);
j < 0 && (j = this._count - 1) || j >= this._count && (j = 0);
this._target = -Math.abs(this.Change) * (this.Index = j);
this._t = 0;
this._b = parseInt(f(this._slider)[this.options.Vertical ? "top": "left"]);
this._c = this._target - this._b;
this.onStart();
this.Move()
},
Move: function() {
clearTimeout(this._timer);
if (this._c && this._t < this.Duration) {
this.MoveTo(Math.round(this.Tween(this._t++, this._b, this._c, this.Duration)));
this._timer = setTimeout(i(this, this.Move), this.Time)
} else {
this.MoveTo(this._target);
this.Auto && (this._timer = setTimeout(i(this, this.Next), this.Pause))
}
},
MoveTo: function(j) {
this._slider.style[this._css] = j + "px"
},
Next: function() {
this.Run(++this.Index)
},
Previous: function() {
this.Run(--this.Index)
},
Stop: function() {
clearTimeout(this._timer);
this.MoveTo(this._target)
}
};
return new h(a, b, c, {
Vertical: false
})
}<file_sep>/core/modules/fenlei/helper/query.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
class query_fenlei {
//获取文章文类
function category($params) {
$loader =& _G('loader');
$category = $loader->variable('category','fenlei');
$result = '';
!$params['pid'] && $params['pid'] = 0;
if($params['pid'] && $params['parent']) {
$params['pid'] = (int) $category[$params['pid']]['pid'];
}
foreach($category as $key => $val) {
if($val['pid'] == $params['pid']) {
$result[$key] = $val;
}
}
return $result;
}
//获取文章列表
function getlist($params) {
extract($params);
$loader =& _G('loader');
$F =& $loader->model(':fenlei');
$F->db->from($F->table);
$F->db->select($select?$select:'fid,aid,catid,subject,username,dateline');
if($sid > 0) $F->db->where('sid',$sid);
if($uid > 0) $F->db->where('uid',$uid);
if($city_id > 0) $F->db->where('city_id',$city_id);
if($catid > 0) {
if(!$F->category[$catid]['pid']) {
$F->db->where('catid', $catid);
} else {
$catids = array();
foreach($F->category as $val) {
if($val['pid'] == $catid) $catids[] = $val['catid'];
}
$F->db->where('catid', $catids);
}
}
if($finer > 0) $F->db->where_more('finer',$finer);
if($comments > 0) $F->db->where_more('comments',$comments);
$F->db->where('status', 1);
$orderby && $F->db->order_by($orderby);
$F->db->limit($start, $rows);
if(!$r=$F->db->get()) { return null; }
$result = array();
while($v = $r->fetch_array()) {
$result[] = $v;
}
$r->free_result();
return $result;
}
}
?><file_sep>/templates/mobile3/js/global.js
$(function() {
$('#sel-area').click(function() {
$('.filter-mask').show();
$('#list-area').css('right','-274px');
$('#list-area').show();
$('#list-area').animate({right: '0'});
})
$('#sel-cat').click(function() {
$('.filter-mask').show();
$('#list-cat').css('right','-274px');
$('#list-cat').show();
$('#list-cat').animate({right: '0'});
})
$('#sel-top').click(function() {
$('.filter-mask').show();
$('#list-top').css('right','-274px');
$('#list-top').show();
$('#list-top').animate({right: '0'});
})
$('.filter-mask').click(function() {
//alert('this:'+this);
obj = event.srcElement ? event.srcElement : event.target;
//alert(obj);
if(obj == this) {
$('.filter-mask').hide();
$('#list-area').css('right','-274px');
$('#list-cat').css('right','-274px');
$('#list-top').css('right','-274px');
}
})
if (window.navigator.geolocation) {
var options = {
enableHighAccuracy: true,
};
//document.getElementById('currentPosLng').innerHTML = 'GPSing';
window.navigator.geolocation.getCurrentPosition(successHandle,errorHandle,options);
} else {
alert("浏览器不支持html5来获取地理位置信息");
}
append_distance();
$(window).scroll( function() {
//append_distance();
loadData(0);
});
})
var ajax_loading = true;
var totalheight = 0;
function successHandle(position){
var lng = position.coords.longitude;
var lat = position.coords.latitude;
$.cookie('lat',lat);
$.cookie('lng',lng);
append_distance();
loadData(1);//获取到当前坐标后加载第一组数据
}
function errorHandle(error){
loadData(0);
}
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
function append_distance() {
//alert(55555);
if ($.cookie('lat') && $.cookie('lng') && !$(this).find('.distance').text()) {
//alert(1111);
var local_lat = parseFloat($.cookie('lat'));
var local_lng = parseFloat($.cookie('lng'));
$('.des-dist').each(function(){
var item_lat = parseFloat($(this).find('.dist-lng').text());
var item_lng = parseFloat($(this).find('.dist-lat').text());
var dist = get_dist(item_lat,item_lng,local_lat,local_lng);
$(this).find('.distance').text(dist);
});
}
}
function get_dist(item_lat,item_lng,local_lat,local_lng) {
//alert(0);
var rad_item_lat = Math.PI/180*item_lat;
var rad_local_lat = Math.PI/180*local_lat;
var rad_item_lng = Math.PI/180*item_lng;
var rad_local_lng = Math.PI/180*local_lng;
var a=rad_item_lat - rad_local_lat;//两纬度之差,纬度<90
var b=rad_item_lng - rad_local_lng;//两经度之差纬度<180
//alert(999);
var dist = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2)+Math.cos(rad_item_lat)*Math.cos(rad_local_lat)*Math.pow(Math.sin(b/2),2)))*6378.137;
dist = Math.round(dist*1000);
if (dist>=1000) {
dist = dist/1000;
dist = Math.round(dist,2)+'Km';
}
else {
dist +='m';
}
return dist;
}
function common_ajax_next_page(boxid,pageid,isFirst) {
if(!ajax_loading) return;
ajax_loading = false;
var nexturl;
if (isFirst) {
nexturl = window.location.href;
} else {
nexturl = $('#multipage').find('[nextpage="Y"]').attr('href');
}
$('#multipage').remove();
if(!nexturl) {
$('#'+pageid).hide();
return;
}
$('#'+pageid).show();
$.post(nexturl, { 'in_ajax':1,'waterfall':'Y'},
function(result) {
if(result == null) {
$('#'+pageid).show();
} else if(result != '') {
if (isFirst) {
$('#'+boxid).empty();
}
$('#'+boxid).append(result);
append_distance();
if($('#multipage').find('[nextpage="Y"]')[0]) {
ajax_loading = true;
} else {
$('#'+pageid).hide();
}
}
});
}
function loadData(isFirst){
totalheight = parseFloat($(window).height()) + parseFloat($(window).scrollTop());
if ($(document).height() <= totalheight) { // 说明滚动条已达底部
/*这里使用Ajax加载更多内容*/
common_ajax_next_page('list-box','loading',isFirst);
}
}
function loadimg(pic){
var bigimg = document.getElementById("banner1");
bigimg.attr('src')=pic;
}<file_sep>/core/modules/item/mobile/pinyin.php
<?php
/*
* 参数说明:
http://huoqu.sinaapp.com/pinyin/?cn=[汉字字符串,必填项]
&m=[返回的数据格式,选填项] xml\json\js,pinyin\all\first
其中pinyin\all\first为返回String格式
m=pinyin 替换汉字为拼音,只返回拼音部分
m=all 替换汉字为拼音,其它原样返回
m=first 返回第一个汉字的第一个字母
*
*/
//$url = 'http://huoqu.sinaapp.com/pinyin/?a=中化人民共和国万岁123&m=all';
//$url = 'http://huoqu.sinaapp.com/pinyin/?a=汉字123&m=xml';
//$url = 'http://huoqu.sinaapp.com/pinyin/?a=汉字123&m=json';
//$url = 'http://huoqu.sinaapp.com/pinyin/?a=汉字123&m=js';
//$url = 'http://huoqu.sinaapp.com/pinyin/?a=汉字123&m=pinyin';
//$url = 'http://huoqu.sinaapp.com/pinyin/?a=汉字123&m=all';
$I = & $_G ['loader']->model ( 'item:subject' );
$tt=$I->getall ();
//print_r($tt);
foreach ($tt as $t){
$url = 'http://huoqu.sinaapp.com/pinyin/?m=all&a='.$t1['fullname'];
echo $url;
$html .= file_get_contents ( $url );
$arr=str_split($html,1);
$first='';
foreach ($t1 as $t2){
$s=ord($t2);
if($s>64&&$s<91)
$first.=$t2;
}
//$I->updatepy($t['id'],$html,$first);
}
echo ( $html );
echo "<br/>";
echo $first;
?>
<file_sep>/core/modules/album/admin/category.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
//由于category是自有类,需要加命名空间album:category
$C =& $_G['loader']->model('album:category');
$op = _input('op');
switch($op) {
case 'new':
$admin->tplname = cptpl('category_save', MOD_FLAG);
break;
case 'delete':
$C->delete(_post('catids'));
redirect('global_op_succeed_delete', cpurl($module,$act));
break;
case 'update':
$C->update($_POST['category']);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'add':
$post = $C->get_post($_POST['newcategory']);
$C->save($post);
redirect('global_op_succeed', cpurl($module,$act));
break;
case 'rebuild':
$C->rebuild($_POST['catids']);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
default:
$op = 'list';
//左连接查询
$C->db->join ( $C->table, 'c.sid', 'dbpre_subject', 's.sid', MF_DB_LJ );
if($_GET ['sname']!="")
$C->db->where ( 's.name', $_GET ['sname'] );
if ($total = $C->db->count ()) {
$C->db->sql_roll_back ( 'from,where' );
$C->db->limit ( get_start ( $_GET ['page'], $_GET ['offset'] ), $_GET ['offset'] );
$C->db->select ( 'c.*,s.name as subjectname,s.subname' );
$list = $C->db->get ();
$multipage = multi ( $total, $_GET ['offset'], $_GET ['page'], cpurl ( $module, $act, 'list', $_GET ) );
}
$admin->tplname = cptpl('category', MOD_FLAG);
}
?><file_sep>/core/modules/tuan/model/tgsite_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
class msm_tuan_tgsite extends ms_model {
var $table = 'dbpre_tuan_tgsite';
var $key = 'id';
var $model_flag = 'tuan';
function __construct() {
parent::__construct ();
$this->model_flag = 'tuan';
$this->init_field ();
$this->modcfg = $this->variable ( 'config' );
}
function msm_tuan_tgsite() {
$this->__construct ();
}
function init_field() {
$this->add_field ( 'sitename,siteurl,breakurl,sitetype,cityid,sort,pinyin,siteapi,localapi,apikey,apirep,css,recommend,isallowed,cityapi,cityrep,citysiteapi,qq,msn,tel,level,logo,email,goodorder,gather_method,breaksuff,limitcity,limitnum,transkey' );
// $this->add_field_fun('content,reply', '_T');
// $this->add_field_fun('tid,sort', 'intval');
}
function save($post, $id = null) {
$edit = $id > 0;
if ($edit) {
if (! $detail = $this->read ( $id ))
redirect ( 'tuan_tgsite_empty' );
}
$id = parent::save ( $post, $id );
return $id;
}
// 数据提交检测函数,实现父类的方法
function check_post($post, $edit = false) {
}
// 团购数据采集
function crawler($ids) {
$ids = array (
6
);
if (! is_array ( $ids ))
return '';
foreach ( $ids as $id ) {
$this->db->from ( $this->table );
$this->db->where ( 'id', $id );
if ($detail = $this->db->get_one ()) {
// 初始化采集类
$spiderfile = 'core' . DS . 'modules' . DS . 'tuan' . DS . 'model' . DS . 'spider_class.php';
include MUDDER_ROOT . $spiderfile;
$spider = new spider ( $detail );
// repurl:要采集的网址的接口地址
$repurl = $detail ["siteapi"];
$myurl = str_replace ( 'limengqi2', '?', str_replace ( 'limengqiurl1', '&', $repurl ) );
echo $myurl;
// 根据规则解析接口数据
$tempdata = $spider->parse_group ( $myurl );
$this->insert_temp_table ( $tempdata, $id );
}
}
}
// 将数据插入临时表
public function insert_temp_table($data = array(), $siteid) {
if (empty ( $data )) {
return false;
} else {
// array_values:返回一个包含给定数组中所有键值的数组,但不保留键名
// DATA中的每一行代表一条团购记录
$data = array_values ( $data );
// array_keys:返回包含数组中所有键名的一个新数组
// 构造字段数组
// implode:把数组元素组合为一个字符串
$fields = '`' . implode ( '`,`', array_keys ( $data [0] ) ) . '`';
$count = count ( $data );
// ceil:向上舍入为最接近的整数
// 每次入库200条记录
$all = ceil ( $count / 200 );
for($i = 0; $i < $all; $i ++) {
$start = $i * 200;
$last = ($i + 1) * 200 > $count ? $count : ($i + 1) * 200;
for($j = $start; $j < $last; $j ++) {
$values = '"' . implode ( '","', $data [$j] ) . '"';
$sql = "replace into ms_tuan_tempurl" . "(" . $fields . ") values(" . $values . ");";
$this->edit_easy ( $sql );
//echo $sql;
//echo "<br/>";
}
$sql = '';
}
return $count;
}
}
}
?><file_sep>/core/modules/fenlei/install/config.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
// 设置模块的默认配置信息
$moduleconfig = array(
'meta_keywords' => '分类信息',
'meta_description' => 'Modoer分类信息模块',
'post_item_owner' => '0',
'post_seccode' => '0',
'post_check' => '0',
'jscache_flag' => '225',
'pointtype' => 'point1',
'buy_top' => '1',
'tops' => '',
'top_level' => '3,2,1',
'color_days' => '1|10
3|15
5|20
7|25',
'buy_color' => '1',
'colors' => '#ff0000,#ffcc00,#330000,#0000ff,#009900,#ff00ff,#cc0000',
'post_des' => '',
'use_itemtpl' => '0',
'top_days' => '1|30
3|40
5|50
7|60',
);
?><file_sep>/core/modules/article/list.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
define('SCRIPTNAV', 'article');
// 实例化主题类
$A =& $_G['loader']->model(':article');
$category = $A->variable('category');
$num = abs ( _cookie ( 'list_display_item_subject_num', ( int ) $MOD ['list_num'], 'intval' ) );
(! $num || ! in_array ( $num, $numlist )) && $num = 20;
$offset = $num;
$wf_count = 5;
$wf_offset = $num * $wf_count;
$wf_page = _get ( 'wfpage', 1, MF_INT_KEY );
$start = get_start ( ($wf_page - 1) * $wf_count + $_GET ['page'], $num );
if (_input ( 'waterfall' ) == 'Y' && $_G ['in_ajax']) {
$tplname = 'share_waterfall_li';
}
$select="articleid,subject,a.dateline,pageview,comments,digg,uid,author,thumb,picture,introduce";
list ( $total, $list ) = $A->search($select, $orderby, $start, $offset);
if ($total) {
$multipage = multi ( $total, $num, $_GET ['page'], url ( "article/list/catid/$catid/order/$order/num/$num/total/$total/wfpage/$wf_page/page/_PAGE_" ) );
}
// seo setting
$seo_tags = get_seo_tags ();
$seo_tags ['area_name'] = $aid ? display ( 'modoer:area', "aid/$aid" ) : '';
$seo_tags ['root_category_keywords'] = $catcfg ['meta_keywords'];
$seo_tags ['root_category_description'] = $catcfg ['meta_description'];
! $MOD ['seo_list_title'] && $MOD ['seo_list_title'] = '{area_name}网上订餐,{area_name}美食,{area_name}优惠券,{area_name}团购--无锡美食网';
! $MOD ['seo_list_keywords'] && $MOD ['seo_list_keywords'] = '{root_category_keywords}';
! $MOD ['seo_list_description'] && $MOD ['seo_list_description'] = '{root_category_description}';
$_HEAD ['title'] = parse_seo_tags ( $MOD ['seo_list_title'], $seo_tags );
$_HEAD['keywords'] = ($detail['keywords'] ? (str_replace(" ",",",$detail['keywords']) . ',') : '') . $MOD['meta_keywords'];
$_HEAD['description'] = str_replace("\r\n",',',$detail['introduce']) . $MOD['meta_keywords'];
// 最近的浏览COOKIE
include template ( 'article_list' );
?><file_sep>/templates/item/sjstyle/pic.php
<?exit?>
<!--{eval
$_HEAD['title'] = $detail[name] . $detail[subname] . 的商家相册;
}-->
{template vip2_header}
<style type="text/css">@import url("{URLROOT}/img/shop/gallery.css");</style>
<script type="text/javascript" src="{URLROOT}/static/javascript/jquery.ad-gallery.pack.js"></script>
<script type="text/javascript">
$(function() {
var galleries = $('.ad-gallery').adGallery();
$('#switch-effect').change(
function() {
galleries[0].settings.effect = $(this).val();
return false;
}
);
$('#toggle-slideshow').click(
function() {
galleries[0].slideshow.toggle();
return false;
}
);
$('#toggle-description').click(
function() {
if(!galleries[0].settings.description_wrapper) {
galleries[0].settings.description_wrapper = $('#descriptions');
} else {
galleries[0].settings.description_wrapper = false;
}
return false;
}
);
});
</script>
<link href="img/shop/$subject[c_sjstyle]/style.css" rel="stylesheet" type="text/css" />
<!--头开始-->
<div class="header">
<div class="headerinfo">$detail[name] $detail[subname]</div>
<div class="headermeun">
<ul>
<li><div><a href="{url item/detail/id/$detail[sid]}">首页</a> </div></li>
<li><div><a href="{url item/vipabout/id/$detail[sid]}">店铺介绍</a> </div></li>
<li><div><a href="{url article/list/sid/$detail[sid]}">店铺动态</a> </div></li>
<li class="in"><div><a href="{url item/pic/sid/$detail[sid]}">店铺展示</a> </div></li>
<li><div><a href="{url product/list/sid/$detail[sid]}">产品展厅</a> </div></li>
<li><div><a href="{url coupon/list/sid/$detail[sid]}">优惠打折</a> </div></li>
<li><div><a href="{url item/vipvideo/id/$detail[sid]}">视频展播</a> </div></li>
<li><div><a href="{url item/vipcontact/id/$detail[sid]}">联系方式</a> </div></li>
</ul>
</div>
</div>
<!--头结束-->
<!--头部flash-->
<!--{if $detail[c_pictop1]}-->
<div style="margin:0 auto; width:976px;">
<SCRIPT src="{URLROOT}/img/shop/js/swfobject_source.js" type=text/javascript></SCRIPT>
<DIV id=flashFCI><A href="#" arget=_blank><IMG alt="" border=0></A></DIV>
<SCRIPT type=text/javascript>
var s1 = new SWFObject("{URLROOT}/img/shop/js/focusFlash_fp.swf", "mymovie1", "976", "150", "5", "#ffffff");
s1.addParam("wmode", "transparent");
s1.addParam("AllowscriptAccess", "sameDomain");
s1.addVariable("bigSrc", "$detail[c_pictop1]{if $detail[c_pictop2]}|$detail[c_pictop2]{/if}{if $detail[c_pictop3]}|$detail[c_pictop3]{/if}");
s1.addVariable("smallSrc", "|$detail[c_pictop1]|||");
s1.addVariable("href", "||");
s1.addVariable("txt", "||");
s1.addVariable("width", "976");
s1.addVariable("height", "150");
s1.write("flashFCI");
</SCRIPT>
</div>
<!--{/if}-->
<!--end头部flash-->
<div class="content">
<div class="pagejc">
<div class="col1">
<div class="titles">
<div class="fl">基本信息</div>
<div class="fr"></div>
<div class="clear"></div>
</div>
<div class="neirongs" style="padding:10px;">
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td align="center" valign="middle">
<a href="{url item/pic/sid/$detail[sid]}"><img src="{URLROOT}/{if $detail[thumb]}$detail[thumb]{else}static/images/noimg.gif{/if}" alt="$detail[name]" width="200" height="150" /></a>
</td>
</tr>
</table>
<div class="lefttitle">$detail[name]</div>
<div class="leftnr">
管 理 者:
<!--{if $detail[owner]}-->
<a href="{url space/index/username/$detail[owner]}" target="_blank">$detail[owner]</a>
<!--{elseif $catcfg[subject_apply]}-->
<a href="{url item/member/ac/subject_apply/sid/$detail[sid]}"><font color="#cc0000"><b>认领$model[item_name]</b></font></a>
<!--{/if}-->
<!--{if $catcfg[use_subbranch]}-->
<a href="{url item/member/ac/subject_add/subbranch_sid/$detail[sid]}">添加分店</a>
<!--{/if}--><br />
<!--{if $detail[finer]}-->
店铺级别:<img src="{URLROOT}/img/shop/eshop/vip$detail[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<table class="custom_field" border="0" cellspacing="0" cellpadding="0">
$detail_custom_field
</table>
</div>
</div>
<div class="mq"></div>
</div> <!--col1end-->
<div class="col2">
<div class="titleb"><div class="fl">相册详情</div><div class="fr"><span class="update-img-ico"><a href="{url item/member/ac/pic_upload/sid/$sid}">上传图片</a></span></div></div>
<div class="neirongb">
<div id="gallery" class="ad-gallery">
<div class="ad-image-wrapper">
</div>
<div class="ad-controls">
</div>
<div class="ad-nav">
<div class="ad-thumbs">
<ul class="ad-thumb-list">
{eval $index=0;}
{dbres $list $val}
<li>
<a href="{URLROOT}/$val[filename]"><img src="{URLROOT}/$val[thumb]" class="image{$index}" title="$val[title] / $val[username] / {date $val[addtime],'Y-m-d'}" alt="$val[comments]" longdesc="$val[url]"></a>
</li>
{eval $index++;}
{/dbres}
</ul>
</div>
</div>
</div>
<!--{if check_module('comment')}-->
<div class="comment_foo">
<style type="text/css">@import url("{URLROOT}/{$_G[tplurl]}css_comment.css");</style>
<script type="text/javascript" src="{URLROOT}/static/javascript/comment.js"></script>
<!--{eval $comment_modcfg = $_G['loader']->variable('config','comment');}-->
<!--{if $detail[comments]}-->
<!--{/if}-->
<a name="comment"></a>
{eval $_G['loader']->helper('form');}
<div id="comment_form">
<!--{if $user->check_access('comment_disable', $_G['loader']->model(':comment'), false)}-->
<!--{if $MOD[album_comment] && !$comment_modcfg['disable_comment']}-->
<!--{eval $idtype = 'album'; $id = $albumid; $title = 'Re:' . $detail[name];}-->
{template comment_post}
<!--{else}-->
<div class="messageborder">评论已关闭</div>
<!--{/if}-->
<!--{else}-->
<div class="messageborder">如果您要进行评论信息,请先 <a href="{url member/login}">登录</a> 或者 <a href="{url member/reg}">快速注册</a> 。</div>
<!--{/if}-->
</div>
<!--{if !$comment_modcfg['hidden_comment']}-->
<div class="mainrail rail-border-3">
<em>评论总数:<span class="font_2">$detail[comments]</span>条</em>
<h1 class="rail-h-3 rail-h-bg-3">网友评论</h1>
<div id="commentlist" style="margin-bottom:10px;"></div>
<script type="text/javascript">
$(document).ready(function() { get_comment('album',$albumid,1); });
</script>
</div>
<!--{/if}-->
</div>
<!--{/if}-->
</div>
</div><!--col2-->
<div class="clear"></div>
</div><!--pagejc-->
</div><!--content-->
</div><!--wrapper-->
{template vip2_footer}
<file_sep>/templates/item/vip/fenlei_listbak.php
<?exit?>
<!--{eval
$head_title = array();
isset($subject[name]) && $head_title[] = $subject[name].$subject[subname];
isset($area[$aid]) && $head_title[] = $area[$aid][name];
isset($F->category[$catid]) && $head_title[] = $F->category[$catid][name];
$head_title[] = $MOD[name];
$_HEAD['title'] = implode($_CFG['titlesplit'],$head_title);
}-->
<!--{template 'header', 'item', $detail[templateid]}-->
<div id="body">
<div class="link_path">
<em><span class="review-ico"><a href="{url fenlei/member/ac/manage/op/add}"><b>发布信息</b></a></span></em>
<div class="home-ico"><a href="{url modoer/index}">$_CITY[name]</a> » {print implode(' » ', $urlpath)}
</div> </div>
<div id="fenlei_left">
<div class="f_category">
<ul>
<h3>按地区查找:</h3>
{get:modoer val=area(pid/$_CITY[aid])}
<li$active[paid][$val[aid]]><a href="{url fenlei/list/sid/$sid/aid/$val[aid]/catid/$catid}">$val[name]</a></li>
{/get}
</ul><div class="clear"></div>
<!--{if $area_level==3}-->
<ul>
<h3>按街道查找:</h3>
{get:modoer val=area(pid/$paid)}
<li$active[aid][$val[aid]]><a href="{url fenlei/list/sid/$sid/aid/$val[aid]/catid/$catid}">$val[name]</a></li>
{/get}
</ul><div class="clear"></div>
<!--{/if}-->
<ul>
<h3>按大分类查找:</h3>
{get:fenlei val=category(pid/0)}
<li$active[pid][$val[catid]]><a href="{url fenlei/list/sid/$sid/aid/$aid/catid/$val[catid]}">$val[name]</a></li>
{/get}
</ul><div class="clear"></div>
<ul>
<h3>按子分类查找:</h3>
{get:fenlei val=category(pid/$pid)}
<li$active[catid][$val[catid]]><a href="{url fenlei/list/sid/$sid/aid/$aid/catid/$val[catid]}">$val[name]</a></li>
{/get}
</ul><div class="clear"></div>
</div>
<div class="fenlei-list">
<!--{if $tops}-->
<!--{eval $fenlelist =& $tops;}-->
<!--{template fenlei_list_normal}-->
<!--{/if}-->
<!--{if $total}-->
<!--{eval $fenlelist =& $list;}-->
<!--{template fenlei_list_normal}-->
<div class="multipage">$multipage</div>
<!--{/if}-->
<!--{if !$tops && !$list}-->
<div class="messageborder">没有找到信息。</div>
<!--{/if}-->
</div>
</div>
<div id="fenlei_right">
<div class="mainrail rail-border-3">
<h3 class="rail-h-3 rail-h-bg-3">广告位招商</h3>
{include display('adv:show','name/fenlei_list右侧广告位')}
</div>
<!--{if $subject}-->
<script type="text/javascript">loadscript('item');</script>
<div class="mainrail rail-border-3">
<h2 class="rail-h-2"><b><a href="{url item/detail/id/$subject[sid]}"><span class="font_2">$subject[name] $subject[subname]</span></a></b></h2>
<div class="subject">
<!--{eval $reviewcfg = $_G['loader']->variable('config','review');}-->
<p class="start start{print get_star($subject[avgsort],$reviewcfg[scoretype])}"></p>
<table class="subject_field_list" border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2"><span class="font_2">$subject[reviews]</span>点评,
<span class="font_2">$subject[guestbooks]</span>留言,
<span class="font_2">$subject[pageviews]</span>浏览</td>
</tr>
$subject_field_table_tr
</table>
<a class="abtn1" href="{url review/member/ac/add/type/item_subject/id/$subject[sid]}"><span>我要点评</span></a>
<a class="abtn2" href="{url item/detail/id/$subject[sid]/view/guestbook}#guestbook"><span>留言</span></a>
<div class="clear"></div>
</div>
</div>
<!--{else}-->
<div class="mainrail rail-border-3">
<h2 class="rail-h-3 rail-h-bg-3">搜索</h2>
<form method="get" action="{URLROOT}/index.php">
<input type="hidden" name="act" value="search" />
<input type="hidden" name="module_flag" value="fenlei" />
<table class="xsearch" border="0" cellspacing="0" cellpadding="0">
<tr><td width="60" align="right">所在地区:</td>
<td width="*">
<select name="aid">
<option value="0" selected="selected" disabled>==选择地区==</option>
<!--{print form_area($_CITY[aid],$aid)}-->
</select>
</td>
</tr>
<tr><td align="right">所属分类:</td>
<td>
<select name="catid">
<option value="0" selected="selected" disabled>==选择分类==</option>
<!--{get:fenlei val=category(pid/0)}-->
<option value="$val[catid]"{if $catid==$val[catid]} selected{/if}>$val[name]</option>
<!--{get:fenlei _val=category(pid/$val[catid])}-->
<option value="$_val[catid]"{if $catid==$_val[catid]} selected{/if}> └$_val[name]</option>
<!--{/get}-->
<!--{/get}-->
</select>
</td></tr>
<tr><td align="right">发布会员:</td>
<td><input type="text" name="username" value="$username" class="t_input" size="25" /></td></tr>
<tr><td align="right">关键字:</td>
<td><input type="text" name="keyword" value="$keyword" class="t_input" size="25" /></td></tr>
<tr><td> </td><td><input type="submit" value=" 搜索 " /></td></tr>
</table>
</form>
</div>
<!--{/if}-->
<div class="mainrail rail-border-3">
<h3 class="rail-h-3 rail-h-bg-3">特别推荐</h3>
<ul class="rail-list">
{get:fenlei val=getlist(city_id/_CITYID_/finer/1/row/10)}
<li><cite>{date $val[dateline],'m-d'}</cite><a href="{url fenlei/detail/id/$val[fid]}">{sublen $val[subject],20}</a></li>
{getempty(val)}
<li>暂无信息</li>
{/get}
</ul>
</div>
<div class="mainrail rail-border-3">
<h3 class="rail-h-3 rail-h-bg-3">最新发布</h3>
<ul class="rail-list">
{get:fenlei val=getlist(city_id/_CITYID_/orderby/dateline DESC/row/10)}
<li><cite>{date $val[dateline],'m-d'}</cite><a href="{url fenlei/detail/id/$val[fid]}">{sublen $val[subject],20}</a></li>
{getempty(val)}
<li>暂无信息</li>
{/get}
</ul>
</div>
</div>
<div class="clear"></div>
</div>
<!--{template 'footer', 'item', $detail[templateid]}--><file_sep>/core/modules/tuan/coupon.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'tuan');
$C = $_G['loader']->model('tuan:coupon');
$op = _get('op');
$id = _get('id',null,'intval');
switch($op) {
case 'print':
if(!$user->isLogin) {
$forward = $_G['web']['reuri'] ? ($_G['web']['url'] . $_G['web']['reuri']) : url('modoer','',1);
header('Location:' . url('member/login/forward/'.base64_encode(str_replace('&','&',$forward))));
exit;
}
if(!$coupon = $C->read($id)) redirect('tuan_coupon_empty');
if($coupon['uid'] != $user->uid) redirect('tuan_coupon_print_access');
$T =& $_G['loader']->model(':tuan');
if(!$tuan = $T->read($coupon['tid'])) redirect('tuan_empty');
$coupon_print = $tuan['coupon_print'] ? unserialize($tuan['coupon_print']) : array();
$member = $user->read($coupon['uid']);
include template('tuan_coupon_print');
break;
case 'sms':
$C->single_send_sms($id);
redirect('tuan_sms_send_succeed');
default:
show_error('global_op_unkown');
}
?><file_sep>/core/modules/party/admin/templates/party_check.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="post" name="myform" action="<?=cpurl($module,$act)?>&">
<div class="space">
<div class="subtitle">活动审核</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" id="config1" trmouse="Y">
<tr class="altbg1">
<td width="25">选</td>
<td width="*">名称</td>
<td width="150">地点</td>
<td width="80">组织人</td>
<td width="120">报名截止</td>
<td width="120">活动时间</td>
<td width="180">操作</td>
</tr>
<?if($total):?>
<?while($val = $list->fetch_array()):?>
<tr>
<td><input type="checkbox" name="partyids[]" value="<?=$val['partyid']?>" /></td>
<td><?=$val['subject']?></td>
<td><?=$val['address']?></td>
<td><?=$val['username']?></td>
<td><?=date('m-d H:i', $val['joinendtime'])?></td>
<td>开始:<?=date('m-d H:i',$val['begintime'])?><br />结束:<?=date('m-d H:i',$val['endtime'])?></td>
<td><a href="<?=cpurl($module,$act,'edit',array('partyid'=>$val['partyid']))?>">编辑活动</a></td>
</tr>
<?endwhile;?>
<tr class="altbg1">
<td colspan="2" class="altbg1">
<button type="button" onclick="checkbox_checked('partyids[]');" class="btn2">全选</button>
<td colspan="5" style="text-align:right;"><?=$multipage?></td>
</tr>
<?else:?>
<td colspan="9">暂无信息。</td>
<?endif;?>
</table>
</div>
<center>
<?if($total):?>
<input type="hidden" name="dosubmit" value="yes" />
<input type="hidden" name="op" value="checkup" />
<button type="button" class="btn" onclick="easy_submit('myform','checkup','partyids[]')">审核所选</button>
<button type="button" class="btn" onclick="easy_submit('myform','delete','partyids[]')">删除所选</button>
<?endif;?>
</center>
</form>
</div><file_sep>/core/modules/modoer/item/mobile/search.php
<?php
$urlpath[] = '搜索';
$q = _input('keyword', '', MF_TEXT);
if(($_GET['Pathinfo'] || $_GET['Rewrite']) && $q && $_G['charset'] != 'utf-8' && $_G['cfg']['utf8url']) {
$q = charset_convert($q,'utf-8',$_G['charset']);
}
$q = str_replace(array("\r\n","\r","\n") ,'', _T($q));
//if(!$q) location('mobile/index');
$urlpath[] = "关键字:$q";
$qlist = explode(' ', $q);
// $this->db->from('dbpre_subject');
$_G['db']->join ( 'dbpre_subject','s.catid','dbpre_category','c.catid' );
$_G['db']->join_together ( 's.aid','dbpre_area','a.aid');
$_G['db']->select ( 's.sid,s.name,s.subname,s.map_lat,s.map_lng,s.avgsort,s.avgprice,c.catid,a.aid,c.name as catname,a.name as aname' );
$_G['db']->where ( 's.city_id',8);
$ci = 0;
// $this->db->where_concat_like ( 's.name,c.name,a.name', "%{$q}%" );
while ($qlist[$ci]) {
$_G['db']->where_concat_like ( 's.name,c.name,a.name', "%{$qlist[$ci]}%" );
$ci++;
}
$_G['db']->where ( 's.status', 1 );
$_G['db']->order_by ('s.avgsort','DESC');
// $_G['db']->from('dbpre_subject');
// $_G['db']->select('*');
// $_G['db']->where('city_id', array(0,$_CITY['aid']));
// $_G['db']->where_concat_like('name,subname', "%{$q}%");
// $_G['db']->where('status', 1);
$multipage = '';
if($total = $_G['db']->count()) {
$_G['db']->sql_roll_back('from,select,where');
$orderby = array($post['ordersort']=>$post['ordertype']);
$offset = 10;
$start = get_start($_GET['page'], $offset);
$_G['db']->order_by($orderby);
$_G['db']->limit($start, $offset);
$list = $_G['db']->get();
if($total) {
$multipage = mobile_page($total, $offset, $_GET['page'], url("item/mobile/do/search/keyword/$q/page/_PAGE_"));
}
}
//显示模版
if($_G['in_ajax']) {
$tplname = 'item_search';
} else {
$tplname = 'item_search';
}
include mobile_template($tplname);
?>
<file_sep>/core/modules/product/install/module_uninstall.sql.bak
DROP TABLE IF EXISTS modoer_product_category;
DROP TABLE IF EXISTS modoer_product;<file_sep>/core/modules/item/film.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
//初始化
$where = array ();
$pid=19;
$I = & $_G ['loader']->model ( 'item:subject' );
$tt='';
$aid = ( int ) $_GET ['aid'];
if($aid!=0){
$A = & $_G ['loader']->model ( 'area' );
$aids=$A->get_list($aid);
foreach ($aids as $aa){
$tt=$tt.$aa['aid'].',';
}
$tt=$tt.$aid;
$where['aid']= explode(',', $tt);
print_r($tt);
}
//查询的数组
$order_arr = array (
'finer' => array (
'finer' => 'DESC' //按人气
),
'pageviews' => array (
'pageviews' => 'DESC' //按浏览
)
);
$orderby='finer';
//查询条件
$where['city_id'] = array(8);
$where['catid'] = 36;
$num = 15;
$select = 's.sid,pid,catid,aid,map_lat,map_lng,avgprice,name,subname,fullname,avgsort,sort1,sort2,sort3,sort4,sort5,sort6,sort7,sort8,best,finer,pageviews,reviews,pictures,favorites,thumb,products,coupons,sf.c_dizhi';
$start = get_start ( $_GET ['page'], $num );
list ( $total, $list ) = $I->getlist ( $pid, $select, $where, $order_arr [$orderby], $start, $num, true );
if ($total) {
$multipage = multi ( $total, $num, $_GET ['page'], url ( "item/film/aid/$aid/order/$order/num/$num/total/$total/page/_PAGE_" ) );
}
define ( 'SUBJECT_CATID', $catid );
$active = array ();
$active ['type'] [$type] = ' class="selected"';
$active ['num'] [$num] = ' class="selected"';
$active ['orderby'] [$orderby] = ' class="selected"';
// 最近的浏览COOKIE
include template ( 'item_film_list' );
// 解析Tags
function get_mytag($val) {
global $I;
return $I->get_mytag ( $val );
}
// 解析Att
function get_myatt($val) {
global $I;
return $I->get_myatt ( $val );
}
?><file_sep>/core/modules/item/mobile/wmdetail.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
$I = & $_G ['loader']->model ( MOD_FLAG . ':takeout' );
$sid = ( int ) $_GET ['sid'];
if (! $sid)
redirect ( lang ( 'global_sql_keyid_invalid', 'id' ) );
// 取得主题信息
if ($sid) {
$detail = $I->read ( $sid );
} else {
http_404 ();
}
if (! $detail || ! $detail ['status']) {
redirect ( 'item_empty' );
}
// 计算商家菜品总数
$P = & $_G ['loader']->model ( ':product' );
$detail ['pronums'] = $P->get_subject_total ( $sid );
// 解析配送范围
$S = & $_G ['loader']->model ( 'item:subject' );
$ranages= $S->get_mytag ( $detail ['c_range'] );
//载入模版
include mobile_template('item_waimai_detail');
?>
<file_sep>/core/modules/modoer/item/ajax/list.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
echo 333;
// $catid = isset ( $_GET ['catid'] ) ? ( int ) $_GET ['catid'] : ( int ) $MOD ['pid'];
// ! $catid and redirect ( 'item_empty_default_pid' );
// $allow_ops = array (
// 'get_recommend'
// );
// $login_ops = array (
// 'post_membereffect',
// 'add_favorite'
// );
// $op = empty ( $op ) || ! in_array ( $op, $allow_ops ) ? '' : $op;
// $S = & $_G ['loader']->model ( 'item:delivery' );
// $json = & $_G ['loader']->lib ( 'json', NULL, TRUE );
// if (! $op) {
// redirect ( 'global_op_unkown' );
// // } elseif (! $user->isLogin && in_array ( $op, $login_ops )) {
// // redirect ( 'member_not_login' );
// // }
// // 实例化主题类
// $I = & $_G ['loader']->model ( 'item:subject' );
// $I->get_category ( $catid );
// if (! $pid = $I->category ['catid']) {
// redirect ( 'item_cat_empty' );
// }
// define ( 'SCRIPTNAV', 'item_' . $pid );
// // 载入配置信息
// $catcfg = & $I->category ['config'];
// $modelid = $I->category ['modelid'];
// $rogid = $I->category ['review_opt_gid'];
// // 载入模型
// $model = $I->variable ( 'model_' . $modelid );
// // 载入点评选项
// $reviewpot = $_G ['loader']->variable ( 'opt_' . $rogid, 'review' );
// // 分类分级变量1主2子
// $category = $_G ['loader']->variable ( 'category_' . $pid, 'item' );
// // 判断子分类是否禁用
// if (! $category [$catid] ['enabled'])
// redirect ( 'item_cat_disabled' );
// // 当前catid的级别
// $category_level = $category [$catid] ['level'];
// $subcats = $category [$catid] ['subcats'];
// $urlpath = array ();
// $urlpath [] = url_path ( $category [$pid] ['name'], url ( "item/list/catid/$pid" ) );
// if ($catid != $pid) {
// if ($category_level > 2) {
// $urlpath [] = url_path ( $category [$category [$catid] ['pid']] ['name'], url ( "item/list/catid/{$category[$catid]['pid']}" ) );
// }
// $urlpath [] = url_path ( $category [$catid] ['name'], url ( "item/list/catid/$catid" ) );
// $attcats = $category [$catid] ['config'] ['attcat'];
// } else {
// $attcats = $catcfg ['attcat'];
// }
// // 使用了地图功能
// if ($model ['usearea']) {
// $aid = ( int ) $_GET ['aid'];
// if($aid==0) $aid=15;
// // 载入地区
// $area = $_G ['loader']->variable ( 'area_' . $_CITY ['aid'], null, false );
// // 地区级别
// $area_level = $area [$aid] ['level'];
// if ($area_level == 2) {
// $paid = 0;
// } else {
// $paid = $area [$aid] ['pid'];
// }
// if ($paid) {
// $urlpath [] = url_path ( $area [$paid] ['name'], url ( "item/list/catid/$pid/aid/$paid" ) );
// }
// if ($paid != $aid) {
// $urlpath [] = url_path ( $area [$aid] ['name'], url ( "item/list/catid/$pid/aid/$aid" ) );
// }
// // 区级:$boroughs;
// // 街道级:$streets;
// $boroughs = $streets = '';
// if ($area)
// foreach ( $area as $key => $val ) {
// if ($val ['level'] == 2)
// $boroughs [$key] = $val ['name'];
// if ($val ['level'] == 3 && ($aid == $val ['pid'] || $paid == $val ['pid']))
// {
// $streets [$key] = $val ['name'];
// }
// }
// }
// // 显示方式
// $typelist = lang ( 'item_list_displytype' );
// $type = _cookie ( 'list_display_item_subject_type', $catcfg ['displaytype'], '_T' );
// $type = isset ( $typelist [$type] ) ? $type : 'normal';
// // 排序数组
// $orderlist = lang ( 'item_list_orderlist' );
// // 查询的数组
// $order_arr = array (
// 'finer' => array (
// 'finer' => 'DESC' //按人气
// ),
// 'avgsort' => array (
// 'avgsort' => 'DESC'
// ),
// 'reviews' => array (
// 'reviews' => 'DESC'
// ),
// 'enjoy' => array (
// 'best' => 'DESC'
// ),
// 'price' => array (
// 'avgprice' => 'DESC'
// ),
// 'pageviews' => array (
// 'pageviews' => 'DESC' //按浏览
// )
// );
// $orderby = _cookie ( 'list_display_item_subject_orderby', $catcfg ['listorder'], '_T' );
// if (! $orderby || ! isset ( $order_arr [$orderby] )) {
// $orderby = $catcfg ['listorder'];
// }
// //构造查询条件
// $where = array ();
// if(empty($catid)||$catid==0){
// $catid=1;
// }
// if($catid==1){
// $catids='4,5,6,7,8,9,10,11,12,13,14,15,65';
// }elseif($catid==19){
// $catids='35,36,37,38,39,54,65';
// }else{
// $catids=$catid;
// }
// $where['s.catid']=explode(',', $catids);
// //$where['s.dzid']=array('where_not_equal',array(''));
// if(!empty($aid)||$aid!=0){
// $where['s.aid']=$aid;
// }
// $select = 's.sid,pid,catid,aid,map_lat,map_lng,avgprice,name,subname,fullname,avgsort,sort1,sort2,sort3,sort4,sort5,sort6,sort7,sort8,best,finer,pageviews,reviews,pictures,favorites,thumb,products,coupons,sf.c_dizhi,c_tags';
// $num = 10;//= abs ( _cookie ( 'list_display_item_subject_num', ( int ) $MOD ['list_num'], 'intval' ) );
// //(! $num || ! in_array ( $num, $numlist )) && $num = 20;
// $start = get_start ( $_GET ['page'], $num );
// list ( $total, $list ) = $I->getlist ( $pid, $select, $where, $order_arr [$orderby], $start, $num, true );
// if ($list) {
// while ( $val = $list->fetch_array () ) {
// $result [] = seatch_to_array ( $val );
// }
// $list->free_result ();
// $output = $json->encode(array('msg'=>'10001','data'=>$result));
// }
// echo 22;
// echo $output;
// //$atturl = item_att_url ();
// if ($total) {
// $multipage = multi ( $total, $num, $_GET ['page'], url ( "item/list/catid/$catid/aid/$aid/order/$order/type/$type/att/$atturl/num/$num/total/$total/wfpage/$wf_page/page/_PAGE_" ) );
// }
// define ( 'SUBJECT_CATID', $catid );
// $active = array ();
// $active ['type'] [$type] = ' class="selected"';
// $active ['num'] [$num] = ' class="selected"';
// $active ['orderby'] [$orderby] = ' class="selected"';
// // 最近的浏览COOKIE
// $cookie_subjects = $I->read_cookie ( $pid );
// // seo setting
// $seo_tags = get_seo_tags ();
// $seo_tags ['area_name'] = $aid ? display ( 'modoer:area', "aid/$aid" ) : '';
// $seo_tags ['root_category_name'] = display ( 'item:category', "catid/$pid" );
// $seo_tags ['current_category_name'] = display ( 'item:category', "catid/$catid" );
// $seo_tags ['page'] = $_GET ['page'];
// $seo_tags ['root_category_keywords'] = $catcfg ['meta_keywords'];
// $seo_tags ['root_category_description'] = $catcfg ['meta_description'];
// if ($att) {
// foreach ( $att as $_att_v ) {
// list ( $_attcatid, $_attid ) = explode ( '.', $_att_v );
// $_attcatid = ( int ) $_attcatid;
// $_attid = ( int ) $_attid;
// if ($_attcatid > 0 && $_attid > 0) {
// $_attlist = $_G ['loader']->variable ( 'att_list_' . $_attcatid, 'item' );
// $seo_tags ['att_name_' . $_attcatid] = $_attlist [$_attid] ['name'];
// }
// }
// }
// ! $MOD ['seo_list_title'] && $MOD ['seo_list_title'] = '{area_name}网上订餐,{area_name}美食,{area_name}优惠券,{area_name}团购--无锡美食网';
// ! $MOD ['seo_list_keywords'] && $MOD ['seo_list_keywords'] = '{root_category_keywords}';
// ! $MOD ['seo_list_description'] && $MOD ['seo_list_description'] = '{root_category_description}';
// $_HEAD ['title'] = parse_seo_tags ( $MOD ['seo_list_title'], $seo_tags );
// $_HEAD ['keywords'] = parse_seo_tags ( $MOD ['seo_list_keywords'], $seo_tags );
// $_HEAD ['description'] = parse_seo_tags ( $MOD ['seo_list_description'], $seo_tags );
// $_G ['show_sitename'] = FALSE;
// //设置显示模板
// if($pid==1) $tplname='item_subject_list';
// include template ( $tplname );
// //标签URL
// function item_att_url($catid = null, $attid = null, $del = false) {
// global $atts;
// $myatts = $atts;
// if ($catid) {
// if ($del) {
// unset ( $myatts [$catid] );
// } else {
// $myatts [$catid] = $attid;
// }
// }
// $url = $split = '';
// foreach ( $myatts as $catid => $attid ) {
// if (! $catid || ! is_numeric ( $catid ))
// continue;
// $url .= $split . $catid . '.' . $attid;
// $split = '_';
// }
// return $url;
// }
// // 解析Tags
// function get_mytag($val) {
// global $I;
// return $I->get_mytag ( $val );
// }
// // 解析Att
// function get_myatt($val) {
// global $I;
// return $I->get_myatt ( $val );
//}
?><file_sep>/templates/item/vip/guestbook.php
<?exit?>
<!--{eval
$_HEAD['title'] = $detail[name] . $detail[subname] . 的留言板;
}-->
<!--{template 'header', 'item', $detail[templateid]}-->
<link href="{URLROOT}/img/vipfiles/css/shopEx_$detail[c_vipstyle].css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
loadscript('swfobject');
$(document).ready(function() {
if(!$.browser.msie && !$.browser.safari) {
var d = $("#thumb");
var dh = parseInt(d.css("height").replace("px",''));
var ih = parseInt(d.find("img").css("height").replace("px",''));
if(dh - ih < 3) return;
var top = Math.ceil((dh - ih) / 2);
d.find("img").css("margin-top",top+"px");
}
<!--{if $MOD['show_thumb'] && $detail['pictures']}-->
get_pictures($sid);
<!--{/if}-->
get_membereffect($sid, $modelid);
});
</script>
<body>
<div class="wrap">
<div id="header">
<div id="crumb">
<p id="crumbL"><a href="{url modoer/index}">首页</a> » {print implode(' » ', $urlpath)} » $detail[name] $detail[subname]
<p id="crumbR"><a href="javascript:post_log($detail[sid]);">补充信息</a> | <a href="{url item/member/ac/subject_add/subbranch_sid/$detail[sid]}">增加分店</a> | <a href="{url member/index}">管理本店</a></p>
</div>
<div id="shopBanner">
<h1>$detail[name] $detail[subname]</h1>
<p>
<!--{if $detail[c_add]}-->
<B>地址:</B></LABEL>$detail[c_add]
<!--{/if}-->
<!--{if $detail[c_tel]}-->
<B>电话:</B></LABEL>$detail[c_tel]</p>
<!--{/if}-->
<div class="headerPic">
<img src="{if $detail[c_vipbanner]}$detail[c_vipbanner]{else}{URLROOT}img/haibao/nonbanner.png{/if}" alt="$detail[name] $detail[subname]店铺海报" width="950" height="150"/>
</div>
</div>
<div id="nav">
<ul>
<!--
<li><a href="#"><span>Array</span></a></li>
<li><a href="#"><span></span></a></li>
<li class="special"><a href="#"><span>导航栏介绍</span></a></li>
-->
<li><a href="{url item/detail/id/$detail[sid]}"><span>首页</span></a></li>
<li><a href="{url article/list/sid/$sid}"><span>店铺资讯</span></a> </li>
<li><a href="{url fenlei/list/sid/$sid}"><span>诚聘英才</span></a> </li>
<li><a href="{url product/list/sid/$sid}"><span>产品展厅</span></a> </li>
<li><a href="{url coupon/list/sid/$sid}"><span>优惠打折</span></a> </li>
<li><a href="{url item/pic/sid/$detail[sid]}"><span>商家相册</span></a> </li>
<li><a href="{url item/vipabout/id/$detail[sid]}"><span>关于我们</span></a></li>
<li><a href="{url item/vipreview/id/$detail[sid]}"><span>会员点评</span></a></li>
<li class="current" ><a href="{url item/vipguestbook/id/$detail[sid]}"><span>留言板</span></a></li>
</ul>
</div>
</div>
<div id="smartAd"><img src="{if $detail[c_vipbanner2]}$detail[c_vipbanner2]{else}{URLROOT}img/haibao//non.png{/if}" alt="$detail[name] $detail[subname]店铺海报"/></a><br />
</div>
<div id="mainBody">
<div id="mainBodyL">
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>【$detail[name] $detail[subname]】</h2>
<p class="deafBoxTitMore"><a href="{url item/vipabout/id/$detail[sid]}">更多</a></p>
</div>
<div class="deafBoxCon">
<dl>
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td valign="top">
<a href="{url item/pic/sid/$detail[sid]}"><img src="{URLROOT}/{if $detail[thumb]}$detail[thumb]{else}static/images/noimg.gif{/if}" alt="$detail[name]" width="110" height="80" /></a>
</td>
<td valign="top">
<!--{loop $reviewpot $val}-->$val[name]:<img src="{URLROOT}/img/vipfiles/img/z{print cfloat($detail[$val[flag]])}.gif" alt="{print cfloat($detail[$val[flag]])} 分" /><br /><!--{/loop}-->
综合:<img src="{URLROOT}/img/vipfiles/img/z{print cfloat($detail[avgsort])}.gif" alt="{print cfloat($detail[avgsort])} 分" />
</td>
</tr>
</table>
<p> </p>
<!--{if $detail[finer]}-->
店铺级别:<img src="{URLROOT}/img/vipfiles/img/vip$detail[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<p> </p>
<table class="custom_field" border="0" cellspacing="0" cellpadding="0">
$detail_custom_field
</table>
</dl>
</div>
</div>
<div id="position" class="deafBox">
<div class="deafBoxTit">
<h2>商户所在位置</h2>
</div>
<div class="deafBoxCon">
<!--{eval $mapparam = array(
'width' => '270',
'height' => '265',
'title' => $subject[name] . $subject[subname],
'show' => $detail[mappoint]?1:0,
);}-->
<iframe id="item_map" src="{url index/map/width/270/height/150/title/$mapparam[title]/p/$detail[mappoint]/show/$mapparam[show]}" frameborder="0" scrolling="no"></iframe>
<div align="center"> <span><!--{if !$detail['mappoint']}--><a href="javascript:post_map($detail[sid], $detail[pid]);">地图未标注,我来标注</a><!--{else}--><a href="javascript:show_bigmap();">查看大图</a> <a href="javascript:post_map($detail[sid], $detail[pid]);">报错</a><!--{/if}--></span></div>
<script type="text/javascript">
function show_bigmap() {
var src = "{url index/map/width/600/height/400/title/$mapparam[title]/p/$detail[mappoint]/show/$mapparam[show]}";
var html = '<iframe src="' + src + '" frameborder="0" scrolling="no" width="100%" height="400" id="ifupmap_map"></iframe>';
dlgOpen('查看大图', html, 600, 450);
}
</script>
</div>
</div>
</div>
<div id="chaBodyR">
<div id="chaBodyRTit">
<h2>会员留言</h2>
<p><a style="color:#FF3300;" href="javascript:post_guestbook($sid);"><b>我要留言</b></a></p>
</div>
<div class="deafBoxCon">
<div class="winFloat">
<div class="mainrail">
<div id="display" style="margin-top:10px">
<!--{if $detail[guestbooks] || $total}-->
<!--{dbres $guestbooks $val}-->
<div class="vipguestbook" id="guestbook_$val[guestbookid]">
<div class="title">
<em>
<!--{if $is_owner}-->
<a href="javascript:reply_guestbook($val[guestbookid]);">回复</a>
<a href="javascript:delete_guestbook($val[guestbookid]);">删除</a>
<!--{elseif $user->uid==$val[uid]}-->
<a href="javascript:edit_guestbook($val[guestbookid]);">编辑</a>
<a href="javascript:delete_guestbook($val[guestbookid]);">删除</a>
<!--{/if}-->
</em>
<h2><span class="member-ico"><a href="{url space/index/uid/$val[uid]}">$val[username]</a></span> 在 {date $val[dateline],'Y-m-d H:i'} 留言:</h2>
</div>
<div class="body">
<div class="content" id="guestbook_content_$val[guestbookid]">{print nl2br($val[content])}</div>
<!--{if $val[replytime]}-->
<div class="reply" id="guestbook_reply_$val[guestbookid]">回复:{print nl2br($val[reply])} <span class="font_3">{date $val[replytime],'m-d H:i'}</span></div>
<!--{/if}-->
</div>
</div>
<!--{/dbres}-->
<!--{if $multipage}-->
<div class="multipage">$multipage</div>
<!--{/if}-->
<!--{else}-->
<div class="messageborder"><span class="msg-ico">暂无留言信息,<a href="javascript:post_guestbook($detail[sid]);">发表您的留言信息</a>!</span></div>
<!--{/if}-->
<!--{if !$_G[in_ajax]}-->
</div>
<!--{if !$user->isLogin}-->
<div class="messageborder">
<span class="msg-ico">想要给<a href="#top"><span class="font_12">$detail[name].$detail[subname]</span></a>留言? 请先<a href="{url member/login}"><span class="font_12">登录</span></a>或<a href="{url membe/reg}"><span class="font_12">快速注册</span></a></span>
</div>
<!--{/if}-->
</div>
<!--{/if}-->
</div>
</div>
</div>
<div class="clear"></div>
</div>
<!--{template 'footer', 'item', $detail[templateid]}--><file_sep>/core/modules/weixin/model/wxdb_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_weixin_wxdb extends ms_model {
var $base_url = 'http://www.aaguo.com/';
var $model_flag = 'weixin';
function __construct() {
parent::__construct();
$this->model_flag = 'weixin';
$this->modcfg = $this->variable('config');
}
function msm_weixin_wxdb() {
$this->__construct();
}
function doSearch($q) {
$q = str_replace ( array (
"\r\n",
"\r",
"\n"
), '', $q );
if (! $q)
location ( 'mobile/index' );
$qlist = explode(' ', $q);
// $this->db->from('dbpre_subject');
$this->db->join ( 'dbpre_subject','s.catid','dbpre_category','c.catid' );
$this->db->join_together ( 's.aid','dbpre_area','a.aid');
$this->db->where ( 's.city_id',8);
$this->db->where_more ( 's.finer',100);
if ($q == 'locationsearch') {
// $this->db->select ( 's.sid,s.name,s.subname,s.thumb,c.name as catname,a.name as aname' );
$this->db->select ( "s.map_lng,s.map_lat,s.sid,s.name,s.subname,s.thumb,c.name as catname,a.name as aname,round((6371*acos(cos(radians($lat))*cos(radians( map_lat))*cos(radians(map_lng)-radians($lng))+sin(radians($lat))*sin(radians(map_lat)))),3) AS distance" );
$this->db->order_by ('distance','ASC');
} else {
$this->db->select ( 's.sid,s.name,s.subname,s.thumb,c.name as catname,a.name as aname' );
$ci = 0;
// $this->db->where_concat_like ( 's.name,c.name,a.name', "%{$q}%" );
while ($qlist[$ci]) {
$this->db->where_concat_like ( 's.name,c.name,a.name', "%{$qlist[$ci]}%" );
$ci++;
}
$this->db->order_by ('s.avgsort','DESC');
}
$this->db->where ( 's.status', 1 );
$result = $this->db->get();
$newsRst = Array();
if ($result) {
$i = 0;
while (( $row = $result->fetch_array())&&($i<8)) {
$newsRst [$i] = $row;
if ($newsRst[$i]['subname']) {
$newsRst[$i]['subname'] = '('.$newsRst[$i]['subname'].')';
}
$i++;
}
} else {
$newsRst = NULL;
}
return $newsRst;
}
function match_card($card,$wxid) {
//return $card.'#####'.$wxid;
$C = & $this->loader->model ( 'coupon:card' );
$M = & $this->loader->model ( 'coupon:match' );
if (empty ( $card )) {
}
$temp = explode ( ',', $card );
$cid = $temp [0];
$cpwd = $temp [1];
//return $cid.'#####'.$cpwd;
$r = $C->valide ( $cid, $cpwd );
if ($r == '1') {
//return "cid_error";
return '卡号错误!';
}
if ($r == '2') {
//return "already_matched";
return '该券已被绑定过!';
}
if ($r == '3') {
//return "password_error";
return '验证密码错误!';
}
// 验证成功
if ($r == '4') {
//$wxid='123';
$uid='5';
$post ['uid'] = $uid;
$post ['wxid'] = $wxid;
$post ['cid'] = $cid;
$post ['dateline'] = date ('Y-m-d h:m:s');
print_r($post);
if ($M->save ( $post,null )) {
return "绑定成功!";
} else {
return "绑定失败!";
}
//redirect ( '绑定成功!' );
}
}
function userReg($userId) {
$loader =& _G('loader');
$member =$loader->model(':member');
}
}
?><file_sep>/static/javascript/map/mapbar.js
var maplet = null;
var marker = null;
maplet = new Maplet(map_id);
//default:wuxi
if(p1==''||p2==''){
p1=120.3007;
p2=31.56617;
}
//Load map
var mpoint=new MPoint(p1,p2);
maplet.centerAndZoom(mpoint, view_level);
maplet.addControl(new MStandardControl());
//是否标记地图
if(show > 0) {
//路径是从根目录开始
var micon=new MIcon("static/images/bz1.jpg", 22, 34);
//var mwindow=new MInfoWindow("信息窗口标题", "信息窗口内容");
var marker = new MMarker(mpoint,micon);
maplet.addOverlay(marker);
marker.openInfoWindow();
}
function markmap() {
//标注
maplet.setMode("bookmark",
function(dataObj) {
if (marker != null) {
maplet.removeOverlay(marker);
}
document.getElementById("x").value = dataObj.point.lon;
document.getElementById("y").value = dataObj.point.lat;
marker = new MMarker(dataObj.point, new MIcon("static/images/bz1.jpg", 32, 32));
maplet.addOverlay(marker);
marker.setEditable(true);
MEvent.addListener(marker, "drag",
function() {
document.getElementById("point1").value = this.pt.lon;
document.getElementById("point2").value = this.pt.lat;
});
});
}
<file_sep>/core/modules/party/install/module_uninstall.sql
DROP TABLE IF EXISTS modoer_party;
DROP TABLE IF EXISTS modoer_party_apply;
DROP TABLE IF EXISTS modoer_party_category;
DROP TABLE IF EXISTS modoer_party_comment;
DROP TABLE IF EXISTS modoer_party_content;
DROP TABLE IF EXISTS modoer_party_picture;<file_sep>/core/modules/tuan/model/crule/lashou.php.bak
<?php
/*
* meituan rule
* rule:a=b
*
*/
$rule='response-deals-data=subject:limengqikey-deal-deal_title,
cityname:limengqikey-deal-city_name,
url:limengqikey-deal-deal_url,
nowprice:limengqikey-deal-price,
oldprice:limengqikey-deal-value,
lasttime:limengqikey-deal-end_time,
bizname:limengqikey-deal_range,
thumb:limengqikey-deal-deal_img,
starttime:limengqikey-deal-start_time,
nowpeople:limengqikey-deal-sales_num,
catname:limengqikey-deal_cate,
shopname:limengqikey-deal_seller';
?><file_sep>/core/lib/spider.php
<?php
/*
* $spider = new spider();
* $spider->addStartUrl(‘http://www.onlinedown.net/hits/week_{2,3}.htm’);
* $spider->addLayer(0,’list’,’../soft/{*}.htm’);
* $spider->addField(‘title’,'<title>{title}</title>’,array(‘华军软件园’,'安风信息网’));
* $spider->run(); $spider->output();
*/
class spider {
var $pages = array ();
var $result = array ();
var $startUrls = array ();
var $timeout;
var $httpContent;
var $httpHead = array ();
var $putHead = array ();
var $field_arr = array ();
var $deep;
var $layout_arr = array ();
var $limit = 0;
var $runtime = 0;
var $charset = 'UTF-8';
var $httpreferer;
var $pagelimit = 0;
var $filepath = './';
function spider() {
$this->timeout = 30;
}
function run() {
$begintime = $this->microtime_float ();
$cnt = 1;
foreach ( $this->startUrls as $starturl ) {
if (preg_match ( "~\{(\d+),(\d+)\}~", $starturl, $pagenum )) {
$pagebegin = intval ( $pagenum [1] );
$pageend = intval ( $pagenum [2] );
for(; $pagebegin <= $pageend; $pagebegin ++) {
$starturl = str_replace ( $pagenum [0], $pagebegin, $starturl );
$urllists = $this->getLists ( $this->layout_arr [0] ['pattern'], $this->getContent ( $starturl ) );
foreach ( $urllists as $url ) {
if (($this->limit > 0 && $cnt <= $this->limit) || $this->limit == 0) {
$this->filterContent ( $this->getContent ( $url, $starturl ) );
$cnt ++;
}
}
}
} else {
$urllists = $this->getLists ( $this->layout_arr [0] ['pattern'], $this->getContent ( $starturl ) );
foreach ( $urllists as $url ) {
if (($this->limit > 0 && $cnt <= $this->limit) || $this->limit == 0) {
$this->filterContent ( $this->getContent ( $url, $starturl ) );
$cnt ++;
}
}
}
}
$this->runtime = $this->microtime_float () - $begintime;
return $this->result;
}
function getLists($pattern = '', $content = '') {
if (strpos ( $pattern, '{*}' ) === false)
return array (
$pattern
);
$pattern = preg_quote ( $pattern );
$pattern = str_replace ( '\{\*\}', '([^\'\">]*)', $pattern );
$pattern = "~" . $pattern . "~is";
preg_match_all ( $pattern, $content, $preg_rs );
return array_unique ( $preg_rs [0] );
}
function getContent($url, $referer = '') {
$url = $this->urlRtoA ( $url, $referer );
preg_match ( "/(http:\/\/)([^:\/]*):?(\d*)(\/?.*)/i", $url, $preg_rs );
$host = $preg_rs [2];
$port = empty ( $preg_rs [3] ) ? 80 : $preg_rs [3];
$innerUrl = $preg_rs [4];
$fsp = fsockopen ( $host, $port, $errno, $errstr, $this->timeout );
if (! $fsp)
$this->log ( $errstr . '(' . $errno . ')' );
$output = "GET $url HTTP/1.0\r\nHost: $host\r\n";
if (! isset ( $this->putHead ['Accept'] ))
$this->putHead['Accept']= "*
function filterContent($content='')
{
$rs = array();
foreach ($this->field_arr as $field => $fieldinfo){
$rs[$field] = $this->getPregField($fieldinfo,$content);
}
$this->result[] = $rs;
}
function urlRtoA($relative,$referer){
if(preg_match("~^(http|ftp)://~i",$relative)) return $relative;
preg_match ( "~((http|ftp)://([^/]*)(.*/))([^/#]*)~i", $referer, $preg_rs );
$parentdir = $preg_rs [1];
$petrol = $preg_rs [2] . '://';
$host = $preg_rs [3];
if (preg_match ( "~^/~i", $relative ))
return $petrol . $host . $relative;
return $parentdir . $relative;
}
function getPregField($fieldinfo, $content) {
if (strpos ( $fieldinfo ['pattern'], '{' . $fieldinfo ['field'] . '}' ) === false)
return $fieldinfo ['pattern'];
if ($fieldinfo ['isregular'] == 'true') {
$pattern = $fieldinfo ['pattern'];
$pattern = str_replace ( '{' . $fieldinfo ['field'] . '}', '(?P<' . $fieldinfo ['field'] . '>.*?)', $pattern );
} else {
$pattern = preg_quote ( $fieldinfo ['pattern'] );
$pattern = str_replace ( '\{' . $fieldinfo ['field'] . '\}', '(?P<' . $fieldinfo ['field'] . '>.*?)', $pattern );
}
$pattern = "~" . $pattern . "~is";
preg_match ( $pattern, $content, $preg_rs );
$fieldresult = $preg_rs [$fieldinfo ['field']];
$fieldresult = preg_replace ( "~[\r\n]*~is", '', $fieldresult );
$replace_arr = $fieldinfo ['replace'];
if (is_array ( $replace_arr )) {
$replace_arr [0] = "~" . $replace_arr [0] . "~s";
$fieldresult = preg_replace ( $replace_arr [0], $replace_arr [1], $fieldresult );
}
if ($this->pagelimit == 0) {
if ($fieldinfo ['nextpage'] != '') {
$pattern = $fieldinfo ['nextpage'];
$pattern = str_replace ( '{nextpage}', '(?P<nextpage>[^\'\">]*?)', $pattern );
$pattern = "~" . $pattern . "~is";
if (preg_match ( $pattern, $content, $preg_rs ) && $preg_rs ['nextpage'] != '') {
$fieldresult .= $this->getPregField ( $fieldinfo, $this->getContent ( $preg_rs ['nextpage'], $this->httpreferer ) );
}
}
}
if (! empty ( $fieldinfo ['callback'] ))
$fieldresult = $fieldinfo ['callback'] ( $fieldresult );
return $fieldresult;
}
function addField($field, $pattern, $replace_arr = '', $isregular = 'false', $nextpage = '', $callback = '') {
$rs = array (
'field' => $field,
'pattern' => $pattern,
'replace' => $replace_arr,
'isregular' => $isregular,
'nextpage' => $nextpage,
'callback' => $callback
);
$this->field_arr [$field] = $rs;
}
function output() {
echo "The result is:<br/>";
echo "runtime :$this->runtime S<br/><pre>";
print_r ( $this->result );
echo "</pre>";
}
function saveXls($file = 'spider_result.xls') {
$fp = fopen ( $file, 'w' );
if ($fp) {
foreach ( $this->result as $result ) {
$line = implode ( "\t", $result ) . "\n";
fputs ( $fp, $line );
}
}
fclose ( $fp );
echo 'The result has been saved to ' . $file . '.<br/>Cost time:' . $this->runtime;
}
function saveSql($table = 'spider_result', $file = 'spider_result.sql') {
$fp = fopen ( $file, 'w' );
if ($fp) {
foreach ( $this->field_arr as $fieldinfo ) {
$sql_key .= ', `' . $fieldinfo ['field'] . '`';
}
$sql_key = substr ( $sql_key, 1 );
foreach ( $this->result as $result ) {
$sql_value = array ();
foreach ( $result as $key => $value ) {
$sql_value [] = "'" . $this->addslash ( $value ) . "'";
}
$line = "INSERT INTO `$table` ( $sql_key ) VALUES (" . join ( ', ', $sql_value ) . ");\r\n";
fputs ( $fp, $line );
}
}
fclose ( $fp );
echo 'The result has been saved to ' . $file . '.<br/>Cost time:' . $this->runtime;
}
function getHead($content) {
$head = explode ( "\r\n\r\n", $content );
$head = $head [0];
// echo $head;
if (! preg_match ( "~charset\=(.*)\r\n~i", $head, $preg_rs ))
preg_match ( '~charset=([^\"\']*)~i', $content, $preg_rs );
$this->httpHead ['charset'] = strtoupper ( trim ( $preg_rs [1] ) );
// preg_match("~charset\=(.*)~i",$head,$preg_rs);
return $this->httpHead;
}
function setCharset($charset) {
$this->charset = strtoupper ( $charset );
}
function setStartUrls($url_arr) {
$this->startUrls = $url_arr;
}
function addStartUrl($url) {
$this->startUrls [] = $url;
}
function addLayer($deep, $layout, $pattern = '', $isSimple = 'false', $isPageBreak = 'false') {
$this->layout_arr [$deep] = array (
'layout' => $layout,
'isSimple' => $isSimple,
'isPageBreak' => $isPageBreak,
'pattern' => $pattern
);
}
function setHead($name, $value) {
$this->putHead [$name] = $value;
}
function clearHtml($content, $cleartags = 'div') {
$cleartags_arr = explode ( '|', $cleartags );
foreach ( $cleartags_arr as $cleartag ) {
$pattern = '~<\/?' . $cleartag . '[^>]*>~is';
$content = preg_replace ( $pattern, '', $content );
}
return $content;
}
function log($str) {
echo $str . "<br/>\n";
}
function getRuntime() {
return $this->runtime;
}
function microtime_float() {
list ( $usec, $sec ) = explode ( " ", microtime () );
return (( float ) $usec + ( float ) $sec);
}
function addslash($string) {
return addslashes ( $string );
}
}
?><file_sep>/core/modules/tuan/admin/tuan.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$T =& $_G['loader']->model(':tuan');
$_G['loader']->helper('form','tuan');
$category = $T->variable('category');
$forward = get_forward(cpurl($module,$act));
(strposex($forward,'cpmenu') || strposex($forward,'cpheader')) && $forward = cpurl($module,$act);
$forward = str_replace('&', '&', $forward);
$op = _input('op');
switch($op) {
case 'delete':
$tid = _input('tid', null, 'intval');
$T->delete($tid);
redirect('global_op_succeed_delete', cpurl($module,$act));
break;
case 'update':
$tuan = _post('tuan');
$T->update($tuan);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'add':
$_G['loader']->lib('editor',null,false);
$editor = new ms_editor('content');
$editor->item = 'admin';
$editor->height = '250px';
$edit_html = $editor->create_html();
$twid = _get('twid',null,MF_INT_KEY);
if($twid > 0) {
$TW =& $_G['loader']->model('tuan:wish');
$wish = $TW->read($twid);
if(empty($wish)) redirect('tuan_wish_empty');
}
$mode = _get('mode',null,MF_TEXT);
$admin->tplname = cptpl('tuan_save', MOD_FLAG);
break;
case 'edit':
$tid = (int) _get('tid');
if(!$detail = $T->read($tid)) redirect('tuan_empty');
$S =& $_G['loader']->model('item:subject');
if($detail['sid']) $subject = $S->read($detail['sid']);
$_G['loader']->lib('editor',null,false);
$editor = new ms_editor('content');
$editor->item = 'admin';
$editor->height = '250px';
$editor->content = $detail['content'];
$edit_html = $editor->create_html();
$detail['starttime'] = date('Y-m-d', $detail['starttime']);
$detail['endtime'] = date('Y-m-d', $detail['endtime']);
$detail['expiretime'] > 0 && $detail['expiretime'] = date('Y-m-d', $detail['expiretime']);
!empty($detail['coupon_print']) && $detail['coupon_print'] = unserialize($detail['coupon_print']);
$mode = $detail['mode'];
$admin->tplname = cptpl('tuan_save', MOD_FLAG);
break;
case 'save':
if($_POST['do'] == 'edit') {
if(!$tid = (int)$_POST['tid']) redirect(lang('global_sql_keyid_invalid','tid'));
} else {
$tid = null;
}
$post = $T->get_post($_POST);
$tid = $T->save($post, $tid);
$twid = _input('twid',null,MF_INT_KEY);
if($twid > 0 && $tid > 0) {
$TW =& $_G['loader']->model('tuan:wish');
$wish = $TW->succeed($twid, $tid);
}
redirect('global_op_succeed', cpurl($module,$act),1);
break;
case 'detail':
$tid = (int) _get('tid');
$T->plan_status($tid);
if(!$detail = $T->read($tid)) redirect('tuan_empty');
$S =& $_G['loader']->model('item:subject');
$subject = $S->read($detail['sid']);
$detail['starttime'] = date('Y-m-d', $detail['starttime']);
$detail['endtime'] = date('Y-m-d', $detail['endtime']);
$detail['expiretime'] > 0 && $detail['expiretime'] = date('Y-m-d', $detail['expiretime']);
$detail['succeedtime'] > 0 && $detail['succeedtime'] = date('Y-m-d H:i', $detail['succeedtime']);
//order_total
$O =& $_G['loader']->model('tuan:order');
$order_total = $O->status_total($tid);
//coupon total
$C =& $_G['loader']->model('tuan:coupon');
$coupon_total = $C->status_total($tid);
//sms total
if($MOD['send_sms']) {
$sms_total = $C->sms_total($tid);
}
$admin->tplname = cptpl('tuan_detail', MOD_FLAG);
break;
case 'sendmail':
redirect('underdevelopment');
break;
case 'checklist':
$where = array();
$where['checked'] = 0;
$offset = 20;
$start = get_start($_GET['page'], $offset);
list($total, $list) = $T->find('*', $where, 'tid', $start, $offset, TRUE);
if($total) {
$multipage = multi($total, $offset, $_GET['page'], cpurl($module, $act, $op));
}
$check_count = $total;
$admin->tplname = cptpl('tuan_list', MOD_FLAG);
break;
default:
$op = 'list';
$where = array();
$_GET['status'] = $status = _get('status','new');
if(!$admin->is_founder) {
$_GET['city_id'] = '';
$where['city_id'] = $_CITY['aid'];
} elseif($_GET['city_id']) {
$where['city_id'] = $_GET['city_id'];
}
if($_GET['catid']) $where['catid'] = $_GET['catid'];
if($_GET['mode']) $where['mode'] = $_GET['mode'];
if($_GET['status']) $where['status'] = $_GET['status'];
if($_GET['subject']) $where['subject'] = $_GET['subject'];
$_GET['orderby'] = _get('orderby','listorder');
$_GET['ordersc'] = _get('ordersc','ASC');
$orderby = array($_GET['orderby'] => $_GET['ordersc']);
$start = get_start($_GET['page'], $_GET['offset']);
list($total, $list) = $T->find('*', $where, $orderby, $start, $_GET['offset'], TRUE);
if($total) {
$multipage = multi($total, $offset, $_GET['page'], cpurl($module, $act, 'list', $_GET));
}
$check_count = $T->get_check_count();
$admin->tplname = cptpl('tuan_list', MOD_FLAG);
}
?><file_sep>/core/modules/party/admin/templates/comment_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="post" name="myform" action="<?=cpurl($module,$act,'save')?>">
<div class="space">
<div class="subtitle">编辑/回复活动留言</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" id="config1" trmouse="Y">
<tr>
<td width="80" class="altbg1">留言内容:</td>
<td width="*"><textarea name="message" style="width:500px;height:80px;"><?=$detail['message']?></textarea></td>
</tr>
<tr>
<td class="altbg1">回复内容:</td>
<td><textarea name="reply" style="width:500px;height:80px;"><?=$detail['reply']?></textarea></td>
</tr>
</table>
</div>
<center>
<input type="hidden" name="commentid" value="<?=$commentid?>" />
<input type="hidden" name="partyid" value="<?=$detail['partyid']?>" />
<button type="submit" class="btn" name="dosubmit" value="yes">提交</button>
<button type="button" class="btn" onclick="history.(-1);">返回</button>
</center>
</form>
</div><file_sep>/core/modules/party/model/comment_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
class msm_party_comment extends ms_model {
var $table = 'dbpre_party_comment';
var $key = 'commentid';
var $model_flag = 'party';
function __construct() {
parent::__construct();
$this->model_flag = 'party';
$this->init_field();
$this->modcfg = $this->variable('config');
}
function msm_party_comment() {
parent::__construct();
}
function init_field() {
$this->add_field('partyid,parentid,uid,username,message,reply');
$this->add_field_fun('partyid,uid,parentid,dateline', 'intval');
$this->add_field_fun('username,message,reply', '_T');
}
function save($post,$commentid) {
$edit = $commentid > 0;
if($edit) {
if(!$detail = $this->read($commentid)) redirect('comment_empty');
} else {
$post['dateline'] = $this->global['timestamp'];
$post['uid'] = $this->global['user']->uid;
$post['username'] = $this->global['user']->username;
if(!$this->in_admin && isset($post['reply'])) unset($post['reply']);
}
$commentid = parent::save($post, $detail?$detail:$commentid);
return $commentid;
}
function reply($commentid, $reply) {
if(!is_numeric($commentid) || $commentid<1) redirect(lang('global_sql_keyid_invalid','commentid'));
if(!$comment = $this->read($commentid)) redirect('party_comment_empty');
if(!$reply = _T($reply)) redirect('party_comment_reply_empty');
//权限判断
$PARTY =& $this->loader->model(':party');
$detail = $PARTY->read($comment['partyid']);
$access = $detail && $detail['uid'] == $this->global['user']->uid;
if(!$access) redirect('party_comment_reply_access');
unset($PARTY);
//更新回复
$this->db->from($this->table);
$this->db->where('commentid',$commentid);
$this->db->set('reply', $reply);
$this->db->update();
}
function check_post(& $post, $edit = false) {
if(!is_numeric($post['partyid']) || $post['partyid'] < 1) redirect(lang('global_sql_keyid_invalid','partyid'));
if(!$post['message']) redirect('party_comment_message_empty');
if(!$this->in_admin && !$this->global['user']->isLogin) redirect('member_not_login');
}
function delete($commentids) {
$ids = parent::get_keyids($commentids);
$this->_delete(array('commentid'=>$ids));
}
function delete_partyids($partyids) {
$ids = parent::get_keyids($partyids);
$this->_delete(array('partyid'=>$ids));
}
function _delete($where) {
$this->db->from($this->table);
$this->db->where($where);
$this->db->delete();
}
}
?><file_sep>/core/modules/album/admin/templates/category_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/jquery.js"></script>
<script type="text/javascript" src="./static/javascript/item.js"></script>
<script type="text/javascript" src="./static/javascript/autocomplete/jquery.autocomplete.min.js"></script>
<link rel="Stylesheet" href="./static/javascript/autocomplete/jquery.autocomplete.css" />
<script type="text/javascript">
function check_submit() {
if($('[name=sname]').val()=="") {
alert('选择所属商家。');
return false;
} else if ($('[name=newcategory[name]]').val() == "" && $('[name=newcategory[name]]').val() == "") {
alert('请填写分类名称。');
return false;
}
return true;
}
</script>
<div id="body">
<form method="post" action="<?=cpurl($module,$act,'add')?>" name="myform" onsubmit="return check_submit();">
<input id="sid" type="hidden" name="newcategory[sid]" value="" />
<div class="space">
<div class="subtitle">添加/编辑菜单分类</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1" width="15%">所属商家:</td>
<td width="75%">
<input id="sname" type="text" name="sname" value="" class="txtbox" />
<script type="text/javascript">
var url="index.php?m=item&act=ajax&do=subject&op=search1";
$().ready(function() {
$("#sname").autocomplete(url, {
max: 12,
minChars: 1,
width: 400,
scrollHeight: 300,
matchContains: true,
autoFill: false,
formatItem: function(row, i, max, value) {
return value.split('-')[1];
},
formatResult: function(row, value) {
return value.split('-')[1];
}
});
$("#sname").result(function(event, data, formatted) {
$("#sid").val(data[0].split('-')[0] );
});
});
</script>
</td>
</tr>
<tr>
<td class="altbg1">分类名称:</td>
<td>
<input type="text" name="newcategory[name]" class="txtbox" />
</td>
</tr>
<tr>
<td class="altbg1">分类排序:</td>
<td>
<input type="text" name="newcategory[listorder]" class="txtbox" value="0"/>
</td>
</tr>
</table>
<center>
<input type="submit" value="提交" class="btn"/>
<input type="button" value="返回" class="btn" onclick="window.location='admin.php?module=album&act=category'"/>
</center>
</div>
</form>
</div><file_sep>/core/modules/party/model/picture_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
class msm_party_picture extends ms_model {
var $table = 'dbpre_party_picture';
var $key = 'picid';
var $model_flag = 'party';
var $status = array(0,1);
var $modcfg = array();
function __construct() {
parent::__construct();
$this->model_flag = 'party';
$this->init_field();
$this->modcfg = $this->variable('config');
}
function msm_party_comment() {
parent::__construct();
}
function init_field() {
$this->add_field('partyid,uid,username,title,pic,thumb,dateline,status');
$this->add_field_fun('partyid,uid,dateline,status', 'intval');
$this->add_field_fun('username,title,pic,thumb', '_T');
}
function checklist($where = array(), $offset=20) {
$this->db->from($this->table);
$this->db->join($this->table, 'pp.partyid', 'dbpre_party', 'p.partyid');
if($where) $this->db->where($where);
$this->db->where('pp.status',0);
$result = array(0,'','');
if($result[0] = $this->db->count()) {
$this->db->sql_roll_back('from,where');
$this->db->select('pp.*,p.subject');
$this->db->order_by('pp.dateline');
$this->db->limit(get_start($_GET['page'], $offset), $offset);
$result[1] = $this->db->get();
$result[2] = multi($total, $offset, $_GET['page'], cpurl($module,$act,'checklist'));
}
return $result;
}
function checkup($picids) {
$ids = parent::get_keyids($picids);
$this->db->from($this->table);
$this->db->where('picid', $ids);
$this->db->set('status',1);
$this->db->update();
}
function save($post,$picid=null) {
$edit = $picid > 0;
if($edit) {
if(!$detail = $this->read($picid)) redirect('party_picture_empty');
if(!$this->in_admin && isset($post['status'])) unset($post['status']);
} else {
$access = $this->in_admin || $this->check_upload_access($post['partyid']);
if(!$access) redirect('party_picture_access');
$post['dateline'] = $this->global['timestamp'];
$post['uid'] = $this->global['user']->uid;
$post['username'] = $this->global['user']->username;
if(!$this->in_admin) $post['status'] = $this->modcfg['pic_check'] ? 0 : 1;
}
if($_FILES['picture']['name']) {
$this->loader->lib('upload_image', NULL, FALSE);
$img = new ms_upload_image('picture', $this->global['cfg']['picture_ext']);
$this->upload_pic($img);
$post['pic'] = str_replace(DS, '/', $img->path . '/' . $img->filename);
$post['thumb'] = str_replace(DS, '/', $img->path . '/' . $img->thumb_filenames['thumb']['filename']);
}
define('RETURN_EVENT_ID', $post['status'] ? 'global_op_succeed' : 'global_op_succeed_check');
$picid = parent::save($post,$picid);
return $picid;
}
function update($post) {
if(!is_array($post)) redirect('global_op_unselect');
foreach($post as $id => $val) {
if(!is_numeric($id) || $id < 1) continue;
$title = _T($val['title']);
$this->db->from($this->table);
$this->db->set('title', $title);
$this->db->where('picid', $id);
$this->db->update();
}
}
function check_post(&$post, $edit = false) {
if(empty($post['title'])) redirect('party_picture_title_empty');
if(!$edit && empty($post['pic'])) redirect('party_picture_upload_empty');
!$this->global['user']->isLogin && redirect('member_not_login');
}
function upload_pic(&$img) {
$config = $this->variable('config');
$thumb_w = $this->modcfg['party_thumb_w'] ? $this->modcfg['party_thumb_w'] : 200;
$thumb_h = $this->modcfg['party_thumb_h'] ? $this->modcfg['party_thumb_h'] : 150;
$img->set_max_size($this->global['cfg']['picture_upload_size']);
$img->userWatermark = $this->global['cfg']['watermark'];
$img->watermark_postion = $this->global['cfg']['watermark_postion'];
$img->thumb_mod = $this->global['cfg']['picture_createthumb_mod'];
$img->set_thumb_level($this->global['cfg']['picture_createthumb_level']);
//$img->limit_ext = array('jpg','png','gif');//picture_ext
$img->set_ext($this->global['cfg']['picture_ext']);
$img->userWatermark = (int)$this->global['cfg']['watermark'];
$img->add_thumb('thumb', 'thumb_', $thumb_w, $thumb_h, 0);
$img->upload('party');
}
function delete($picids) {
$ids = parent::get_keyids($picids);
$this->_delete(array('picid'=>$ids));
}
function check_upload_access($partyid) {
$P =& $this->loader->model(':party');
if($P->is_myparty($partyid,$this->global['user']->uid)) return TRUE;
$A =& $this->loader->model('party:apply');
return $A->check_join_exists($partyid,$this->global['user']->uid);
}
function delete_partyids($partyids) {
$ids = parent::get_keyids($partyids);
$this->_delete(array('partyid'=>$ids));
}
function _delete($where) {
$this->db->from($this->table);
$this->db->where($where);
$this->db->select('picid,partyid,uid,pic,thumb,status');
if(!$q = $this->db->get()) return;
//获取我发起的活动
$mypartys = array();
if(!$this->in_admin) {
$PARTY =& $this->loader->model(':party');
$mypartys = $PARTY->mypartys($this->global['user']->uid);
}
$keyids = array();
while($v=$q->fetch_array()) {
//前台删除照片,删除图片需要判断图片的所属项,以避免非法的跨权限删除
$access = $this->in_admin || $this->global['user']->uid == $v['uid'] || in_array($v['partyid'], $mypartys);
if(!$access) redirect('party_picture_delete_access');
$keyids[] = $v['picid'];
if(strlen($v['pic'])>10) @unlink(MUDDER_ROOT . $v['pic']);
if(strlen($v['thumb'])>10) @unlink(MUDDER_ROOT . $v['thumb']);
}
$q->free_result();
if($keyids) {
parent::delete($keyids);
}
}
}
?><file_sep>/core/modules/party/admin/templates/party_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="get" action="<?=SELF?>">
<input type="hidden" name="module" value="<?=$module?>" />
<input type="hidden" name="act" value="<?=$act?>" />
<input type="hidden" name="op" value="<?=$op?>" />
<div class="space">
<div class="subtitle">活动筛选</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100" class="altbg1">活动类型</td>
<td width="350">
<select name="catid">
<option value="">==全部==</option>
<?=form_party_category(_get('catid'));?>
</select>
</td>
<td width="100" class="altbg1">活动地区</td>
<td width="*">
<?if($admin->is_founder):?>
<select name="city_id" onchange="select_city(this,'aid');">
<option value="">全部</option>
<?=form_city($_GET['city_id'])?>
</select>
<?endif;?>
<select name="aid" id="aid">
<option value="">全部</option>
<?=form_area($_GET['city_id'], $_GET['aid'])?>
</select>
</td>
</tr>
<tr>
<td class="altbg1">活动标题</td>
<td colspan="3"><input type="text" name="subject" class="txtbox" value="<?=$_GET['subject']?>" /></td>
</tr>
<tr>
<td class="altbg1">发起者</td>
<td><input type="text" name="username" class="txtbox3" value="<?=$_GET['username']?>" /></td>
<td width="100" class="altbg1">主题SID</td>
<td width="*"><input type="text" name="sid" class="txtbox3" value="<?=$_GET['sid']?>" /></td>
</tr>
<tr>
<td class="altbg1">发布时间</td>
<td colspan="3"><input type="text" name="starttime" class="txtbox3" value="<?=$_GET['starttime']?>" /> ~ <input type="text" name="endtime" class="txtbox3" value="<?=$_GET['endtime']?>" /> (YYYY-MM-DD)</td>
</tr>
<tr>
<td class="altbg1">结果排序</td>
<td colspan="3">
<select name="orderby">
<option value="partyid"<?=$_GET['orderby']=='partyid'?' selected="selected"':''?>>ID排序</option>
<option value="dateline"<?=$_GET['orderby']=='dateline'?' selected="selected"':''?>>发布时间</option>
<option value="pageview"<?=$_GET['orderby']=='pageview'?' selected="selected"':''?>>浏览量</option>
</select>
<select name="ordersc">
<option value="DESC"<?=$_GET['ordersc']=='DESC'?' selected="selected"':''?>>递减</option>
<option value="ASC"<?=$_GET['ordersc']=='ASC'?' selected="selected"':''?>>递增</option>
</select>
<select name="offset">
<option value="20"<?=$_GET['offset']=='20'?' selected="selected"':''?>>每页显示20个</option>
<option value="50"<?=$_GET['offset']=='50'?' selected="selected"':''?>>每页显示50个</option>
<option value="100"<?=$_GET['offset']=='100'?' selected="selected"':''?>>每页显示100个</option>
</select>
<button type="submit" value="yes" name="dosubmit" class="btn2">筛选</button>
<button type="button" class="btn2" onclick="document.location='<?=cpurl($module,$act,'add')?>';">发起活动</button>
</td>
</tr>
</table>
</div>
</form>
<?if($_GET['dosubmit']):?>
<form method="post" name="myform" action="<?=cpurl($module,$act)?>&">
<div class="space">
<div class="subtitle">活动管理</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" id="config1" trmouse="Y">
<tr class="altbg1">
<td width="25">选</td>
<td width="*">名称/地点</td>
<td width="80">组织人</td>
<td width="110">报名截止</td>
<td width="110">活动时间</td>
<td width="60">活动状态</td>
<td width="60">报名人数</td>
<td width="25">荐</td>
<td width="180">操作</td>
</tr>
<?if($total):?>
<?while($val = $list->fetch_array()):?>
<tr>
<input type="hidden" name="partys[<?=$val['partyid']?>][partyid]" value="<?=$val['partyid']?>" />
<td><input type="checkbox" name="partyids[]" value="<?=$val['partyid']?>" /></td>
<td>
<span class="font_2">[<?=template_print('modoer','area',array('aid'=>$val['city_id']))?>]</span><a href="<?=url("party/detail/id/$val[partyid]")?>" target="_blank"><?=$val['subject']?></a><br />
<?=$val['address']?></td>
<td><?=$val['username']?></td>
<td><?=date('m-d H:i', $val['joinendtime'])?></td>
<td>开始:<?=date('m-d H:i',$val['begintime'])?><br />结束:<?=date('m-d H:i',$val['endtime'])?></td>
<td><?=lang('party_flag_'.$val['flag'])?></td>
<td><?=$val['num']?></td>
<td><input type="checkbox" name="partys[<?=$val['partyid']?>]" value="1"<?if($val['finer'])echo' checked="checked"';?> /></td>
<td>
<a href="<?=cpurl($module,$act,'edit',array('partyid'=>$val['partyid']))?>">编辑活动</a>
<a href="<?=cpurl($module,'apply','',array('partyid'=>$val['partyid']))?>">报名会员</a>
<a href="<?=cpurl($module,'picture','',array('partyid'=>$val['partyid']))?>">照片管理</a><br />
<a href="<?=cpurl($module,'comment','',array('partyid'=>$val['partyid']))?>">留言管理</a>
<a href="<?=cpurl($module,'party','content',array('partyid'=>$val['partyid']))?>">精彩回顾</a>
</td>
</tr>
<?endwhile;?>
<tr class="altbg1">
<td colspan="2" class="altbg1">
<button type="button" onclick="checkbox_checked('partyids[]');" class="btn2">全选</button>
<td colspan="8" style="text-align:right;"><?=$multipage?></td>
</tr>
<?else:?>
<td colspan="10">暂无信息。</td>
<?endif;?>
</table>
</div>
<center>
<?if($total):?>
<input type="hidden" name="dosubmit" value="yes" />
<input type="hidden" name="op" value="update" />
<button type="button" class="btn" onclick="easy_submit('myform','update',null)">提交操作</button>
<button type="button" class="btn" onclick="easy_submit('myform','delete','partyids[]')">删除所选</button>
<?endif;?>
</center>
</form>
</div>
<?endif;?><file_sep>/core/modules/modoer/item/admin/templates/delivery_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/jquery.js"></script>
<script type="text/javascript" src="./static/javascript/item.js"></script>
<script type="text/javascript" src="./static/javascript/autocomplete/jquery.autocomplete.min.js"></script>
<link rel="Stylesheet" href="./static/javascript/autocomplete/jquery.autocomplete.css" />
<div id="body">
<form method="get" action="<?=SELF?>">
<input type="hidden" name="module" value="<?=$module?>" />
<input type="hidden" name="act" value="<?=$act?>" />
<input type="hidden" name="op" value="<?=$op?>" />
<input id="sid" name="sid" type="hidden"/>
<div class="space">
<div class="subtitle">外卖查询</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="50" class="altbg1">商家状态</td>
<td width="100">
<select name="f">
<option value="">全部</option>
<option value="0">未审核</option>
<option value="1">已审核</option>
</select>
</td>
<td width="50" class="altbg1">商家名称</td>
<td width="100">
<input type="text" id="sname" name="sname" class="txtbox3" />
<script type="text/javascript">
var url="index.php?m=item&act=ajax&do=subject&op=search1";
//var url="index.php?m=item&act=ajax&do=test";
$().ready(function() {
$("#sname").autocomplete(url, {
max: 12,
minChars: 1,
width: 400,
scrollHeight: 300,
matchContains: true,
autoFill: false,
formatItem: function(row, i, max, value) {
return value.split('-')[1];
},
formatResult: function(row, value) {
return value.split('-')[1];
}
});
$("#sname").result(function(event, data, formatted) {
$("#sid").val(data[0].split('-')[0] );
});
});
</script>
</td>
<td width="50" class="altbg1">
<button type="submit" value="yes" name="dosubmit" class="btn2">查 询</button>
</td>
</tr>
</table>
</div>
</form>
<form method="post" name="myform" action="<?=cpurl($module,$act,'',array('pid'=>$pid))?>">
<input type="hidden" id="hsid" name="hsid" />
<div class="space">
<div class="subtitle">外卖列表 </div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y">
<tr class="altbg1">
<td width="25">选择</td>
<td width="50">排序</td>
<td width="110">商家名称</td>
<td width="110">商家分类</td>
<td width="110">起送金额</td>
<td width="50" align="center">状态</td>
<td width="50">权重</td>
<td width="80">操作</td>
</tr>
<?if($total):?>
<?while($val=$list->fetch_array()):?>
<tr>
<td><input type="checkbox" name="sids[]" value="<?=$val['sid']?>" /></td>
<td><?=$val['c_listorder']?></td>
<td><?=$val['fullname']?></td>
<td><?=$val['fullname']?></td>
<td><?=$val['c_minprice']?></td>
<td><? if($val['c_status']='1') echo '营业'; else echo '歇业';?></td>
<td><?=$val['c_finer']?></td>
<td>
<a href="<?=cpurl($module,'delivery','update',array('sid'=>$val[sid]))?>">修改</a>|
<a href="admin.php?module=product&act=product_list&sid=<?=$val['sid']?>">菜单</a>
</td>
</tr>
<?endwhile;?>
<tr class="altbg1">
<td colspan="2"><button type="button" onclick="checkbox_checked('picids[]');" class="btn2">全选</button></td>
<td colspan="4" style="text-align:right;"><?=$multipage?></td>
</tr>
<?else:?>
<tr>
<td colspan="6">暂无信息。</td>
</tr>
<?endif;?>
</table>
</div>
<?if($total):?>
<center>
<input type="hidden" name="dosubmit" value="yes" />
<input type="hidden" name="op" value="checkup" />
<button type="button" class="btn" onclick="easy_submit('myform','update',null)">更新修改</button>
<button type="button" class="btn" onclick="easy_submit('myform','delete','sids[]')">删除所选</button>
</center>
<?endif;?>
</form>
</div>
<file_sep>/core/modules/tuan/wish.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'tuan');
$TW =& $_G['loader']->model('tuan:wish');
$offset = 10;
$start = get_start($_GET['page'], $offset);
$city_id = array(0,$_CITY['aid']);
$succeed = _get('succeed', null, MF_INT_KEY);
$orderby = array('twid'=>'DESC');
list($total,$list) = $TW->get_list($city_id,$succeed,$orderby,$start,$offset);
$_HEAD['keywords'] = $MOD['meta_keywords'];
$_HEAD['description'] = $MOD['meta_description'];
include template('tuan_wish');
?><file_sep>/core/modules/tuan/model/tuandh_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_tuan_tuandh extends ms_model {
var $table = 'dbpre_tuan_collect';
var $key = 'id';
var $model_flag = 'tuandh';
function __construct() {
parent::__construct ();
$this->model_flag = 'tuandh';
$this->init_field ();
}
function msm_tuandh() {
$this->__construct ();
}
function init_field() {
$this->add_field ( 'subject,picture,price,market_price,starttime,endtime,
sname,area,areaid,url,catname,intro,listorder,catid,status,siteid' );
$this->add_field_fun ( 'intro,subject,url', '_T' );
$this->add_field_fun ( 'areaid,catid', 'intval' );
}
// 团购数据筛选
function find($select = "*", $where = null, $orderby = null, $start = 0, $offset = 10, $total = FALSE) {
$this->db->from ( $this->table );
$where && $this->db->where ( $where );
$result = array (
0,
''
);
if ($total) {
if (! $result [0] = $this->db->count ()) {
return $result;
}
$this->db->sql_roll_back ( 'from,where' );
}
$this->db->select ( $select ? $select : '*' );
if ($orderby)
$this->db->order_by ( $orderby );
if ($start < 0) {
if (! $result [0]) {
$start = 0;
} else {
// 负数页数 换算读取位置
$start = (ceil ( $result [0] / $offset ) - abs ( $start )) * $offset; // 按
}
}
$this->db->limit ( $start, $offset );
$result [1] = $this->db->get ();
return $result;
}
// 首页的今日头条团购
function getone($city_id = null) {
$start = strtotime ( date ( 'Y-m-d', $this->global ['timestamp'] ) );
$endtime = strtotime ( date ( 'Y-m-d', $this->global ['timestamp'] ) );
$this->db->from ( $this->table );
$this->db->where_less ( 'starttime', $start );
$this->db->where_more ( 'endtime', $endtime );
// 状态正常
$this->db->where ( 'status', '1' );
$this->db->order_by ( array (
'listorder' => 'ASC'
) );
$this->db->limit ( 0, 1 );
$result = $this->db->get_one ();
return $result;
}
// 往期团购(非采集)
function deals($where = array(), $offset = 24) {
$this->db->select ( 'id,subject,picture,price,market_price,starttime,endtime,sname,area,url,catname,intro,webname,listorder,senddate,status' );
$this->db->from ( $this->table );
// 状态过期
$this->db->where ( 'status', '4' );
$this->db->where ( 'checked', '1' );
if ($where)
$this->db->where ( $where );
$result = array (
0,
'',
''
);
if ($result [0] = $this->db->count ()) {
$this->db->sql_roll_back ( 'from,where' );
$this->db->select ( 'id,catname,city_id,sid,mode,subject,picture,thumb,price,prices,total_price,market_price,real_price,goods_total,goods_sell,goods_min,people_buylimit,peoples_sell,peoples_min,starttime,endtime,succeedtime,expiretime,status' );
$this->db->order_by ( 'listorder' );
$this->db->limit ( get_start ( $_GET ['page'], $offset ), $offset );
$result [1] = $this->db->get ();
$result [2] = multi ( $result [0], $offset, $_GET ['page'], url ( "tuandh/deals/page/_PAGE_" ) );
}
return $result;
}
// 团购列表(非采集)
function getlist($caid, $start, $offset) {
$this->db->from ( $this->table );
if ($catname > 0)
$this->db->where ( 'catname', $catname );
$result = array (0,'' );
if ($result [0] = $this->db->count ()) {
$this->db->sql_roll_back ( 'from,where' );
$this->db->select ( 'id,subject,picture,price,market_price,starttime,endtime,sname,area,url,catname,intro,webname,listorder,senddate,status,uid' );
$this->db->order_by ( 'listorder' );
$this->db->limit ( $start, $offset );
$result [1] = $this->db->get ();
}
return $result;
}
// 团购列表(采集)
function getlist2($flag, $catid, $aid, $start, $offset) {
$this->db->where ('city_id',8);
if ($catid>0&&$catid<6){
// $this->db->where ('catid',$catid);
}
elseif($catid>5){
// $this->db->where ('catid1',$catid);
}
/*
if (!empty($aid)){
$this->db->where_like ('areaname','%'.$aid.'%');
}
*/
// 今日团购
$today = strtotime ( date ( 'Y-m-d', $this->global ['timestamp'] ) );
if ($flag == '1') {
$this->db->where_less ( 'starttime', time() );
$this->db->where_more ( 'endtime', time() );
}
// 往期团购
if ($flag == '2') {
$this->db->where_more ( 'starttime', $today );
}
// 品质团购
if ($flag == '3') {
$start = strtotime ( date ( 'Y-m-d', $this->global ['timestamp'] ) );
$endtime = strtotime ( date ( 'Y-m-d', $this->global ['timestamp'] ) );
$this->db->where_more ( 'starttime', $start );
$this->db->where_less ( 'endtime', $endtime );
}
// 结果检索
$result = array (0,'' );
//$table = 'dbpre_tuan_tgsite';
$this->db->from ( $this->table, 's' );
//$this->db->join ( 's.catid', 'dbpre_tuan_category', 'cat.catid', 'LEFT JOIN' );
//$this->db->join ( $this->table, 's.siteid', $table, 'site.id', 'LEFT JOIN' );
//$this->db->join_together ( 's.catid', 'dbpre_category', 'cat.catid', 'LEFT JOIN' );
//$this->db->join_together ( 's.aid', 'dbpre_area', 'area.aid', 'LEFT JOIN' );
if ($result [0] = $this->db->count ()) {
$this->db->sql_roll_back('from,where');
$this->db->select ( 's.id,s.catname,s.catname1,s.subject,s.picture,s.price,s.market_price,s.starttime,s.endtime,
s.url,s.sitename' );
//$this->db->select ( 'area.name as areaname' );
//$this->db->select ( 'cat.name as catname' );
//$this->db->select ( 'site.sitename' );
$this->db->order_by ( array ('s.starttime' => 'DESC' ) );
$this->db->limit ( $start, $offset );
$result [1] = $this->db->get ();
}
return $result;
}
// 新建团购
function save($post, $tid) {
$edit = $tid != null;
if ($edit) {
if (! $detail = $this->read ( $tid ))
redirect ( 'tuan_empty' );
} else {
$post ['status'] = '1';
if (! $this->in_admin) {
$post ['uid'] = $this->global ['user']->uid;
$post ['username'] = $this->global ['user']->username;
}
}
// 时间转换
$post ['starttime'] && $post ['starttime'] = strtotime ( $post ['starttime'] );
$post ['endtime'] && $post ['endtime'] = strtotime ( $post ['endtime'] ) + (24 * 3600 - 1);
if ($edit && isset ( $post ['endtime'] ) && $post ['endtime'] >= $this->global ['timestamp']) {
$post ['status'] = '1';
}
$post ['datetime'] = $this->timestamp;
$tid = parent::save ( $post, $edit ? $detail : $tid );
}
// 删除
function delete($tids) {
$ids = parent::get_keyids ( $tids );
// 删除其他关联表
$C = & $this->loader->model ( 'tuandh:coupon' );
$C->delete_tids ( $ids );
$O = & $this->loader->model ( 'tuandh:order' );
$O->delete_tids ( $ids );
// 删除团购
parent::delete ( $ids );
}
// 更新
function update($post) {
if (! $post)
return;
foreach ( $post as $tid => $val ) {
$this->db->from ( $this->table );
$this->db->where ( 'tid', $tid );
$this->db->set ( $val );
$this->db->update ();
}
}
// 提交检测
function check_post(& $post, $edit = false) {
$this->loader->helper ( 'validate' );
return $post;
}
// 状态更新
function update_status($tid = null, $status = 'new') {
}
// 计划检测更新状态
function plan_status($tid = null) {
$endtime = strtotime ( date ( 'Y-m-d', $this->global ['timestamp'] ) ) - 1;
$this->db->from ( $this->table, '', ! $tid ? 'FORCE INDEX(plan)' : '' );
$this->db->select ( 'tid,goods_total,goods_sell,goods_min,people_buylimit,peoples_sell,peoples_min,succeedtime,endtime' );
if ($tid > 0) {
$this->db->where ( 'tid', $tid );
$this->db->where ( 'status', 'new' );
}
if (! $tid) {
$this->db->where_less ( 'endtime', $endtime );
$this->db->where ( 'status', 'new' );
$this->db->where ( 'city_id', array (
0,
$this->global ['city'] ['aid']
) );
}
if (! $q = $this->db->get ())
return;
$uptids = $succeeded = array ();
while ( $v = $q->fetch_array () ) {
// 时间到或者销售光了,就结束团购
if ($v ['endtime'] <= $endtime || $v ['goods_total'] <= $v ['goods_sell']) {
$uptids [] = $v ['tid'];
if ($v ['succeedtime'] > 0)
$succeeded [] = $v ['tid'];
}
}
$q->free_result ();
if ($uptids) {
$up_price_tids = array ();
foreach ( $uptids as $tid ) {
$succeed = in_array ( $tid, $succeeded );
$this->db->from ( $this->table );
$this->db->set ( 'status', $succeed ? 'succeeded' : 'lose' );
if ($v ['endtime'] > $endtime)
$this->db->set ( 'endtime', $this->global ['timestamp'] );
$this->db->where ( 'tid', $tid );
$this->db->update ();
if ($succeed)
$up_price_tids [] = $tid;
}
if ($up_price_tids) {
$this->_update_real_price ( $up_price_tids );
}
}
}
// 按指定条件统计,兼容in格式查询
function get_tuandh_total($key, $value) {
$this->db->where_in ( $key, $value );
$this->db->from ( $this->table );
return $this->db->count ();
}
//更新主题内团购数量的统计
function update_subject_tuan_num($sid,$num=1) {
if(!$sid||!$num) return;
$this->db->from('dbpre_subject');
if($num>0) $this->db->set_add('tuans',$num);
if($num<0) $this->db->set_dec('tuans',abs($num));
$this->db->where('sid',$sid);
$this->db->update();
}
function getcount($where) {
$this->db->from ( $this->table, 's' );
// $this->db->where($where);
return $this->db->count ();
}
}
?><file_sep>/templates/item/sjstyle/album.php
<?exit?>
<!--{eval
$_HEAD['title'] = $subject[name] . $subject[subname] . 的商家相册;
}-->
{template vip2_header}
<link href="{URLROOT}/img/shop/$subject[c_sjstyle]/style.css" rel="stylesheet" type="text/css" />
<!--头开始-->
<div class="header">
<div class="headerinfo">$subject[name] $subject[subname]</div>
<div class="headermeun">
<ul>
<li><div><a href="{url item/detail/id/$subject[sid]}">首页</a> </div></li>
<li><div><a href="{url item/vipabout/id/$subject[sid]}">店铺介绍</a> </div></li>
<li><div><a href="{url article/list/sid/$sid}">店铺动态</a> </div></li>
<li class="in"><div><a href="{url item/pic/sid/$subject[sid]}">店铺展示</a> </div></li>
<li><div><a href="{url product/list/sid/$sid}">产品展厅</a> </div></li>
<li><div><a href="{url coupon/list/sid/$sid}">优惠打折</a> </div></li>
<li><div><a href="{url item/vipvideo/id/$subject[sid]}">视频展播</a> </div></li>
<li><div><a href="{url item/vipcontact/id/$subject[sid]}">联系方式</a> </div></li>
</ul>
</div>
</div>
<!--头结束-->
<!--头部flash-->
<!--{if $subject[c_pictop1]}-->
<div style="margin:0 auto; width:976px;">
<SCRIPT src="{URLROOT}/img/shop/js/swfobject_source.js" type=text/javascript></SCRIPT>
<DIV id=flashFCI><A href="#" arget=_blank><IMG alt="" border=0></A></DIV>
<SCRIPT type=text/javascript>
var s1 = new SWFObject("{URLROOT}/img/shop/js/focusFlash_fp.swf", "mymovie1", "976", "150", "5", "#ffffff");
s1.addParam("wmode", "transparent");
s1.addParam("AllowscriptAccess", "sameDomain");
s1.addVariable("bigSrc", "$subject[c_pictop1]{if $subject[c_pictop2]}|$subject[c_pictop2]{/if}{if $subject[c_pictop3]}|$subject[c_pictop3]{/if}");
s1.addVariable("smallSrc", "|$subject[c_pictop1]|||");
s1.addVariable("href", "||");
s1.addVariable("txt", "||");
s1.addVariable("width", "976");
s1.addVariable("height", "150");
s1.write("flashFCI");
</SCRIPT>
</div>
<!--{/if}-->
<!--end头部flash-->
<div class="content">
<div class="pagejc">
<div class="col1">
<div class="titles">
<div class="fl">基本信息</div>
<div class="fr"></div>
<div class="clear"></div>
</div>
<div class="neirongs" style="padding:10px;">
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td align="center" valign="middle">
<a href="{url item/pic/sid/$subject[sid]}"><img src="{URLROOT}/{if $subject[thumb]}$subject[thumb]{else}static/images/noimg.gif{/if}" alt="$subject[name]" width="200" height="150" /></a>
</td>
</tr>
</table>
<div class="lefttitle">$subject[name]</div>
<div class="leftnr">
管 理 者:
<!--{if $subject[owner]}-->
<a href="{url space/index/username/$subject[owner]}" target="_blank">$subject[owner]</a>
<!--{elseif $catcfg[subject_apply]}-->
<a href="{url item/member/ac/subject_apply/sid/$subject[sid]}"><font color="#cc0000"><b>认领$model[item_name]</b></font></a>
<!--{/if}-->
<!--{if $catcfg[use_subbranch]}-->
<a href="{url item/member/ac/subject_add/subbranch_sid/$subject[sid]}">添加分店</a>
<!--{/if}--><br />
<!--{if $subject[finer]}-->
店铺级别:<img src="{URLROOT}/img/shop/eshop/vip$subject[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<table class="custom_field" border="0" cellspacing="0" cellpadding="0">
$subject_custom_field
</table>
</div>
</div>
<div class="mq"></div>
</div> <!--col1end-->
<div class="col2">
<div class="titleb"><div class="fl">$subject[name] $subject[subname]全部相册列表</div><div class="fr"><span class="update-img-ico"><a href="{url item/member/ac/pic_upload/sid/$sid}">上传图片</a></span></div></div>
<div class="neirongb">
<div id="pic" >
<div class="multipage">$multipage</div>
<div class="pic_display">
{dbres $list $val}
<div class="pic">
<a href="{url item/album/id/$val[albumid]}"> <img src="$val[thumb]" alt="最后更新日期:{date $val[lastupdate],'Y年-m月-d日'}"/></a>
</div>
<p>加盟商家名称:<a href="{url item/album/id/$val[albumid]}">{sublen $val[name],9}</a></p>
<p>本相册照片数量:$val[num] 张</p>
<p>本相册最后更新:{date $val[lastupdate],'Y-m-d'}</p>
{/dbres}
</div>
</div>
</div>
</div><!--col2-->
<div class="clear"></div>
</div><!--pagejc-->
</div><!--content-->
</div><!--wrapper-->
{template vip2_footer}
<file_sep>/core/modules/fenlei/admin/templates/config.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');?>
<div id="body">
<?=form_begin(cpurl($module,$act))?>
<div class="space">
<div class="subtitle"><?=$MOD['name']?> - 参数设置</div>
<ul class="cptab">
<li class="selected" id="btn_config1"><a href="#" onclick="tabSelect(1,'config');" onfocus="this.blur()">功能设置</a></li>
<li id="btn_config2"><a href="#" onclick="tabSelect(2,'config');" onfocus="this.blur()">搜索引擎优化</a></li>
</ul>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" id="config1">
<tr>
<td class="altbg1"><strong>分类信息使用置顶和变色的积分类型:</strong>设置用户分类信息在列表页进行置顶和变色时花费时使用的积分类型</td>
<td>
<select name="modcfg[pointtype]">
<option value="">选择积分类型</option>
<?=form_member_pointgroup($modcfg['pointtype'])?>
</select>
</td>
</tr>
<tr>
<td class="altbg1"><strong>启用购买信息置顶功能:</strong>可以允许用户通过积分购买信息的置顶功能</td>
<td>
<?=form_bool('modcfg[buy_top]',$modcfg['buy_top'])?>
</td>
</tr>
<tr>
<td class="altbg1" valign="top"><strong>列表页信息置顶天数和积分:</strong>设定信息在列表置顶<br /><span class="font_1">格式:置顶天数|积分,一行一个</span></td>
<td>
<textarea name="modcfg[top_days]" rows="5" cols="50"><?=$modcfg['top_days']?></textarea>
</td>
</tr>
<tr>
<td class="altbg1" valign="top"><strong>列表页信息置顶积分基数:</strong>设置3中置顶类型的积分技术,设置分数×置顶类型基数得出最后需要花费的积分;比如置顶天数是7|10(置顶7天,10个积分),用户选择全局置顶,后台设定全局置顶的基数是3,那么这条信息全局置顶7天需要花费的积分则是10×3=30分。<br /><span class="font_1">共三种置顶类型,用逗号分隔,“全局置顶,大分类置顶,子分类置顶”,例如:3,2,1</span></td>
<td>
<?=form_input('modcfg[top_level]',$modcfg['top_level'],'txtbox2')?>
</td>
</tr>
<tr>
<td class="altbg1"><strong>启用购买信息变色功能:</strong>可以允许用户通过积分购买信息的变色功能</td>
<td>
<?=form_bool('modcfg[buy_color]',$modcfg['buy_color'])?>
</td>
</tr>
<tr>
<td class="altbg1" valign="top"><strong>列表页信息变色时间和积分:</strong>设置信息在列表页的高亮的时间和花费的积分<br /><span class="font_1">格式:变色天数|积分,一行一个</span></td>
<td>
<textarea name="modcfg[color_days]" rows="5" cols="50"><?=$modcfg['color_days']?></textarea>
</td>
</tr>
<tr>
<td class="altbg1" valign="top"><strong>设置变色时所能使用的颜色:</strong>颜色使用16进制值表示,多个请用逗号分隔<br /><span class="font_1">例如:#ff0000,#ffcc00,#330000</span></td>
<td>
<?=form_input('modcfg[colors]',$modcfg['colors'],'txtbox2')?>
</td>
</tr>
<tr>
<td class="altbg1" width="45%"><strong>仅店主可关联自身商铺:</strong>设置关联商铺功能,是否只允许店主关联自己的店铺,否表示自由关联</td>
<td width="*">
<?=form_bool('modcfg[post_item_owner]',$modcfg['post_item_owner'],'txtbox')?>
</td>
</tr>
<tr>
<td class="altbg1"><strong>发布信息验证码:</strong>在前台发布分类信息时,要求登记者填写验证码。</td>
<td>
<?=form_bool('modcfg[post_seccode]',$modcfg['post_seccode'])?>
</td>
</tr>
<tr>
<td class="altbg1"><strong>启用发布验证:</strong>用户发布分类信息后,需由管理员审核后方可显示。</td>
<td>
<?=form_bool('modcfg[post_check]',$modcfg['post_check'])?>
</td>
</tr>
<tr>
<td class="altbg1" valign="top"><strong>发布信息须知:</strong>在发布分类信息时,侧边的提示说明文字。</td>
<td>
<textarea name="modcfg[post_des]" rows="5" cols="50"><?=$modcfg['post_des']?></textarea>
</td>
</tr>
<tr>
<td class="altbg1"><strong>允许已关联主题的分类信息使用主题风格:</strong>对已经关联了主题的分类信息(列表和内容),采用主题设置的主题风格。</td>
<td><?=form_bool('modcfg[use_itemtpl]', $modcfg['use_itemtpl'])?></td>
</tr>
<!--
<tr>
<td class="altbg1"><strong>游客发布:</strong>是否允许游客发布分类信息</td>
<td>
<input type="radio" name="modcfg[post_guest]" value="1"<?if($modcfg['post_guest'])echo' checked';?> />是
<input type="radio" name="modcfg[post_guest]" value="0"<?if(!$modcfg['post_guest'])echo' checked';?> />否
</td>
</tr>
-->
</table>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" id="config2" style="display:none;">
<tr>
<td class="altbg1" width="45%"><strong>Meta Keywords:</strong>Keywords 项出现在页面头部的 Meta 标签中,用于记录本页面的关键字,多个关键字间请用半角逗号 "," 隔开</td>
<td width="*"><input type="text" name="modcfg[meta_keywords]" value="<?=$modcfg['meta_keywords']?>" class="txtbox" /></td>
</tr>
<tr>
<td class="altbg1"><strong>Meta Description:</strong>Description 出现在页面头部的 Meta 标签中,用于记录本页面的概要与描述</td>
<td><input type="text" name="modcfg[meta_description]" value="<?=$modcfg['meta_description']?>" class="txtbox" /></td>
</tr>
</table>
<center><button type="submit" name="dosubmit" value="yes" class="btn" /> 提交 </button></center>
</div>
</form>
</div><file_sep>/core/modules/item/admin/templates/delivery_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/item.js"></script>
<div id="body">
<form method="post" name="myform" action="<?=cpurl($module,$act,$op)?>" onsubmit="return checkdata();">
<div class="space">
<div class="subtitle">编辑外卖信息</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1" width="150">外卖分类:</td>
<td width="*">
<select name="c_types">
<?=form_item_atts('3',$detail['c_types']);?>
</select>
</td>
</tr>
<tr>
<td class="altbg1" width="150">订餐方式:</td>
<td width="*">
<?=form_check('c_book',array('电话订餐','在线订餐'),$detail['c_book'])?>
</td>
</tr>
<tr>
<td class="altbg1" width="150">支付方式:</td>
<td width="*">
<?=form_check('c_payment',array('在线支付','货到付款'),$detail['c_payment'])?>
</td>
</tr>
<tr>
<td class="altbg1" width="150">送餐方式:</td>
<td width="*">
<?=form_check('c_deliver',array('商家自送','专业配送'),$detail['c_deliver'])?>
</td>
</tr>
<tr>
<td class="altbg1" width="150">起送价格:</td>
<td width="*"><input type="text" class="txtbox2" name="c_minprice" value="<?=$detail['c_minprice']?>"/></td>
</tr>
<tr>
<td class="altbg1" width="150">送餐费用:</td>
<td width="*"><input type="text" class="txtbox2" name="c_freight" value="<?=$detail['c_freight']?>"/></td>
</tr>
<tr>
<td class="altbg1" width="150">打包费用:</td>
<td width="*"><input type="text" class="txtbox2" name="c_pack" value="<?=$detail['c_pack']?>"/></td>
</tr>
<tr>
<td class="altbg1" width="150">配送范围:</td>
<td width="*">
<input type="text" class="txtbox2" id="c_range" name="c_range" value="<?=$detail['c_range']?>" readonly="readonly" onclick="popdivs()"/>
</td>
</tr>
<tr>
<td class="altbg1" width="150">商家公告:</td>
<td width="*">
<textarea name="c_content" style="height:100px; width:600px;"><?=$detail['c_content']?></textarea></td>
</td>
</tr>
</table>
</div>
<center>
<input type="hidden" name="sid" value="<?=$detail['sid']?>" />
<input type="hidden" id="book" name="book" value="" />
<input type="hidden" id="payment" name="payment" value="" />
<input type="hidden" id="deliver" name="deliver" value="" />
<?=form_submit('dosubmit',lang('global_submit'),'yes','btn')?>
<?=form_button_return(lang('global_return'),'btn')?>
</center>
</form>
</div>
<script type="text/javascript">
//加载地区信息
function popdivs(){
load_threeareas(9);
}
function checkdata(){
$("#book").val(getchecked('c_book'));
$("#payment").val(getchecked('c_payment'));
$("#deliver").val(getchecked('c_deliver'));
return true;
}
</script><file_sep>/core/modules/coupon/install/module_uninstall.sql
DROP TABLE IF EXISTS modoer_coupon_category;
DROP TABLE IF EXISTS modoer_coupons;
DROP TABLE IF EXISTS modoer_coupon_print;<file_sep>/core/modules/fenlei/admin/category.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$C =& $_G['loader']->model('fenlei:category');
$_G['loader']->helper('form','fenlei');
$op = _input('op');
switch($op) {
case 'add':
$pid = (int)_get('pid',0);
$admin->tplname = cptpl('category_save', MOD_FLAG);
break;
case 'edit':
if(!$catid = (int)_get('catid',0)) redirect(lang('global_sql_keyid_invalid','catid'));
if(!$detail = $C->read($catid)) redirect('fenlei_category_empty');
$catgory = $C->variable('category');
$pid = $catgory[$detail['catid']]['pid'];
$admin->tplname = cptpl('category_save', MOD_FLAG);
break;
case 'save':
$catid = _post('catid');
$C->save(_post('category'), $catid);
redirect('global_op_succeed', get_forward(cpurl($module,$act),1));
break;
case 'delete':
if(!$catid = (int)_input('catid')) redirect(lang('global_sql_keyid_invalid','catid'));
$C->delete($catid);
redirect('global_op_succeed', cpurl($module,$act));
break;
case 'update':
$C->update(_post('category'));
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
default:
$pid = (int)_get('pid',0);
$list = $C->read_all($pid);
$admin->tplname = cptpl('category_list', MOD_FLAG);
}
?><file_sep>/templates/item/sjstyle/product_detail.php
<?exit?>
<!--{eval
$_HEAD['title'] = $subject['name'].$subject['subname'] . '的产品' . ($catid ? $_CFG['titlesplit'] . $category[$catid]['name'] : '');
}-->
{template vip2_header}
<link href="{URLROOT}/img/shop/$subject[c_sjstyle]/style.css" rel="stylesheet" type="text/css" />
<link href="{URLROOT}/img/shop/eshop/detail.css" rel="stylesheet" type="text/css" />
<!--头开始-->
<div class="header">
<div class="headerinfo">$subject[name] $subject[subname]</div>
<div class="headermeun">
<ul>
<li><div><a href="{url item/detail/id/$subject[sid]}">首页</a> </div></li>
<li><div><a href="{url item/vipabout/id/$subject[sid]}">店铺介绍</a> </div></li>
<li><div><a href="{url article/list/sid/$subject[sid]}">店铺动态</a> </div></li>
<li><div><a href="{url item/pic/sid/$subject[sid]}">店铺展示</a> </div></li>
<li class="in"><div><a href="{url product/list/sid/$subject[sid]}">产品展厅</a> </div></li>
<li><div><a href="{url coupon/list/sid/$subject[sid]}">优惠打折</a> </div></li>
<li><div><a href="{url item/vipvideo/id/$subject[sid]}">视频展播</a> </div></li>
<li><div><a href="{url item/vipcontact/id/$subject[sid]}">联系方式</a> </div></li>
</ul>
</div>
</div>
<!--头结束-->
<!--头部flash-->
<!--{if $subject[c_pictop1]}-->
<div style="margin:0 auto; width:976px;">
<SCRIPT src="{URLROOT}/img/shop/js/swfobject_source.js" type=text/javascript></SCRIPT>
<DIV id=flashFCI><A href="#" arget=_blank><IMG alt="" border=0></A></DIV>
<SCRIPT type=text/javascript>
var s1 = new SWFObject("{URLROOT}/img/shop/js/focusFlash_fp.swf", "mymovie1", "976", "150", "5", "#ffffff");
s1.addParam("wmode", "transparent");
s1.addParam("AllowscriptAccess", "sameDomain");
s1.addVariable("bigSrc", "$subject[c_pictop1]{if $subject[c_pictop2]}|$subject[c_pictop2]{/if}{if $subject[c_pictop3]}|$subject[c_pictop3]{/if}");
s1.addVariable("smallSrc", "|$subject[c_pictop1]|||");
s1.addVariable("href", "||");
s1.addVariable("txt", "||");
s1.addVariable("width", "976");
s1.addVariable("height", "150");
s1.write("flashFCI");
</SCRIPT>
</div>
<!--{/if}-->
<!--end头部flash-->
<div class="content">
<div class="pagejc">
<div class="col1">
<div class="titles">
<div class="fl">基本信息</div>
<div class="fr"></div>
<div class="clear"></div>
</div>
<div class="neirongs" style="padding:10px;">
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td align="center" valign="middle">
<a href="{url item/pic/sid/$subject[sid]}"><img src="{URLROOT}/{if $subject[thumb]}$subject[thumb]{else}static/images/noimg.gif{/if}" alt="$subject[name]" width="200" height="150" /></a>
</td>
</tr>
</table>
<div class="lefttitle">$subject[name]</div>
<div class="leftnr">
管 理 者:
<!--{if $subject[owner]}-->
<a href="{url space/index/username/$subject[owner]}" target="_blank">$subject[owner]</a>
<!--{elseif $catcfg[subject_apply]}-->
<a href="{url item/member/ac/subject_apply/sid/$subject[sid]}"><font color="#cc0000"><b>认领$model[item_name]</b></font></a>
<!--{/if}-->
<!--{if $catcfg[use_subbranch]}-->
<a href="{url item/member/ac/subject_add/subbranch_sid/$subject[sid]}">添加分店</a>
<!--{/if}--><br />
<!--{if $subject[finer]}-->
店铺级别:<img src="{URLROOT}/img/shop/eshop/vip$subject[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<!--{if $subject[c_dianhua]}-->
电 话:$subject[c_dianhua]<br />
<!--{/if}-->
<!--{if $subject[c_wangzhi]}-->
网 址:$subject[c_wangzhi]<br />
<!--{/if}-->
<!--{if $subject[c_dizhi]}-->
店铺地址:$subject[c_dizhi]<br />
<!--{/if}-->
<!--{if $subject[c_gongjiao]}-->
公交线路:$subject[c_gongjiao]<br />
<!--{/if}-->
<!--{if $subject[c_tingche]}-->
停车状况:$subject[c_tingche]<br />
<!--{/if}-->
<!--{if $subject[c_shijian]}-->
营业时间:$subject[c_shijian]<br />
<!--{/if}-->
访 问 量:<span class="font_2">$subject[pageviews]</span>次浏览<br />
<!--{if $subject[c_qqkey]}-->
在线交流:
<a target="_blank" href="http://wpa.qq.com/msgrd?v=1&uin=$subject[c_qqkey]&site=qq&menu=yes"><img src="http://wpa.qq.com/pa?p=2:$subject[c_qqkey]:41" alt="点击这里给我发消息" border="0" align="absmiddle" title="点击这里给我发消息"></a><br />
<!--{/if}-->
加盟时间:{date $subject[addtime],'Y-m-d'} <br /><br />
<script type="text/javascript">loadscript('item');</script>
<a href="javascript:post_log($subject[sid]);"><img src="{URLROOT}/img/shop/other/bc_botton.gif" height="28" width="100"/></a>
<a href="javascript:add_favorite($subject[sid]);"><img src="{URLROOT}/img/shop/other/sc_botton.gif" height="28" width="72"/></a><br />
</div>
</div>
<div class="mq"></div>
</div> <!--col1end-->
<div class="col2">
<div class="titleb">
<div class="fl">商家产品</div>
<div class="fr"></div>
</div>
<div class="neirongb">
<div id="product_left">
<h1 class="title">$detail[subject]</h1>
<p class="t">发布时间:{date $detail[subject]}
人气:<span class="font_2">$detail[pageview]</span>
评论:<span class="font_2">$detail[comments]</span></p>
<div class="info">
<div class="field">
<table class="detail_field" border="0" cellspacing="0" cellpadding="0">
$detail_field
</table>
</div>
<div class="thumb">
<img src="{URLROOT}/$detail[thumb]" />
</div>
<div class="clear"></div>
</div>
<div class="content">
<h3>详细介绍:</h3>
<p class="c">$detail[content]</p>
</div>
<!--{if check_module('comment')}-->
<div class="comment_foo">
<style type="text/css">@import url("{URLROOT}/{$_G[tplurl]}css_comment.css");</style>
<script type="text/javascript" src="{URLROOT}/static/javascript/comment.js"></script>
<!--{eval $comment_modcfg = $_G['loader']->variable('config','comment');}-->
<!--{if $detail[comments]}-->
<!--{/if}-->
<a name="comment"></a>
<h3>网友评论:</h3>
{eval $_G['loader']->helper('form');}
<div id="comment_form">
<!--{if $user->check_access('comment_disable', $_G['loader']->model(':comment'), false)}-->
<!--{if $MOD[post_comment] && !$comment_modcfg['disable_comment'] && !$detail[closed_comment]}-->
<!--{eval $idtype = 'product'; $id = $pid; $title = 'Re:' . $detail[subject];}-->
{template comment_post}
<!--{else}-->
<div class="messageborder">评论已关闭</div>
<!--{/if}-->
<!--{else}-->
<div class="messageborder">如果您要进行评论信息,请先 <a href="{url member/login}">登录</a> 或者 <a href="{url member/reg}">快速注册</a> 。</div>
<!--{/if}-->
</div>
<!--{if !$comment_modcfg['hidden_comment']}-->
<div class="mainrail rail-border-3">
<em>评论总数:<span class="font_2">$detail[comments]</span>条</em>
<h1 class="rail-h-3 rail-h-bg-3">网友评论</h1>
<div id="commentlist" style="margin-bottom:10px;"></div>
<script type="text/javascript">
$(document).ready(function() { get_comment('product',$pid,1); });
</script>
</div>
<!--{/if}-->
</div>
<!--{/if}-->
</div>
</div><!--col2-->
<div class="clear"></div>
</div><!--pagejc-->
</div><!--content-->
</div><!--wrapper-->
{template vip2_footer}
<file_sep>/core/modules/member/model/profile_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @package modoer
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
class msm_member_profile extends ms_model {
public $table = 'dbpre_member_profile';
public $key = 'uid';
public $model_flag = 'member';
private $uid = 0;
private $fields = array('realname','gender','birthday','alipay','qq','tel','address','zipcode','home','work ');
private $vars = array();
public function __construct() {
parent::__construct();
}
function init_field() {
$this->add_field('realname,gender,birthday,alipay,qq,tel,address,zipcode,home,work');
$this->add_field_fun('address,realname', '_T');
$this->add_field_fun('home,work', 'intval');
$this->add_field_fun('tel', 'trim');
}
public function set_uid($uid) {
$this->uid = $uid;
return $this;
}
public function read($uid=null) {
$uid = (int) $uid;
if($uid > 0) $this->uid = $uid;
$detail = parent::read($this->uid);
if(!$detail) return false;
return $detail;
}
function save($post,$uid=null) {
$uid = parent::save($post, $uid);
return $uid;
}
}
?><file_sep>/core/modules/party/index.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'party');
$urlpath = $where = array();
$urlpath[] = url_path($MOD['name'], url("party/index"));
$PARTY = $_G['loader']->model(':party');
//更新状态
$PARTY->update_flag();
//城市
$where['city_id'] = $_CITY['aid'];
//分类
$category = $_G['loader']->variable('category','party');
if($catid = _get('catid', 0, 'intval')) {
$where['catid'] = $catid;
$urlpath[] = url_path($category[$catid]['name'], url("party/index/catid/$catid"));
}
if($catid == 0) unset($catid);
//显示模式
$type = _get('type', $MOD['index_type']);
if($type != 'calendar') $type = 'normal';
//时间
$time_arr = lang('party_time');
if($time = _get('time', 0, 'intval')) {
if($type!='calendar') {
if(!$where['begintime'] = party_index_create_time($time)) {
unset($where['begintime']);
}
if(strlen($time)==8) {
$urlpath[] = url_path($time, url("party/index/catid/$catid/time/$time"));
$selecttime = $time;
} else {
$urlpath[] = url_path($time_arr[$time], url("party/index/catid/$catid/time/$time"));
}
}
}
if($time == 0) unset($time);
//排序
$orderby = array(
'new' => array('dateline'=>'DESC'),
'hot' => array('pageview'=>'DESC'),
);
$order = _get('order', 'hot');
if($order != 'new') $order = 'hot';
//状态
$flag = _get('flag',0,'intval');
if($flag<0 || $flag>3) $flag = 0;
if($flag == 0) {
unset($flag);
} else {
$where['flag'] = $flag;
}
//审核
$where['status'] = 1;
$select = 'partyid,subject,thumb,joinendtime,begintime,endtime,num,address,aid,catid,address,sid,flag,des';
if($type=='calendar') { //日历
$calendar = party_index_create_calendar($time);
$where['begintime'] = array('where_less', array($calendar['endtime']));
$where['endtime'] = array('where_more', array($calendar['datetime']));
$list = $PARTY->calendar($select, $where);
} else { //图文列表
$offset = $MOD['listnum']>0?$MOD['listnum']:10;
$start = get_start($_GET['page'], $offset);
list($total, $list) = $PARTY->find($select, $where, $orderby[$order], $start, $offset, TRUE);
if($total) $multipage = multi($total, $offset, $_GET['page'], url("party/index/catid/$catid/time/$time/type/$type/order/$order/flag/$flag/page/_PAGE_"));
}
//高亮
$active['catid'][(int)$catid] = ' class="selected"';
$active['time'][(int)$time] = ' class="selected"';
$active['type'][$type] = ' class="selected"';
$active['order'][$order] = ' class="selected"';
$active['flag'][(int)$flag] = ' class="selected"';
//SEO
$_HEAD['keywords'] = $MOD['meta_keywords'];
$_HEAD['description'] = $MOD['meta_description'];
include template('party_index');
function party_index_create_time($time) {
global $_G;
$begintime = mktime(0,0,0,date('m',$_G['timestamp']),date('d',$_G['timestamp']),date('Y',$_G['timestamp']));
if($time == 1) {
$endtime = $begintime + (24*3600-1);
} elseif($time == 2) {
$begintime += 24*3600;
$endtime = $begintime + (24*3600-1);
} elseif($time == 3) {
$endtime = $begintime + (24*3600*6-1);
} else if($time == 4) {
$endtime = $begintime + (24*3600*30-1);
} elseif(strlen($time) == 8) {
$begintime = strtotime($time);
$endtime = $begintime + (24*3600-1);
}
return array('where_between_and', array($begintime, $endtime));
}
function party_index_create_calendar($date) {
global $_G;
if(strlen($date) > 6) $date = substr($date,0,6);
if(!$datetime = strtotime($date.'01')) $date = '';
if(!$date) $datetime = mktime(0,0,0,date('m',$_G['timestamp']),1,date('Y',$_G['timestamp']));
//取得当月天数
$days = date('t',$datetime);
//1号是星期几
$weeks = array(0=>'Sunday',1=>'Monday',2=>'Tuesday',3=>'Wednesday',4=>'Thursday',5=>'Friday',6=>'Saturday');
$week = array_search(date('l', $datetime), $weeks);
$end = array_search(date('l', $datetime+(($days-1)*24*3600)), $weeks);
$result = array(
'datetime' => $datetime,
'endtime' => $datetime + ($days*24*3600-1),
'days' => $days,
'week' => $week,
'year' => date('Y',$datetime),
'month' => date('n',$datetime),
'forward' => date('Ym', $datetime - 24*3600) . '01',
'next' => date('Ymd', $datetime + ($days*24*3600)),
);
//日一二三四五六
$i = 0;
$c = array();
if($x = abs(0 - $week)) {
for($i=1;$i<=$x;$i++) $c[] = 0;
}
for($i=1;$i<=$days;$i++) $c[] = array($i, strtotime("{$result[year]}-{$result[month]}-{$i} 23:59:59"));
if($end != 6) {
for($i=1;$i<=(6-$end);$i++) $c[] = 0;
}
$result['list'] = $c;
return $result;
}
?><file_sep>/core/modules/modoer/item/model/subject_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
$_G ['loader']->model ( 'item:itembase', FALSE );
class msm_item_subject extends msm_item_itembase {
var $table = 'dbpre_subject';
var $key = 'sid';
var $field = null;
var $category = '';
var $model = '';
var $modcfg = '';
var $style = null;
function __construct() {
parent::__construct ();
$this->field = & $this->loader->model ( 'item:field' );
! $this->modcfg && $this->modcfg = $this->variable ( 'config', 'item' );
}
function msm_item_subject() {
$this->__construct ();
}
function init_field() {
// 处理为在后台管理的默认字段
parent::add_field ( 'domain,aid,pid,catid,avgsort,sort1,sort2,sort3,sort4,sort5,sort6,sort7,sort8,avgprice,best,reviews,
guestbooks,pictures,pageviews,level,finer,owner,cuid,creator,addtime,video,thumb,status,mappoint,description' );
parent::add_field_fun ( 'aid,avgprice,best,reviews,guestbooks,pictures,pageviews,level,finer,cuid,addtime,status', 'intval' );
parent::add_field_fun ( 'sort1,sort2,sort3,sort4,sort5,sort6,sort7,sort8,avgsort', 'floatval', 'fullname' );
parent::add_field_fun ( 'domain,thumb', '_T' );
}
// 取得主题信息
function read($key, $select = '*', $read_field = TRUE, $is_domain = FALSE) {
if (! $key) {
redirect ( lang ( 'global_sql_keyid_invalid', 'sid' ) );
}
$result = '';
$this->db->from ( $this->table );
if ($is_domain) {
$this->db->where ( 'domain', $key );
} else {
$this->db->where ( 'sid', $key );
}
$this->db->select ( $select );
if ($read_field && $select != '*' && ! strposex ( $read_field, 'catid' )) {
$this->db->select ( 'catid' );
}
if (! $result = $this->db->get_one ()) {
return $result;
}
$sid = $result ['sid'];
// 坐标字段处理
if (! num_empty ( $result ['map_lng'] ) && ! num_empty ( $result ['map_lat'] )) {
$result ['mappoint'] = $result ['map_lat'] . ',' . $result ['map_lng'];
} else {
$result ['mappoint'] = '';
}
// 读取附表信息
$result_field = array ();
if ($read_field) {
$result_field = $this->read_field ( $sid, $result ['catid'] );
}
if ($result_field) {
$result = array_merge ( $result, $result_field );
}
return $result;
}
function read_bysid($sid) {
$this->db->from ( $this->table );
$this->db->where ( 'sid', $sid );
$this->db->where ( 'status', 1 );
$this->db->limit ( 0, 1 );
return $this->db->get_one ();
}
function read_byname($name) {
$this->db->from ( $this->table );
$this->db->where ( 'fullname', $name );
$this->db->where ( 'status', 1 );
$this->db->limit ( 0, 1 );
return $this->db->get_one ();
}
function read_random($where = null) {
$this->db->from ( $this->table );
if ($where)
$this->db->where ( $where );
$this->db->where ( 'status', 1 );
$this->db->order_by ( 'rand()' );
$this->db->limit ( 0, 1 );
return $this->db->get_one ();
}
// 取得附表数据
function read_field($sid, $catid, $select = '*') {
$this->get_category ( $catid );
$this->get_model ( $this->category ['modelid'] );
$table = 'dbpre_' . $this->model ['tablename'];
$this->db->from ( $table );
$this->db->where ( 'sid', $sid );
$this->db->select ( $select );
$result = $this->db->get_one ();
return $result;
}
function getcount($where) {
$atts = $where ['attid'];
unset ( $where ['attid'] );
$this->db->from ( $this->table, 's' );
if ($atts) {
$attlist = array_values ( $atts );
$num = count ( $attlist );
foreach ( $attlist as $attid ) {
$this->db->where_exist ( "SELECT 1 FROM dbpre_subjectatt st WHERE s.sid=st.sid AND attid=$attid" );
}
}
$this->db->where ( $where );
return $this->db->count ();
}
// 列表页查询(带分页)
function getlist($pid, $select, $where, $orderby, $start, $offset, $total = TRUE) {
$result = array (
0,
''
);
if ($total) {
$result [0] = $this->getcount ( $where );
}
$atts = $where ['attid'];
unset ( $where ['attid'] );
$this->get_category ( $pid );
$this->get_model ( $this->category ['modelid'] );
$table = 'dbpre_' . $this->model ['tablename'];
$this->db->join ( $this->table, 's.sid', $table, 'sf.sid', 'LEFT JOIN' );
if ($atts) {
$attlist = array_values ( $atts );
$num = count ( $attlist );
foreach ( $attlist as $attid ) {
$this->db->where_exist ( "SELECT 1 FROM dbpre_subjectatt st WHERE s.sid=st.sid AND attid=$attid" );
}
}
$this->db->where ( $where );
$this->db->select ( $select ? $select : '*' );
$this->db->order_by ( $orderby );
if ($offset > 0)
$this->db->limit ( $start, $offset );
$result [1] = $this->db->get ();
return $result;
}
// 列表页查询(外卖)
function getlist1($pid, $select, $where, $orderby, $start, $offset, $total = TRUE) {
$result = array (
0,
''
);
if ($total) {
$result [0] = $this->getcount ( $where );
}
$atts = $where ['attid'];
unset ( $where ['attid'] );
$this->get_category ( $pid );
$this->get_model ( $this->category ['modelid'] );
$table = 'dbpre_' . $this->model ['tablename'];
$this->db->join ( $this->table, 's.sid', $table, 'sf.sid', 'LEFT JOIN' );
if ($atts) {
$attlist = array_values ( $atts );
$num = count ( $attlist );
foreach ( $attlist as $attid ) {
$this->db->where_exist ( "SELECT 1 FROM dbpre_subjectatt st WHERE s.sid=st.sid AND attid=$attid" );
}
}
$this->db->where ( $where );
$this->db->select ( $select ? $select : '*' );
$this->db->order_by ( $orderby );
if ($offset > 0)
$this->db->limit ( $start, $offset );
$result [1] = $this->db->get ();
return $result;
}
// 筛选数据
function find($select, $where, $orderby, $start, $offset, $total = TRUE, $field_catid = NULL, $atts = NULL) {
if ($field_catid) {
$this->get_category ( $field_catid );
$this->get_model ( $this->category ['modelid'] );
$table = 'dbpre_' . $this->model ['tablename'];
$this->db->join ( $this->table, 's.sid', $table, 'sf.sid', 'JOIN' );
} else {
$this->db->from ( $this->table, 's' );
}
if ($atts) {
$attlist = array_values ( $atts );
$num = count ( $attlist );
if ($num > 1) {
$this->db->where_exist ( "SELECT 1 FROM dbpre_subjectatt st WHERE s.sid=st.sid AND attid IN (" . implode ( ',', $attlist ) . ") GROUP BY st.sid HAVING COUNT(st.sid)=$num" );
} else {
$this->db->where_exist ( "SELECT 1 FROM dbpre_subjectatt st WHERE s.sid=st.sid AND attid=" . array_pop ( $attlist ) );
}
}
if ($where ['aid']) {
$AA = & $this->loader->model ( 'area' );
$CITY_ID = $AA->get_parent_aid ( $where ['aid'] );
$area = $this->loader->variable ( 'area_' . $CITY_ID );
if (! isset ( $area [$where ['aid']] )) {
unset ( $where ['aid'] );
} else {
$area_slg = $area [$where ['aid']];
$adis = array (
( int ) $where ['aid']
);
// 条件是第二层时,需要把最后一层地区也集合
if ($area_slg ['level'] == 2) {
foreach ( $area as $key => $val ) {
if ($val ['pid'] == $where ['aid'])
$adis [] = $key;
}
$where ['aid'] = $adis;
}
unset ( $area_slg, $adis );
}
}
if ($where ['fn']) {
$keyword = $where ['fn'];
unset ( $where ['fn'] );
}
$this->db->where ( $where );
isset ( $keyword ) && $this->db->where_concat_like ( array (
'name',
'subname'
), '%' . $keyword . '%' );
$result = array (
0,
''
);
if ($total) {
if (! $result [0] = $this->db->count ()) {
return $result;
}
$this->db->sql_roll_back ( 'from,where' );
}
$this->db->select ( $select ? $select : '*' );
$this->db->order_by ( $orderby );
if ($offset > 0)
$this->db->limit ( $start, $offset );
$result [1] = $this->db->get ();
return $result;
}
// 搜索标签
function find_tag($tagid, $where, $select, $orderby, $start, $offset, $total = TRUE) {
$this->db->join ( 'dbpre_tag_data', 'td.id', $this->table, 's.sid', 'LEFT JOIN' );
$this->db->where ( 'tagid', $tagid );
$this->db->where ( $where );
$result = array (
0,
''
);
if ($total) {
if (! $result [0] = $this->db->count ()) {
return $result;
}
$this->db->sql_roll_back ( 'from,where' );
}
$this->db->select ( $select ? $select : '*' );
$this->db->order_by ( $orderby );
$this->db->limit ( $start, $offset );
$result [1] = $this->db->get ();
return $result;
}
// 搜索图片
function find_picture($where, $orderby, $start, $offset, $total = TRUE) {
$this->db->from ( $this->table );
if ($where ['aid']) {
$AA = & $this->loader->model ( 'area' );
$CITY_ID = $AA->get_parent_aid ( $where ['aid'] );
$area = $this->loader->variable ( 'area_' . $CITY_ID );
if (! isset ( $area [$where ['aid']] )) {
unset ( $where ['aid'] );
} else {
$area_slg = $area [$where ['aid']];
$adis = array (
( int ) $where ['aid']
);
if ($area_slg ['level'] == 2) {
foreach ( $area as $key => $val ) {
if ($val ['pid'] == $where ['aid']) {
$adis [] = $key;
}
}
$where ['aid'] = $adis;
}
unset ( $area_slg, $adis );
}
}
if ($where ['fn']) {
$keyword = $where ['fn'];
unset ( $where ['fn'] );
}
$this->db->where ( $where );
$this->db->where_more ( 'pictures', 1 );
$result = array (
0,
''
);
if ($total) {
if (! $result [0] = $this->db->count ()) {
return $result;
}
$this->db->sql_roll_back ( 'from,where' );
}
$this->db->select ( "sid,pid,catid,name,subname,pictures,thumb" );
$this->db->order_by ( $orderby );
$this->db->limit ( $start, $offset );
$result [1] = $this->db->get ();
return $result;
}
// 保存主题
function save($post, $sid = null) {
// 主表SQL
$main_fields = array (
'sid',
'domain',
'city_id',
'aid',
'pid',
'catid',
'sub_catids',
'minor_catids',
'name',
'subname',
'avgsort',
'sort1',
'sort2',
'sort3',
'sort4',
'sort5',
'sort6',
'sort7',
'sort8',
'avgprice',
'best',
'reviews',
'guestbooks',
'pictures',
'pageviews',
'level',
'finer',
'owner',
'cuid',
'creator',
'addtime',
'video',
'thumb',
'status',
'map_lat',
'map_lng',
'description',
'fullname'
);
if ($edit = $sid > 0) {
if (! $detail = $this->read ( $sid )) {
redirect ( 'global_op_empty' );
}
if (! $this->in_admin) {
$cfg = $this->get_category ( $detail ['pid'] );
$access_edit = $cfg ['config'] ['allow_edit_subject'] && $this->global ['user']->check_access ( 'item_allow_edit_subject', $this, false );
if (! $access_edit && $this->global ['user']->username != $detail ['owner']) {
redirect ( 'global_op_access' );
}
}
define ( 'EDIT_SID', $sid );
}
// 构造商家全名
if ($post ['subname'] != '')
$post ['fullname'] = $post ['name'] . '(' . $post ['subname'] . ')';
else
$post ['fullname'] = $post ['name'];
if (! isset ( $post ['thumb'] ))
$post ['thumb'] = '';
if (! $catid = $post ['catid'])
$catid = $post ['catid'] = $_POST ['pid'];
if (! $catid)
redirect ( 'item_cat_sub_empty' );
$this->get_category ( $catid );
// 取得主题模型数据附加表
$this->get_model ( $this->category ['modelid'] );
$table = 'dbpre_' . $this->model ['tablename'];
// 字段检测
$modelid = $this->category ['modelid'];
$data = $this->field->validator ( $modelid, $post, $sid );
$data ['pid'] = $this->category ['catid'];
// 固定字段(非自定义内)
if (isset ( $post ['domain'] ))
$data ['domain'] = $post ['domain'];
if (isset ( $post ['owner'] ))
$data ['owner'] = $post ['owner'];
if (isset ( $post ['thumb'] ))
$data ['thumb'] = _T ( $post ['thumb'] );
// 主题模板
if (isset ( $post ['templateid'] )) {
$data ['templateid'] = ( int ) $post ['templateid'];
if ($edit && ! $this->in_admin)
$post ['templateid'] = $detail ['templateid'];
}
// 主题状态
if (isset ( $post ['status'] )) {
$data ['status'] = ( int ) $post ['status'];
if ($edit && ! $this->in_admin)
$post ['status'] = $detail ['status'];
}
// 城市字段
if ($data ['aid']) {
$AREA = & $this->loader->model ( 'area' );
$data ['city_id'] = $post ['city_id'] = ( int ) $AREA->get_parent_aid ( $data ['aid'], 1 );
}
//商家全名
$data ['fullname']=$post ['fullname'];
// 检测
$this->check_post ( $data, $edit, $sid );
if (! $edit) {
! $this->in_admin && $this->global ['user']->check_access ( 'item_subjects', $this );
// 主题登记/创建者
if ($post ['cuid'] && isset ( $post ['creator'] )) {
$data ['cuid'] = $post ['cuid'];
$data ['creator'] = _T ( $post ['creator'] );
}
$data ['addtime'] = $this->global ['timestamp'];
}
if (! $edit || $data ['name'] . $data ['subname'] != $detail ['name'] . $detail ['subname']) {
if ($this->exists ( $data ['city_id'], $data ['name'], $data ['subname'], $sid )) {
redirect ( lang ( 'item_post_exists_item', $this->model ['item_name'] ) );
}
}
// 防止前台修改状态
if ($edit && ! $this->in_admin) {
unset ( $data ['status'] );
} elseif (! $edit && ! $this->in_admin) {
$data ['status'] = $this->category ['config'] ['itemcheck'] ? 0 : 1;
$data ['domain'] = '';
}
$field_post = $main_post = array ();
foreach ( $data as $keyname => $val ) {
if (in_array ( $keyname, $main_fields )) {
if (isset ( $data [$keyname] )) {
$main_post [$keyname] = $data [$keyname];
}
} else {
$field_post [$keyname] = $data [$keyname];
}
}
print_r($main_post);
// 去掉虚拟字段
$v_f = array (
'mappoint'
);
foreach ( $v_f as $v ) {
if (isset ( $field_post [$v] ))
unset ( $field_post [$v] );
}
// 隐藏字段(主表)
$i_f = array (
'sub_catids',
'minor_catids'
);
foreach ( $i_f as $v ) {
if (isset ( $post [$v] ))
$main_post [$v] = $post [$v];
}
// 附表
$i_f = array (
'forumid'
);
foreach ( $i_f as $v ) {
if (isset ( $post [$v] ))
$field_post [$v] = $post [$v];
}
// 处理sub_catids
$catids = array ();
foreach ( array (
'sub_catids',
'minor_catids'
) as $_keyid ) {
if ($main_post [$_keyid]) {
$_catids = $main_post [$_keyid];
$main_post [$_keyid] = '';
$catids = array_merge ( $catids, $_catids );
foreach ( $_catids as $_catid ) {
$main_post [$_keyid] .= '|' . $_catid;
}
$main_post [$_keyid] && $main_post [$_keyid] = $main_post [$_keyid] . '|';
unset ( $_catids );
}
}
if (! $catids)
$catids = array (
$main_post ['catid']
);
// 处理模版
if ($field_post ['templateid'] > 0 && $edit && $sid > 0) {
$ST = & $this->loader->model ( 'item:subjectstyle' );
$tpl = $ST->get_exists ( array (
'sid' => $sid,
'templateid' => $field_post ['templateid']
) );
if (empty ( $tpl ))
$field_post ['templateid'] = 0; // 不存在购买记录,则设置为 0
}
if ($edit) {
// 主表
foreach ( $main_post as $key => $val ) {
if ($val == $detail [$key])
unset ( $main_post [$key] );
}
if ($main_post) {
$this->db->from ( $this->table );
$this->db->set ( $main_post );
$this->db->where ( 'sid', $sid );
$this->db->update ();
}
// 附表
foreach ( $field_post as $key => $val ) {
if ($val == $detail [$key])
unset ( $field_post [$key] );
}
if ($field_post) {
$this->db->from ( $table );
$this->db->set ( $field_post );
$this->db->where ( 'sid', $sid );
$this->db->update ();
}
} else {
// 主表
$this->db->from ( $this->table );
$this->db->set ( $main_post );
$this->db->insert ();
$sid = $this->db->insert_id ();
// 附表
$this->db->from ( $table );
$this->db->set ( 'sid', $sid );
$this->db->set ( $field_post );
$this->db->insert ();
}
if (! $edit) {
define ( 'RETURN_EVENT_ID', $main_post ['status'] ? 'global_op_succeed' : 'global_op_succeed_check' );
} elseif ($edit) {
if ($main_post ['status'] || $detail ['status'])
define ( 'RETURN_EVENT_ID', 'global_op_succeed' );
if (! $main_post ['status'] || ! $detail ['status'])
define ( 'RETURN_EVENT_ID', 'global_op_succeed_check' );
}
// 设置管理员
if (! $edit && isset ( $main_post ['owner'] )) {
$this->set_owner ( $sid, $main_post ['owner'], '', false, false );
}
// 设置模版
if (! $edit && $field_post ['templateid'] > 0) {
$ST = & $this->loader->model ( 'item:subjectstyle' );
$ST->_addnew ( 0, $sid, $field_post ['templateid'], $this->timestamp + 30 * 24 * 3600, true ); // 提供一个月
}
// 上传的图片
if (! empty ( $_FILES ['picture'] ['name'] )) {
$P = & $this->loader->model ( 'item:picture' );
$P->save ( array (
'sid' => $sid
), TRUE, TRUE );
}
define ( 'ITEM_PID', $data ['pid'] );
$status = 0; // 是否被审核
$catid = $data ['catid'];
// 更新分类统计
if (! $edit && $data ['status'] == 1) {
$this->category_num_add ( $catid, 1 ); // 新入不需要审核+1
$this->add_user_point ( $post ['cuid'] ); // 会员积分
if ($post ['cuid'] > 0) {
// $this->activity($post['cuid'], $post['creator']); //会员活跃度
$this->_feed ( $sid );
}
$status = 1;
} elseif ($edit) {
if (isset ( $data ['catid'] ) && ($detail ['catid'] != $data ['catid'])) { // 是否更换了分类
if ($detail ['status'] == 1)
$this->category_num_dec ( $detail ['catid'] ); // 原分类通过审核的数量-1
if ($data ['status'] == 1) {
$this->category_num_add ( $data ['catid'] ); // 新分类数量+1
$status = 1;
}
} else {
if ($detail ['status'] != 1 && $data ['status'] == 1) {
$this->category_num_add ( $data ['catid'] ); // 通过审核+1
if ($post ['cuid'] > 0) {
$this->add_user_point ( $post ['cuid'] );
$this->_feed ( $sid );
}
$status = 1;
// $this->activity($post['cuid'], $detail['creator']);
} elseif ($detail ['status'] == 1 && isset ( $data ['status'] ) && $data ['status'] != 1) {
$this->category_num_dec ( $detail ['catid'] ); // 更改审核状态-1
} else {
if ($detail ['status'])
$status = 1;
}
}
}
if (! isset ( $detail ))
$detail = array ();
// if(isset($data['status'])) $field_post['status'] =
// $data['status'];
$data ['status'] = $status;
// 处理分类att
$this->save_att_category ( $sid, $catids, $status );
// 处理地区att
$this->save_att_area ( $sid, $data ['aid'], $status );
// 属性需要后期处理
$this->save_atts ( $table, $sid, $modelid, $data, $detail, $edit );
// 主题管理需要后期处理
$this->save_subjects ( $sid, $modelid, $edit );
// 标签需要后期处理
$this->save_tags ( $table, $sid, $modelid, $data, $detail, $edit );
// 更换了城市/更新下其他管理的id
if ($edit && isset ( $main_post ['city_id'] ) && $detail ['city_id'] != $main_post ['city_id']) {
$A = & $this->loader->model ( 'item:album' );
$A->change_city ( $sid, $main_post ['city_id'] );
}
return $sid;
}
// 保存主题附表
function save_field(&$post, $sid = null) {
}
// 单独处理标签
function save_tags($table, $sid, $modelid, &$post, &$detail, $edit = false) {
$city_id = ( int ) $post ['city_id'];
$fields = $this->variable ( 'field_' . $modelid );
$savedata = array ();
$TAG = & $this->loader->model ( 'item:tag' );
foreach ( $fields as $val ) {
if ($val ['type'] != 'tag')
continue;
if (! isset ( $post [$val ['fieldname']] ))
continue; // 如果不存,则表示数据和就的相同,已经被注销
if ($newtags = $post [$val ['fieldname']])
is_string ( $newtags ) && $newtags = unserialize ( $newtags );
if (! $groupid = $val ['config'] ['groupid'])
continue;
if (! $edit) {
if ($post ['status'] == 1)
if ($newtags)
$TAG->add ( $city_id, $groupid, $sid, $newtags ); // 新建
} else {
if ($city_id != ( int ) $detail ['city_id']) { // 转移所在城市
// 删除旧城市数据,增加新城市数据
$TAG->move_city ( $sid, $groupid, $city_id, $newtags );
continue;
}
if ($oldtags = $detail [$val ['fieldname']])
is_string ( $oldtags ) && $oldtags = unserialize ( $oldtags );
if ($detail ['status'] != 1 && $post ['status'] == 1) {
if ($newtags)
$TAG->add ( $city_id, $groupid, $sid, $newtags ); // 新建
} elseif ($detail ['status'] == 1 && $post ['status'] == 1) {
if ($oldtags && $newtags)
$TAG->replace ( $city_id, $groupid, $sid, $newtags, $oldtags ); // 删除,替换与更新
if (! $oldtags && $newtags)
$TAG->add ( $city_id, $groupid, $sid, $newtags ); // 新建
if ($oldtags && ! $newtags)
$TAG->delete ( $city_id, $groupid, $sid, $oldtags ); // 删除
} elseif ($detail ['status'] == 1 && isset ( $post ['status'] ) && $post ['status'] != 1) {
if ($oldtags)
$TAG->delete ( $city_id, $groupid, $sid, $oldtags ); // 删除
}
}
}
}
// 单独处理属性
function save_atts($table, $sid, $modelid, &$post, &$detail, $edit = false) {
$city_id = ( int ) $post ['city_id'];
$fields = $this->variable ( 'field_' . $modelid );
$savedata = array ();
$AD = & $this->loader->model ( 'item:att_data' );
foreach ( $fields as $val ) {
if ($val ['type'] != 'att')
continue;
if (! isset ( $post [$val ['fieldname']] ))
continue; // 如果不存,则表示数据和就的相同,已经被注销
$newatts = $post [$val ['fieldname']];
if (! $catid = $val ['config'] ['catid'])
continue;
// 删除旧的
$AD->delete_sid_catid ( $sid, $catid, 'att' );
if (! $newatts)
continue;
if (! $edit) {
if ($post ['status'] == 1 && $newatts)
$AD->add ( $catid, $sid, $newatts ); // 新建
} else {
$oldatts = $detail [$val ['fieldname']];
if ($detail ['status'] != 1 && $post ['status'] == 1) {
if ($newatts)
$AD->add ( $catid, $sid, $newatts ); // 新建
} elseif ($detail ['status'] == 1 && ($post ['status'] == 1 || ! isset ( $post ['status'] ))) {
if ($newatts)
$AD->add ( $catid, $sid, $newatts ); // 新建
// if($oldatts
// && $newatts)
// $AD->replace($catid,
// $sid, $newatts,
// $oldatts); //删除,替换与更新
// if(!$oldatts
// && $newatts)
// $AD->add($catid, $sid,
// $newatts); //新建
// if($oldatts
// && !$newatts)
// $AD->delete($catid,
// $sid, $oldatts); //删除
} elseif ($detail ['status'] == 1 && isset ( $post ['status'] ) && $post ['status'] != 1) {
// if($oldatts) $AD->delete($catid, $sid, $oldatts); //删除
}
}
}
}
// 单独处理分类
function save_att_category($sid, $catids, $status = 1) {
$AD = & $this->loader->model ( 'item:att_data' );
if (! $catids || ! $status) {
$AD->delete_sid ( $sid, 'category' );
return;
}
$atts = $AD->get_list ( $sid, 'category' );
if ($atts)
$atts = array_keys ( $atts );
$C = & $this->loader->model ( 'item:category' );
$attids = array ();
foreach ( $catids as $catid ) {
$_attids = $C->get_attids ( $catid );
if ($_attids)
$attids = array_merge ( $attids, $_attids );
}
$attids = array_unique ( $attids );
if (! $atts && ! $attids)
return;
if (! $atts && $attids) {
$AD->save ( $sid, $attids, 'category' );
return;
} elseif ($atts && ! $attids) {
$AD->delete ( $sid, $atts, 'category' );
return;
}
$del = $add = array ();
foreach ( $attids as $id ) {
if (! in_array ( $id, $atts ))
$add [] = $id;
}
foreach ( $atts as $id ) {
if (! in_array ( $id, $attids ))
$del [] = $id;
}
if ($del)
$AD->delete ( $sid, $del, 'category' );
if ($add)
$AD->save ( $sid, $add, 'category' );
}
// 单独处理地区
function save_att_area($sid, $aid, $status = 1) {
$AD = & $this->loader->model ( 'item:att_data' );
if (! $aid || ! $status) {
$AD->delete_sid ( $sid, 'area' );
return;
}
$atts = $AD->get_list ( $sid, 'area' );
if ($atts)
$atts = array_keys ( $atts );
$A = & $this->loader->model ( 'area' );
$attids = $A->get_attids ( $aid );
if (! $atts && ! $attids)
return;
if (! $atts && $attids) {
$AD->save ( $sid, $attids, 'area' );
return;
} elseif ($atts && ! $attids) {
$AD->delete ( $sid, $atts, 'area' );
return;
}
$del = $add = array ();
foreach ( $attids as $id ) {
if (! in_array ( $id, $atts ))
$add [] = $id;
}
foreach ( $atts as $id ) {
if (! in_array ( $id, $attids ))
$del [] = $id;
}
if ($del)
$AD->delete ( $sid, $del, 'area' );
if ($add)
$AD->save ( $sid, $add, 'area' );
}
// 单独处理主题关联
function save_subjects($sid, $modelid, $edit = false) {
$fields = $this->variable ( 'field_' . $modelid );
foreach ( $fields as $val ) {
if ($val ['type'] != 'subject')
continue;
$definname = 'ITEM_' . strtoupper ( $val ['fieldname'] ) . '_SUBJECTS';
$value = & $this->global ['define'] [$definname];
if ($edit && ! $value)
$this->subject_delete_related ( $sid, $val ['modelid'], $val ['fieldid'] ); // 删除所有关联
if ($value)
$this->subject_update_related ( $sid, $value, $val ['modelid'], $val ['fieldid'] ); // 更新关联表
unset ( $this->global ['define'] [$definname] );
}
}
// 更新主题关联表数据
function subject_update_related($sid, $subjects, $modelid, $fieldid) {
$this->db->from ( 'dbpre_subjectrelated' );
$this->db->where ( 'fieldid', $fieldid );
$this->db->where ( 'sid', $sid );
$addlist = $dellist = array ();
if ($q = $this->db->get ()) {
while ( $v = $q->fetch_array () ) {
if (! array_key_exists ( $v ['r_sid'], $subjects )) {
// 不存在则等待删除
$dellist [] = $v ['related_id'];
} else {
// 存在,则把准备添加的删除
unset ( $subjects [$v ['r_sid']] );
}
}
}
if ($subjects)
$addlist = array_keys ( $subjects );
if ($dellist) {
$this->db->from ( 'dbpre_subjectrelated' );
$this->db->where ( 'related_id', $dellist );
$this->db->delete ();
}
if ($addlist) {
foreach ( $addlist as $_sid ) {
$this->db->from ( 'dbpre_subjectrelated' );
$this->db->set ( 'fieldid', $fieldid );
$this->db->set ( 'modelid', $modelid );
$this->db->set ( 'sid', $sid );
$this->db->set ( 'r_sid', $_sid );
$this->db->insert ();
}
}
}
// 删除主题关联表数据
function subject_delete_related($sid, $modelid, $fieldid) {
$this->db->from ( 'dbpre_subjectrelated' );
$this->db->where ( 'fieldid', $fieldid );
$this->db->where ( 'sid', $sid );
$this->db->delete ();
}
// 在列表内提交更新,只涉及主表字段
function update($post) {
if (! is_array ( $post ) || ! $post)
redirect ( 'global_op_nothing' );
foreach ( $post as $sid => $val ) {
$this->db->from ( $this->table );
$this->db->set ( $val );
$this->db->where ( 'sid', $sid );
$this->db->update ();
}
}
// 批量移动分类
function move($sids, $catid) {
$sids = parent::get_keyids ( $sids );
if (! $catid)
redirect ( 'item_subject_move_catid_empty' );
$C = & $this->loader->model ( 'item:category' );
$root_pid = $C->get_parent_id ( $catid );
$category = $this->variable ( 'category_' . $root_pid );
if (! $mtcat = $category [$catid])
redirect ( 'itemcp_cat_empty' );
if ($mtcat ['pid'] == 0)
redirect ( 'item_subject_move_catid_isroot' );
$pid = $mtcat ['pid'];
$this->db->from ( $this->table );
$this->db->where_in ( 'sid', $sids );
$this->db->select ( 'sid,pid,catid,status,sub_catids,minor_catids' );
if (! $q = $this->db->get ())
return;
$dec_cats = $moveids = array ();
$add_num = 0;
$attids = array ();
while ( $v = $q->fetch () ) {
if ($v ['catid'] == $catid)
continue;
$moveids [] = $v ['sid'];
if ($v ['status'] = 1) {
if (isset ( $dec_cats [$v ['catid']] )) {
$dec_cats [$v ['catid']] ++;
} else {
$dec_cats [$v ['catid']] = 1;
}
$add_num ++;
}
$attids [$v ['sid']] [] = $catid;
if ($pid == $val ['pid'] && $val ['minor_catids']) {
$minor = explode ( '|', $val ['minor_catids'] );
foreach ( $minor as $_k => $_v ) {
if (! $_v)
unset ( $minor [$_k] );
}
$attids [$v ['sid']] = array_merge ( $attids [$v ['sid']], $minor );
}
}
$q->free ();
// 更新数据
if ($moveids) {
$this->db->from ( $this->table );
$this->db->where_in ( 'sid', $moveids );
$this->db->set ( 'pid', $pid );
$this->db->set ( 'catid', $catid );
$this->db->set ( 'sub_catids', '' );
$this->db->update ();
// 更新点评表
$R = & $this->loader->model ( ':review' );
$R->update_category ( 'item_subject', $moveids, $pid );
}
// 更新att
foreach ( $attids as $_sid => $_catids ) {
$this->save_att_category ( $_sid, $_catids );
}
// 更新分类统计
if ($add_num > 0) {
$this->category_num_add ( $catid, $add_num );
}
foreach ( $dec_cats as $catid => $num ) {
$this->category_num_dec ( $catid, $num );
}
}
// 删除主题
function delete($ids, $delete_point = FALSE) {
$ids = $this->get_keyids ( $ids );
$where = array (
'sid' => $ids
);
$this->_delete ( $where );
}
// 删除某个分类的主题
function delete_catid($catid) {
if (! is_numeric ( $catid ) || ! $catid)
return;
$where = array ();
$catids = $this->loader->model ( 'item:category' )->get_child_all_catids ( $catid );
if ($catids) {
$where ['catid'] = array_merge ( $catid, $catids );
} else {
$where ['catid'] = $catid;
}
$this->_delete ( $where, FALSE, FALSE );
}
// 审核主题
function checkup($sids) {
if (is_numeric ( $sids ) && $sids > 0)
$sids = array (
$sids
);
if (! is_array ( $sids ) || count ( $sids ) == 0)
redirect ( 'global_op_unselect' );
$this->db->from ( $this->table );
$this->db->where_in ( 'sid', $sids );
$this->db->where_not_equal ( 'status', 1 );
$this->db->select ( 'sid,aid,status,cuid,pid,catid,sub_catids,minor_catids' );
if (! $row = $this->db->get ())
return;
$upids = $pids = $atts = array ();
while ( $value = $row->fetch_array () ) {
$upids [] = $value ['sid'];
$this->category_num_add ( $value ['catid'] );
if ($value ['cuid'] > 0) {
// $this->activity($value['cuid'], $value['creator']); //活跃度
$this->add_user_point ( $value ['cuid'] ); // 会员积分
$this->_feed ( $value ['sid'] ); // feed
}
$pids [$value ['pid']] [] = $value ['sid'];
// 属性组
$fielddata = $this->read_field ( $value ['sid'], $value ['catid'] );
$fielddata = array_merge ( $fielddata, $value );
$fielddata ['status'] = 1;
$fielddata ['modelid'] = $this->model ['modelid'];
$fielddata ['tablename'] = 'dbpre_' . $this->model ['tablename'];
$atts [] = $fielddata;
// 分类/地区属性
$cat_attids = $area_attids = array ();
$area_attids [$value ['sid']] = $value ['aid'];
foreach ( array (
'sub_catids',
'minor_catids'
) as $_key ) {
$minor = explode ( '|', $value [$_key] );
foreach ( $minor as $_k => $_v ) {
if (! $_v)
unset ( $minor [$_k] );
}
$minor [] = $value ['catid'];
$minor = array_unique ( $minor );
$cat_attids [$value ['sid']] = $minor;
}
}
$row->free_result ();
if ($upids) {
$this->db->from ( $this->table );
$this->db->set ( 'status', 1 );
$this->db->where_in ( 'sid', $upids );
$this->db->update ();
// 标签部分因为在附表,所以要通过主分类id,获取模型表明,查询后处理
$this->checkup_tags ( $pids );
// 添加属性组
$detail = array ();
if ($atts)
foreach ( $atts as $val ) {
$this->save_atts ( $val ['tablename'], $val ['sid'], $val ['modelid'], $val, $detail, false );
}
if ($cat_attids)
foreach ( $cat_attids as $_sid => $_catids ) {
$this->save_att_category ( $_sid, $_catids );
}
if ($area_attids)
foreach ( $area_attids as $_sid => $_aid ) {
$this->save_att_area ( $_sid, $_aid );
}
}
}
// 审核更新标签
function checkup_tags($data) {
if (! $data)
return false;
$fields = $usetag = array ();
$TAG = & $this->loader->model ( 'item:tag' );
// 参数data的结构是 [pid]=>array([sid],[sid])
foreach ( $data as $pid => $sids ) {
if (! $pid)
continue;
$model = $this->get_model ( $pid, TRUE ); // 取分类关联模型
$modelid = $model ['modelid'];
if (! isset ( $fields [$modelid] ))
$fields [$modelid] = $this->variable ( 'field_' . $modelid ); // 取模型字段
if (! $fields [$modelid])
continue;
foreach ( $fields [$modelid] as $k => $val ) {
if ($val ['type'] == 'tag')
$usetag [$modelid] [$k] = $val; // 取标签字段
}
// 判断是否使用标签
if (! isset ( $usetag [$modelid] ) || count ( $usetag [$modelid] ) == 0)
continue;
$select = 's.sid,s.city_id';
$selects = array ();
foreach ( $usetag [$modelid] as $val ) {
$select .= ',' . $val ['fieldname']; // 获取数据的字段列表,由sid和其他标签字段组成
$selects [$val ['fieldname']] = $val; // 设置以标签字段名称为键名的数组内容
}
$table = 'dbpre_' . $model ['tablename']; // 查询的主题附表
// 因为需要知道主题的所属城市,必须关联到主表
$this->db->join ( $this->table, 's.sid', $table, 'sf.sid' );
$this->db->where_in ( 's.sid', $sids ); // 查询的sid
$this->db->select ( $select );
if (! $q = $this->db->get ())
continue;
// 获得数据
while ( $v = $q->fetch_array () ) {
// 循环每条数据的各个字段
foreach ( $v as $_k => $_v ) {
if ($_k == 'sid')
continue;
if (! $_v || strlen ( $_v ) < 3)
continue;
// 从selects里利通自读名称索引到标签关联的标签组id
if (! $groupid = ( int ) $selects [$_k] ['config'] ['groupid'])
continue;
$_v = unserialize ( $_v );
$TAG->add ( $v ['city_id'], $groupid, $v ['sid'], $_v ); // 加入标签表
}
}
$q->free_result ();
}
}
// 重建指定统计
function rebuild($sids) {
if (is_numeric ( $sids ) && $sids > 0)
$sids = array (
$sids
);
if (! is_array ( $sids ) || count ( $sids ) == 0)
redirect ( 'global_op_unselect' );
foreach ( $sids as $sid ) {
if (! $detail = $this->read ( $sid, '*', FALSE ))
continue;
$set = array ();
// 点评
$this->db->from ( 'dbpre_review' );
$this->db->where ( array (
'idtype' => 'item_subject',
'id' => $sid,
'status' => 1
) );
$set ['reviews'] = $this->db->count ();
// 图片
$this->db->from ( 'dbpre_pictures' );
$this->db->where ( array (
'sid' => $sid,
'status' => 1
) );
$set ['pictures'] = $this->db->count ();
// 留言
$this->db->from ( 'dbpre_guestbook' );
$this->db->where ( array (
'sid' => $sid,
'status' => 1
) );
$set ['guestbooks'] = $this->db->count ();
// 分数统计
$R = & $this->loader->model ( ':review' );
$myset = $R->update_review_point ( 'item_subject', $sid, $this->get_review_config ( $detail ), FALSE );
$myset && $set = array_merge ( $set, $myset );
unset ( $R );
// 其他模块关联的HOOK
foreach ( array_keys ( $this->global ['modules'] ) as $flag ) {
if ($flag == $this->model_flag)
continue;
$file = MUDDER_MODULE . $flag . DS . 'inc' . DS . 'item_rebuild_hook.php';
if (is_file ( $file )) {
if ($myset = include $file) {
$set = array_merge ( $set, $myset );
}
}
}
// 去掉不需要更新的
foreach ( $set as $key => $val ) {
if ($detail [$key] == $val) {
unset ( $set [$key] );
}
}
if (empty ( $set ))
continue;
$this->db->from ( $this->table );
$this->db->set ( $set );
$this->db->where ( 'sid', $sid );
$this->db->update ();
}
}
// 更新浏览量
function pageview($sid, $num = 1) {
$num = intval ( $num );
if (empty ( $num ))
return;
$this->db->from ( $this->table );
$this->db->set_add ( 'pageviews', $num );
$this->db->where ( 'sid', $sid );
$this->db->update ();
// 访客
$V = & $this->loader->model ( 'item:visitor' );
$V->visit ( $sid );
}
// 取得某分类下的点评对象数量
function category_count($catid) {
if (empty ( $catid ))
return false;
$this->db->from ( $this->table );
$this->db->where ( 'catid', $catid );
return $this->db->count ();
}
// 查询主题名称是否存在
function exists($city_id, $name, $subname, $without_sid = NULL) {
$this->db->from ( $this->table );
$this->db->where ( 'city_id', ( int ) $city_id );
$this->db->where ( 'name', $name );
$this->db->where ( 'subname', $subname );
$without_sid > 0 && $this->db->where_not_equal ( 'sid', $without_sid );
return $this->db->count () > 0;
}
// 设置坐标点
function mappoint($sid, $mappoint) {
if (! $mappoint)
return;
list ( $lat, $lng ) = explode ( ',', $mappoint );
$this->db->from ( $this->table );
$this->db->set ( 'map_lng', $lng );
$this->db->set ( 'map_lat', $lat );
$this->db->where ( 'sid', $sid );
$this->db->update ();
}
// 设定管理员
function set_owner($sid, $username, $expirydate = '', $update_subject = true, $show_error = true, $is_username = true) {
if (! $sid || ! $username) {
if (! $show_error)
return;
redirect ( lang ( 'global_sql_keyid_invalid', 'sid|username' ) );
}
$M = & $this->loader->model ( ':member' );
if (! $member = $M->read ( $username, $is_username )) {
if (! $show_error)
return;
redirect ( 'member_empty' );
}
$uid = $member ['uid'];
if ($expirydate) {
$this->loader->helper ( 'validate' );
if (! validate::is_date ( $expirydate )) {
if (! $show_error)
return;
redirect ( 'item_post_owner_expirydate_invalid' );
}
if (! $expirydate = strtotime ( $expirydate )) {
if (! $show_error)
return;
redirect ( 'item_post_owner_expirydate_invalid' );
}
if ($expirydate < $this->global ['timestamp']) {
if (! $show_error)
return;
redirect ( 'item_post_owner_expirydate_less' );
}
} else {
$expirydate = 0;
}
$this->db->from ( 'dbpre_mysubject' );
$this->db->where ( 'sid', $sid );
if ($detail = $this->db->get_one ()) {
if ($detail ['uid'] == $uid && $detail ['expirydate'] == $expirydate)
return;
$this->db->sql_roll_back ( 'from,where' );
$this->db->set ( 'uid', $uid );
$this->db->set ( 'expirydate', $expirydate );
$this->db->set ( 'lasttime ', _G ( 'timestamp' ) );
$this->db->update ();
} else {
$this->db->sql_roll_back ( 'from' );
$this->db->set ( 'sid', $sid );
$this->db->set ( 'uid', $uid );
$this->db->set ( 'expirydate', $expirydate );
$this->db->set ( 'lasttime ', _G ( 'timestamp' ) );
$this->db->insert ();
}
if ($update_subject) {
// if($detail && $detail['uid'] == $uid) return;
$this->db->from ( $this->table );
$this->db->set ( 'owner', $member ['username'] );
$this->db->where ( 'sid', $sid );
$this->db->update ();
}
}
// 删除一个管理员
function delete_owner($sid, $uid) {
$this->db->join ( 'dbpre_mysubject', 'ms.uid', 'dbpre_members', 'm.uid' );
$this->db->where ( 'sid', $sid );
$this->db->select ( 'ms.*,m.username' );
$this->db->order_by ( 'ms.uid' );
if (! $q = $this->db->get ())
return;
$up_username = array ();
$delete = false;
while ( $v = $q->fetch_array () ) {
if ($v ['uid'] == $uid) {
$delete = true;
} else {
$up_username [] = $v ['username'];
}
}
if (! $delete)
return;
$this->db->from ( 'dbpre_mysubject' );
$this->db->where ( 'sid', $sid );
$this->db->where ( 'uid', $uid );
$this->db->delete ();
// 更新主题字段
$this->db->from ( 'dbpre_subject' );
$this->db->where ( 'sid', $sid );
$this->db->set ( 'owner', $up_username ? implode ( ',', $up_username ) : '' );
$this->db->update ();
}
// 我管理的主题
function mysubject($uid) {
if (isset ( $this->global ['mysubjects'] ))
return $this->global ['mysubjects'];
$mindate = strtotime ( date ( 'Y-m-d', $this->global ['timestamp'] ) );
$result = array ();
$this->db->from ( 'dbpre_mysubject' );
$this->db->where ( 'uid', $uid );
if (! $query = $this->db->get ())
return $result;
$delete = array ();
$up_sid = array ();
while ( $val = $query->fetch_array () ) {
if ($val ['expirydate'] == 0 || $val ['expirydate'] >= $mindate) {
$result [] = $val ['sid'];
} else {
$delete [] = $val ['id'];
$up_sid [] = $val ['sid'];
}
}
if ($delete) {
$this->db->from ( 'dbpre_mysubject' );
$this->db->where_in ( 'id', $delete );
$this->db->delete ();
$this->update_owner ( $delete ); // 更新主题表
}
return $result;
}
// 更新主题会员表
function update_owner($sids) {
$this->db->join ( 'dbpre_mysubject', 'ms.uid', 'dbpre_members', 'm.uid' );
$this->db->where_in ( 'sid', $sids );
$this->db->select ( 'ms.*,m.username' );
$this->db->order_by ( 'ms.uid' );
$result = array ();
if (! $query = $this->db->get ())
return $result;
while ( $val = $query->fetch_array () ) {
$result [$val ['sid']] [] = $v ['username'];
}
$query->free_result ();
foreach ( $sids as $sid ) {
$this->db->from ( 'dbpre_subject' );
$this->db->where ( 'sid', $sid );
$this->db->set ( 'owner', isset ( $result [$sid] ) ? implode ( ',', $result [$sid] ) : '' );
$this->db->update ();
}
}
// 判断我的主题
function is_mysubject($sid, $uid) {
if (isset ( $this->global ['mysubjects'] ) && $uid == $this->global ['user']->uid) {
return in_array ( $sid, $this->global ['mysubjects'] );
}
$this->db->from ( 'dbpre_mysubject' );
$this->db->where ( 'uid', $uid );
$this->db->where ( 'sid', $sid );
return $this->db->count () >= 1;
}
// 读取某个主题的管理员
function owners($sid) {
$this->db->join ( 'dbpre_mysubject', 'ms.uid', 'dbpre_members', 'm.uid' );
$this->db->where ( 'sid', $sid );
$this->db->select ( 'ms.*,m.username,m.groupid' );
$this->db->order_by ( 'ms.uid' );
$result = array ();
if (! $query = $this->db->get ())
return $result;
while ( $val = $query->fetch_array () ) {
$result [] = $val;
}
$query->free_result ();
return $result;
}
// 读取最近浏览
function read_cookie($pid) {
$key = 'subject_' . ( int ) $pid;
$ckitems = empty ( $this->global ['cookie'] [$key] ) ? array () : unserialize ( stripslashes ( $this->global ['cookie'] [$key] ) );
foreach ( $ckitems as $key => $val ) {
$ckitems [$key] = _T ( $val );
}
return $ckitems;
}
// 写入最近浏览的
function write_cookie(& $subject, $num = 10, $day = 3) {
$ckitems = $this->read_cookie ( $subject ['pid'] );
if (! in_array ( $subject ['sid'], $ckitems )) {
$result = array ();
$result [$subject ['sid']] = $subject ['name'] . $subject ['subname'];
if (! empty ( $ckitems )) {
$i = 1;
foreach ( $ckitems as $key => $val ) {
if ($i >= $num)
break;
$result [$key] = $val;
$i ++;
}
}
}
set_cookie ( 'subject_' . $subject ['pid'], serialize ( $result ), 86400 * $day );
}
// 读取单个列表样式主题
function display_listfield(&$subject) {
$modelid = $this->get_modelid ( $subject ['pid'] );
$subject_field = array ();
$select = 's.sid,pid,catid,name,avgsort,sort1,sort2,sort3,sort4,sort5,sort6,sort7,sort8,best,pageviews,reviews,pictures,thumb,guestbooks,favorites';
$select_arr = explode ( ',', $select );
$fields = $this->variable ( 'field_' . $modelid );
foreach ( $fields as $val ) {
if (! $val ['show_list'])
continue;
if (! in_array ( $val ['fieldname'], $select_arr )) {
$select .= ',' . $val ['fieldname'];
}
if (! in_array ( $val ['fieldname'], array (
'name',
'subname',
'mappoint',
'owner',
'status',
'templateid',
'listorder'
) )) {
$subject_field [] = $val;
}
}
unset ( $select, $select_arr, $val, $fields );
$IFD = & $this->loader->model ( 'item:fielddetail' );
// 当前显示的页面类型
$IFD->pagemod = 'list';
// 样式设计
$IFD->td_num = 1; // 表只有1个td
$IFD->class = "";
$IFD->width = "";
$IFD->align = "left";
$result = '';
foreach ( $subject_field as $_val ) {
$result .= $IFD->detail ( $_val, $subject [$_val ['fieldname']], $subject ['sid'] );
}
return $result;
}
// 读取单个详细样式主题
function display_detailfield($subject) {
$modelid = $this->get_modelid ( $subject ['pid'] );
// 生成表格内容
$FD = & $this->loader->model ( $this->model_flag . ':fielddetail' );
$IFD = & $this->loader->model ( 'item:fielddetail' );
// 当前显示的页面类型
$IFD->pagemod = 'detail';
// 样式设计
$FD->class = 'key';
$FD->width = '';
$result = '';
// 载入字段信息
$fields = $this->variable ( 'field_' . $modelid );
foreach ( $fields as $val ) {
if (in_array ( $val ['fieldname'], array (
'mappoint',
'status',
'templateid',
'listorder'
) ))
continue;
if ($val ['type'] == 'textarea')
continue;
if ($val ['show_detail'])
$result .= $FD->detail ( $val, $subject [$val ['fieldname']], $subject ['sid'] ) . "\r\n";
}
return $result;
}
// 读取单个列表样式主题
function display_sidefield(&$subject) {
$modelid = $this->get_modelid ( $subject ['pid'] );
$subject_field = array ();
$select = 's.sid,pid,catid,name,avgsort,sort1,sort2,sort3,sort4,sort5,sort6,sort7,sort8,best,pageviews,reviews,pictures,thumb,guestbooks,favorites';
$select_arr = explode ( ',', $select );
$fields = $this->variable ( 'field_' . $modelid );
foreach ( $fields as $val ) {
if (! $val ['show_side'])
continue;
if (! in_array ( $val ['fieldname'], $select_arr )) {
$select .= ',' . $val ['fieldname'];
}
if (! in_array ( $val ['fieldname'], array (
'name',
'subname',
'mappoint',
'owner',
'status',
'templateid',
'listorder'
) )) {
$subject_field [] = $val;
}
}
unset ( $select, $select_arr, $val, $fields );
$IFD = & $this->loader->model ( 'item:fielddetail' );
// 当前显示的页面类型
$IFD->pagemod = 'side';
// 样式设计
$IFD->td_num = 1; // 表只有1个td
$IFD->class = "";
$IFD->width = "";
$IFD->align = "left";
$result = '';
foreach ( $subject_field as $_val ) {
$result .= $IFD->detail ( $_val, $subject [$_val ['fieldname']], $subject ['sid'] );
}
return $result;
}
// 生成表单
function create_form($pid, $subject = null, $ff_prarms = array('class'=>'altbg1')) {
$cate = $this->loader->variable ( 'category', $this->model_flag );
if (! $category = $cate [$pid])
redirect ( 'item_cat_empty' );
if (! $fieldlist = $this->loader->variable ( 'field_' . $category ['modelid'], $this->model_flag ))
redirect ( 'item_field_empty' );
$FF = & $this->loader->model ( $this->model_flag . ':fieldform' );
$FF->all_data ( $subject );
if ($ff_prarms && is_array ( $ff_prarms )) {
foreach ( $ff_prarms as $k => $v ) {
$FF->$k = $v;
}
}
$content = '';
foreach ( $fieldlist as $val ) {
if (! $this->in_admin && $val ['isadminfield'] == '2') {
if (! $this->is_mysubject ( $subject ['sid'], $this->global ['user']->uid ))
continue;
} elseif (! $this->in_admin && ! empty ( $val ['isadminfield'] )) {
continue;
}
if (defined ( 'item_allownull_' . $val ['fieldname'] ))
$val ['allownull'] = 0;
$content .= $FF->form ( $val, $subject ? $subject [$val ['fieldname']] : '', $subject != null );
}
return $content;
}
// 取得某个分类的数量
function get_category_total($catid) {
$this->db->where ( 'catid', $catid );
$this->db->where ( 'status', 1 );
$this->db->from ( $this->table );
return $this->db->count ();
}
// 增加分类统计数量
function category_num_add($catid, $num = 1) {
$this->db->from ( 'dbpre_category' );
$this->db->set_add ( 'total', $num );
$this->db->where ( 'catid', $catid );
$this->db->update ();
}
// 较少分类统计数量
function category_num_dec($catid, $num = 1) {
$this->db->from ( 'dbpre_category' );
$this->db->set_dec ( 'total', $num );
$this->db->where ( 'catid', $catid );
$this->db->update ();
}
// 增加积分
function add_user_point($uid, $num = 1) {
if (! $uid)
return;
$P = & $this->loader->model ( 'member:point' );
$BOOL = $P->update_point ( $uid, 'add_subject', FALSE, $num, FALSE, FALSE );
if (! $BOOL)
return;
$this->db->set_add ( 'subjects', $num );
$this->db->update ();
}
// 减少积分
function dec_user_point($uid, $num = 1) {
if (! $uid)
return;
$P = & $this->loader->model ( 'member:point' );
$BOOL = $P->update_point ( $uid, 'add_subject', TRUE, $num, FALSE, FALSE );
if (! $BOOL)
return;
$this->db->set_dec ( 'subjects', $num );
$this->db->update ();
}
// 活跃度
function activity($uid, $username) {
if (! $uid && ! $username)
return;
$post = array ();
if (! $uid || ! $username) {
$this->db->from ( 'dbpre_members' );
$this->db->select ( 'uid,username' );
if ($uid)
$this->db->where ( 'uid', $uid );
if ($username)
$this->db->where ( 'username', $username );
if (! $res = $this->db->get_one ())
return;
$uid = $res ['uid'];
$username = $res ['username'];
}
$A = & $this->loader->model ( $this->model_flag . ':activity' );
$A->save ( $uid, $username, 1, 0 );
}
// 检测添加主题权限
function check_access($key, $value, $jump) {
if ($this->in_admin)
return TRUE;
if ($key == 'item_subjects') {
$value = ( int ) $value;
if ($value && $value < 0) {
if (! $jump)
return FALSE;
if (! $this->global ['user']->isLogin)
redirect ( 'member_not_login' );
redirect ( 'item_access_alow_subject' );
}
if ($value && $value < $this->global ['user']->subjects) {
if (! $jump)
return FALSE;
redirect ( 'item_access_subjects' );
}
} elseif ($key == 'item_allow_edit_subject') {
$value = ( int ) $value;
if (! $value) {
if (! $jump)
return FALSE;
if (! $this->global ['user']->isLogin)
redirect ( 'member_not_login' );
redirect ( 'item_access_allow_edit_subject' );
}
}
return TRUE;
}
// 检查提交数据
function check_post(&$post, $edit, $sid) {
if ($post ['domain']) {
! $this->domain_check ( $post ['domain'] ) and redirect ( 'item_post_domain_invalid' );
$this->domain_exists ( $post ['domain'], $sid ) and redirect ( 'item_post_domain_exists' );
}
if ($post ['aid']) {
if (! $post ['city_id'])
redirect ( 'item_post_city_id_empty' );
$area = $this->loader->variable ( 'area_' . $post ['city_id'], '', false );
if (! isset ( $area [$post ['aid']] ))
redirect ( 'item_post_aid_empty' );
if ($area [$post ['aid']] ['level'] < 2)
redirect ( 'item_post_aid_level_invalid' );
}
// 检查风格ID字段
if ($post ['templateid'] > 0) { // 使用了风格,需要进行检测
$tpllist = $this->loader->variable ( 'templates' );
$exists = false;
empty ( $tpllist ) && redirect ( lang ( 'item_fieldvalidator_no_select_item', '主题风格' ) );
if ($tpllist ['item'])
foreach ( $tpllist ['item'] as $val ) {
if ($val ['templateid'] == $post ['templateid']) {
$exists = true;
break;
}
}
! $exists && redirect ( lang ( 'item_fieldvalidator_invalid_item', '主题风格' ) );
}
}
// 二级域名的合法性检测
function domain_check($domain) {
if (preg_match ( "/^[0-9]+$/i", $domain ))
return false;
if (! preg_match ( "/^[a-z0-9]{1,20}$/i", $domain ))
return false;
if (is_numeric ( $domain ))
return false;
if (in_array ( $domain, array_keys ( $this->global ['modules'] ) ))
return false;
$actlist = array (
'ajax',
'member',
'index',
'list',
'detail',
'pic',
'allpic',
'reviews',
'top',
'tag',
'rss',
'search',
'cate',
'category'
);
if (in_array ( $domain, $actlist ))
return false;
if ($reserve = $this->modcfg ['reserve_sldomain']) {
$list = explode ( ',', $reserve );
if (in_array ( $domain, $list ))
return false;
}
return true;
}
// 检测二级域名是否存在
function domain_exists($domain, $exc_sid = null) {
$this->db->from ( $this->table );
$this->db->where ( 'domain', $domain );
if ($exc_sid > 0)
$this->db->where_not_equal ( 'sid', $exc_sid );
return $this->db->count () >= 1;
}
// 检测当前用户的点评权限
// 返回数组的值
// code | 1:正常 -1:权限不足 -2:分类未开启游客点评 -3:分类未开启重复点 -4:会员没有重复点评权限
// -5:会员重复点评次数已满(extra:最大次数) -6:重复点评时间间隔未到(extra:时间间隔)
function review_access($sid = null) {
$result = array (
'code' => 1,
'extra' => ''
);
if ($this->in_admin)
return $result;
$R = & $this->loader->model ( ':review' );
if (! $this->global ['user']->check_access ( 'review_num', $R, FALSE )) {
$result ['code'] = - 1;
return $result;
}
$R = & $this->loader->model ( ':review' );
if (! $sid)
return $result;
$subject = is_array ( $sid ) ? $sid : $this->read ( $sid, '*', false );
$sid = $subject ['sid'];
$count = $R->reviewed ( 'item_subject', $sid, true ); // 单个主题点评数量
$category = $this->get_category ( $subject ['pid'] );
if (! $category ['config'] ['guest_review'] && ! $this->global ['user']->isLogin) {
$result ['code'] = - 2;
return $result; // 未开启游客点评
}
if (! $count ['num'])
return $result; // 第一次点评
if (! $category ['config'] ['repeat_review'] && $count ['num'] > 0) {
$result ['code'] = - 3;
return $result; // 未开启重复点评
}
if (! $this->global ['user']->check_access ( 'review_repeat', $R, FALSE )) {
$result ['code'] = - 4;
return $result; // 会员组没有重复点评权限
}
$minnum = ( int ) $category ['config'] ['repeat_review_num'];
if ($minnum && $minnum <= $count ['num']) {
$result ['code'] = - 5;
$result ['extra'] = $minnum;
return $result; // 点评次数超过了
}
if ($count ['num'] > 1) {
$last = $R->get_last ( 'item_subject', $sid );
$lasttime = $last ['posttime'];
} else {
$lasttime = $count ['posttime'];
}
$time = $this->global ['timestamp'] - $lasttime;
$mintime = ( int ) $category ['config'] ['repeat_review_time'];
if ($mintime && ($mintime * 60) >= $time) {
$result ['code'] = - 6;
$result ['extra'] = $mintime;
return $result; // 重复点评时间间隔未到
}
return $result;
}
// 获取主题的名称
function get_subject($params) {
// vp($params);
return $params ['name'] . ($params ['subname'] ? ('(' . $params ['subname'] . ')') : '');
}
// 获取主题所属名称
function get_city_id($params) {
return $params ['city_id'];
}
// 获取主题的pid
function get_obj_pid($params) {
return $params ['pid'];
}
// 更新点评数量
function review_total($sid, $num) {
if (! $sid || ! $num)
return;
$this->db->from ( $this->table );
$this->db->where ( 'sid', $sid );
if ($num > 0) {
$this->db->set_add ( $sid, $num );
} else {
$this->db->set_dec ( $sid, abs ( $num ) );
}
$this->db->update ();
}
// 获取主题所属分类的参数设置
function get_review_config($params) {
$category = $this->variable ( 'category' );
$pid = $params ['pid'];
$config = array ();
$config = $category [$pid] ['config'];
$config ['review_opt_gid'] = $category [$pid] ['review_opt_gid'];
return $config;
}
// 获取点评主分类规则列表
function get_review_category() {
$category = $this->variable ( 'category' );
$array = array ();
if ($category)
foreach ( $category as $val ) {
$array [$val ['catid']] = $val ['name'];
}
return $array;
}
// 获取当前主题的关联主题字段
function get_relate_subject_field($modelid) {
$result = array ();
$fields = $this->variable ( 'field_' . $modelid );
foreach ( $fields as $val ) {
if ($val ['type'] != 'subject')
continue;
if (! $val ['show_detail'])
continue;
// if($val['isadminfield']) continue;
if ($val ['config'] ['showmod'] == 'word' || ! $val ['config'] ['showmod'])
continue;
$result [] = $val;
}
return $result;
}
// 获取当前主题的淘宝客产品字段
function get_taoke_product_field($modelid) {
$result = array ();
$fields = $this->variable ( 'field_' . $modelid );
foreach ( $fields as $val ) {
if ($val ['type'] != 'taoke_product')
continue;
if (! $val ['show_detail'])
continue;
// if($val['isadminfield']) continue;
$result [] = $val;
}
return $result;
}
// 获取当前主题的多行文本字段
function get_textarea_field($modelid) {
$result = array ();
$fields = $this->variable ( 'field_' . $modelid );
foreach ( $fields as $val ) {
if ($val ['type'] != 'textarea')
continue;
if (! $val ['show_detail'])
continue;
// if($val['isadminfield']) continue;
$result [] = $val;
}
return $result;
}
// 单独设置主题
function set_template($sid, $templateid, $catid = null) {
if (! $catid) {
// 设置分类ID,可减少一次查表
$subject = $this->read ( $sid );
if (empty ( $subject ))
redirect ( 'item_empty' );
$catid = $subject ['catid'];
}
$templateid = ( int ) $templateid;
$this->get_category ( $catid );
$this->get_model ( $this->category ['modelid'] );
$table = 'dbpre_' . $this->model ['tablename'];
$this->db->from ( $table );
$this->db->where ( 'sid', $sid );
$this->db->set ( 'templateid', $templateid );
$this->db->update ();
}
// 获取主题风格类
function get_style() {
if (! $this->style) {
$this->style = & $this->loader->model ( 'item:subjectstyle' );
}
return $this->style;
}
// 删除主题
function _delete($where, $uptotal = TRUE, $delete_point = TRUE) {
$this->db->select ( 'sid,pid,catid,status,cuid,owner,creator' );
$this->db->from ( $this->table );
$this->db->where ( $where );
if (! $row = $this->db->get ())
return;
$upids = $creator = array ();
while ( $value = $row->fetch_array () ) {
if (! $this->in_admin && $this->global ['user']->username != $value ['owner']) {
redirect ( 'global_op_access' );
}
$upids [$value ['catid']] [] = $value ['sid'];
if ($value ['status'] == '1') {
// 分类统计更新
if ($uptotal)
$this->category_num_dec ( $value ['catid'] );
// 积分
if ($delete_point && $value ['cuid']) {
if (isset ( $creator [$value ['cuid']] )) {
$creator [$value ['cuid']] ++;
} else {
$creator [$value ['cuid']] = 1;
}
}
}
}
$row->free_result ();
if ($upids) {
$delids = array ();
foreach ( $upids as $pid => $ids ) {
// 附表(因模型会生成不同的表)
$this->_delete_field ( $ids, $pid );
$delids = array_merge ( $delids, $ids );
}
// 主题
$this->db->from ( $this->table );
$this->db->where_in ( 'sid', $delids );
$this->db->delete ();
// 删除关联表
$this->_delete_relate ( $delids );
}
if ($creator) {
if ($delete_point) {
// 减少积分
$P = & $this->loader->model ( 'member:point' );
foreach ( $creator as $uid => $num ) {
$P->update_point ( $uid, 'add_subject', TRUE, $num );
}
}
if ($creator)
foreach ( $creator as $uid => $num ) {
$this->db->from ( 'dbpre_members' )->where ( 'uid', $uid )->set_dec ( 'subjects', ( int ) $num )->update ();
}
}
}
// 删除附表
function _delete_field($ids, $pid) {
$this->get_category ( $pid );
$this->get_model ( $this->category ['modelid'] );
$table = 'dbpre_' . $this->model ['tablename'];
// 删除附表数据
$this->db->from ( $table );
$this->db->where_in ( 'sid', $ids );
$this->db->delete ();
// 删除会员参与
$MF = & $this->loader->model ( 'member:membereffect' );
$MF->delete ( $ids, $this->model ['tablename'] );
}
// 删除关联表信息(直接关联)
function _delete_relate($sids) {
// 主题管理员表
$this->db->from ( 'dbpre_mysubject' );
$this->db->where_in ( 'sid', $sids );
$this->db->delete ();
// 点评
$R = & $this->loader->model ( ':review' );
$R->delete_idtype ( 'item_subject', $sids, FALSE, FALSE );
// 图片
$P = & $this->loader->model ( 'item:picture' );
$P->delete_subject ( $sids );
// 相册
$A = & $this->loader->model ( 'item:album' );
$A->delete_subject ( $sids );
// 留言
$GB = & $this->loader->model ( 'item:guestbook' );
$GB->delete ( $sids, FALSE, FALSE, TRUE );
// 标签
$TAG = & $this->loader->model ( 'item:tag' );
$TAG->delete_ids ( $sids );
// 收藏
$FAV = & $this->loader->model ( 'item:favorite' );
$FAV->delete_sids ( $sids );
// 淘宝客
$STK = & $this->loader->model ( 'item:subjecttaoke' );
$STK->delete_sids ( $sids );
unset ( $R, $P, $GB, $TAG, $FAV, $STK );
// 其他模块关联的删除操作HOOK
foreach ( array_keys ( $this->global ['modules'] ) as $flag ) {
if ($flag == $this->model_flag)
continue;
$file = MUDDER_MODULE . $flag . DS . 'inc' . DS . 'item_delete_hook.php';
if (is_file ( $file )) {
@include $file;
}
}
}
// feed
function _feed($sid) {
if (! $sid)
return;
$FEED = & $this->loader->model ( 'member:feed' );
if (! $FEED->enabled ())
return;
$this->global ['fullalways'] = TRUE;
if (! $detail = $this->read ( $sid, '*', FALSE ))
return;
if (! $detail ['cuid'])
return;
$model = $this->get_model ( $detail ['pid'], TRUE );
$feed = array ();
$feed ['icon'] = lang ( 'item_subject_feed_icon' );
$feed ['title_template'] = lang ( 'item_subject_feed_title_template' );
$feed ['title_data'] = array (
'username' => '<a href="' . url ( "space/index/uid/$detail[cuid]" ) . '">' . $detail ['creator'] . '</a>',
'item_unit' => $model ['item_unit'],
'item_name' => $model ['item_name']
);
$feed ['body_template'] = lang ( 'item_subject_feed_body_template' );
$title = $detail ['name'] . ($detail ['subname'] ? "($detail[subname])" : '');
$feed ['body_data'] = array (
'title' => '<a href="' . url ( "item/detail/id/$detail[sid]" ) . '">' . $title . '</a>',
'review' => '<a href="' . url ( "review/member/ac/add/type/item_subject/id/$detail[sid]" ) . '">' . lang ( 'item_review' ) . '</a>'
);
$feed ['body_general'] = '';
$FEED->save ( $this->model_flag, $detail ['city_id'], $feed ['icon'], $detail ['cuid'], $detail ['creator'], $feed );
// $FEED->add($feed['icon'], $detail['cuid'], $detail['creator'],
// $feed['title_template'], $feed['title_data'], $feed['body_template'],
// $feed['body_data'], $feed['body_general']);
}
// 解析Tags
function get_mytag($val) {
$taghtml = "";
$mytag = & $this->loader->model ( 'item:tag' );
$val = $val ? unserialize ( $val ) : '';
if (count ( $val ) > 0) {
foreach ( $val as $tag ) {
if (! empty ( $tag )) {
$rr = $mytag->read ( $tag, null, true );
$taghtml = $taghtml . $rr[tagname].' ';
}
}
}
return $taghtml;
}
// 解析Att
function get_myatt($val) {
$atthtml = "";
$myatt = & $this->loader->model ( 'item:att_list' );
$attids = explode ( ',', $val );
if (count ( $attids ) > 0) {
foreach ( $attids as $attid ) {
if (! empty ( $attid )) {
$rr = $myatt->read ( $attid, null, false );
$atthtml = $atthtml . "<a href='{url item/list/catid/$rr[catid]/att/$rr[attid]}' class='mytag'>$rr[name]</a> ";
}
}
}
return $atthtml;
}
/*
* 按指定要求统计 可支持多条件统计
*/
function get_subject_total($aid) {
$this->db->where ( 'aid', $aid );
$this->db->from ( $this->table );
return $this->db->count ();
}
/*
* 构造多家分店名
*/
function buildmutiname($sids) {
$str = $temp = '';
if (count ( $sids ) > 1) {
foreach ( $sids as $key => $val ) {
$sj = $this->read_bysid ( $val );
$temp = $sj ['name'];
if ($sj ['subname'] != '') {
$str = $str . '/' . $sj ['subname'];
}
}
return $temp . $str;
} else {
$sj = $this->read_bysid ( $sids [0] );
return $sj ['name'];
}
}
// 复杂查询方法
function getlist2($sql) {
$result = array (0,'');
$result[1] = $this->db->query($sql);
return $result;
}
}
?>
<file_sep>/core/modules/tuan/helper/form.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
function form_tuan_category($select = '') {
$loader =& _G('loader');
if(!$category =& $loader->variable('category', 'tuan')) return;
$list = array();
foreach($category as $val) {
$list[$val['catid']] = $val['name'];
}
$loader->helper('form');
return form_option($list,$select);
}
function form_tuan_myowner($sid, $select='') {
$loader =& _G('loader');
$db =& _G('db');
$db->from('dbpre_tuan');
$db->select('tid,catid,sid,subject');
$db->where('sid',$sid);
if(!$q = $db->get()) return '';
$list = array();
while($v=$q->fetch_array()) {
$list[$v['tid']] = $v['subject'];
}
$q->free_result();
$loader->helper('form');
return form_option($list, $select);
}
function form_tuan_good_status($select='') {
$loader =& _G('loader');
$status = array('wait','stockout','sent','canceled');
$list = array();
foreach($status as $val) {
$list[$val] = lang('tuan_good_status_' . $val);
}
$loader->helper('form');
return form_option($list,$select);
}
function form_tuan_express($select='') {
$loader =& _G('loader');
$modcfg = $loader->variable('config','tuan');
$express = $modcfg['express'] ? explode(',',$modcfg['express']) : '';
if(!$express) return '';
$list = array();
foreach($express as $val) {
$list[$val] = $val;
}
$loader->helper('form');
return form_option($list, $select);
}
function form_tuan_sms_api($select='') {
$directory = MUDDER_MODULE . 'tuan' . DS . 'model' . DS . 'sms' . DS;
if(!$dirs = glob($directory . "*.inc")) return '';
$list = array();
foreach($dirs as $file) {
$name = _T(str_replace('<?php exit();?>', '', file_get_contents($file)));
$key = substr(basename($file,'.inc'),4);
$list[$key] = $name;
}
$loader =& _G('loader');
$loader->helper('form');
return form_option($list, $select);
}
function form_tuan_site_api($select='') {
$list=array();
$api = array('zuntu','fangwei','hao123','sohu','meituan','qq','360tuan');
foreach($api as $a) {
$key=$name=$a;
$list[$key] = $name;
}
$loader =& _G('loader');
$loader->helper('form');
return form_option($list, $select);
}
//团购网站
function form_tuan_tgsite($select = '') {
$loader =& _G('loader');
$db =& _G('db');
$db->from('dbpre_tuan_tgsite');
$db->select('id,sitename');
if(!$q = $db->get()) return '';
$list = array();
while($v=$q->fetch_array()) {
$list[$v['id']] = $v['sitename'];
}
$q->free_result();
$loader->helper('form');
return form_option($list, $select);
}
//团购网站接口API
function form_tuan_crule_api($select='') {
$directory = MUDDER_MODULE . 'tuan' . DS . 'model' . DS . 'crule' . DS;
if(!$dirs = glob($directory . "*.php")) return '';
$list = array();
foreach($dirs as $file) {
$key = basename($file,'.php');
$list[$key] = $key;
}
$loader =& _G('loader');
$loader->helper('form');
return form_option($list, $select);
}
?><file_sep>/core/modules/tuan/model/tempurl_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_tuan_tempurl extends ms_model {
var $table = 'dbpre_tuan_tempurl';
var $key = 'id';
var $model_flag = 'tuan';
function __construct() {
parent::__construct();
$this->model_flag = 'tuan';
$this->init_field();
$this->modcfg = $this->variable('config');
}
function msm_tuan_tempurl() {
$this->__construct();
}
function init_field() {
$this->add_field('subject,shortsubject,siteid,groupsite,url,thumb,oldprice,nowprice,discount,lasttime,starttime,sortorder,cityid,keyword,updatetime,cityname,citysname,recommend,nowpeople,bizgroup,bizname,big_catelist,small_catelist,big_catelist_catename,small_catelist_catename,groupkey,areaid,shopname');
//$this->add_field_fun('content,reply', '_T');
//$this->add_field_fun('tid,sort', 'intval');
}
function save($post, $id=null) {
$edit = $id > 0;
if($edit) {
//上传图片部分
if($_FILES['picture']['name']) {
$this->loader->lib('upload_image', NULL, FALSE);
$img = new ms_upload_image('picture', $this->global['cfg']['picture_ext']);
$this->upload_thumb($img);
$post['picture'] = str_replace(DS, '/', $img->path . '/' . $img->filename);
$post['thumb'] = str_replace(DS, '/', $img->path . '/' . $img->thumb_filenames['thumb']['filename']);
unset($img);
}
//时间转换
$post['starttime'] && $post['starttime'] = strtotime($post['starttime']);
$post['lasttime'] && $post['lasttime'] = strtotime($post['lasttime']) + (24 * 3600 - 1);
if(!$detail = $this->read($id)) redirect('tuan_tempurl_empty');
}
$id = parent::save($post,$id);
return $id;
}
//数据提交检测函数,实现父类的方法
function check_post($post, $edit = false) {
}
//团购数据采集
function spider($ids) {
}
}
?><file_sep>/core/modules/fenlei/admin/templates/fenlei_save.tpl.php
<?php
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
?>
<script type="text/javascript" src="./data/cachefiles/fenlei_category.js?r=<?=$MOD['jscache_flag']?>"></script>
<script type="text/javascript" src="./static/javascript/fenlei.js"></script>
<script type="text/javascript" src="./static/javascript/item.js"></script>
<script type="text/javascript" src="./static/javascript/validator.js"></script>
<script type="text/javascript" src="./static/javascript/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript">
var g;
function reload() {
var obj = document.getElementById('reload');
var btn = document.getElementById('switch');
if(obj.innerHTML.match(/^<.+href=.+>/)) {
g = obj.innerHTML;
obj.innerHTML = '<input type="file" name="thumb" size="20">';
btn.innerHTML = '取消上传';
} else {
obj.innerHTML = g;
btn.innerHTML = '重新上传';
}
}
function select_search(x) {
$('#search_result').css('display','').html(x);
$("#search_result li").each(function(i){
$(this).mouseover(function(){$(this).css("background","#C1EBFF")})
.mouseout(function(){$(this).css("background","#FFF")})
.click(function(){
$('#sid').val($(this).attr('sid'));
$('#keyword').val($(this).attr('name'));
$('#search_result').hide();
});
});
$('#search_result').append('<div class="search-closed">[<a href="###" onclick="$(\'#search_result\').hide();">关闭</a>]</div>');
$('#search_result').show();
}
function load_field() {
var value = $("#catid").val();
if(value == null || value == ''|| value == 0) return;
$("#custom_field").html("");
$.post("<?=cpurl($module,$act,'form')?>", { catid:value, fid:"<?=$fid?>", in_admin:1, in_ajax:1 }, function(result) {
if (result.match(/\{\s+caption:".*",message:".*".*\s*\}/)) {
myAlert(result);
} else {
html = '<table class="maintable" border="0" cellspacing="0" cellpadding="0">';
html += result;
html += '</table>';
$("#custom_field").html(html);
}
});
}
var maptext = '';
var point1 = point2 = '';
function map_mark(id, p1, p2) {
maptext = id;
point1 = p1;
point2 = p2;
var url = Url('modoer/index/act/map/width/450/height/300/p1/'+p1+'/p2/'+p2);
if(point1 != '' && point2 != '') {
url += '&show=yes';
}
var html = '<iframe src="' + url + '" frameborder="0" scrolling="no" width="450" height="310" id="ifupmap_map"></iframe>';
html += '<button type="button" id="mapbtn1">标注坐标</button> ';
html += '<button type="button" id="mapbtn2">确定</button>';
dlgOpen('选择地图坐标点', html, 470, 390);
$('#mapbtn1').click(
function() {
$(document.getElementById('ifupmap_map').contentWindow.document.body).find('#markbtn').click();
}
);
$('#mapbtn2').click(
function() {
point1 = $(document.getElementById('ifupmap_map').contentWindow.document.body).find('#point1').val();
point2 = $(document.getElementById('ifupmap_map').contentWindow.document.body).find('#point2').val();
if(point1 == '' || point2 == '') {
alert('您尚未完成标注。');
return;
}
$('#'+maptext).val(point1 + ',' + point2);
dlgClose();
}
);
}
$(document).ready(function(){
<?if(!$detail['catid']):?>
fenlei_select_category(document.getElementById('pid'),'catid');
<?endif;?>
load_field();
});
</script>
<div id="body">
<form method="post" action="<?=cpurl($module,$act,'save')?>" enctype="multipart/form-data" onsubmit="return validator(this);">
<div class="space">
<div class="subtitle">分类管理</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="right" class="altbg1" width="100"><span class="font_1">*</span>所属分类:</td>
<td width="*">
<select name="pid" id="pid" onchange="fenlei_select_category(this,'catid');load_field();">
<option value="">==选择主分类==</option>
<?=form_fenlei_category(0,$pid);?>
</select>
<select name="fenlei[catid]" id="catid" onchange="load_field();" validator="{'empty':'N','errmsg':'请选择信息所属子分类。'}">
<?=$detail['catid']?form_fenlei_category($pid,$detail['catid']):''?>
</select>
</td>
</tr>
<tr>
<td align="right" class="altbg1"><span class="font_1">*</span>所在地区:</td>
<td>
<?if($admin->is_founder):?>
<select name="city_id" onchange="select_city(this,'aid');">
<?=form_city($detail['city_id'])?>
</select>
<?endif;?>
<select name="fenlei[aid]" id="aid" validator="{'empty':'N','errmsg':'请选择信息所属地区。'}">
<option value="">全部</option>
<?=form_area($detail['city_id'], $detail['aid'])?>
</select>
</td>
</tr>
<tr>
<td align="right" class="altbg1"><span class="font_1">*</span>前台显示:</td>
<td><?=form_bool('fenlei[status]', (isset($detail['status'])?$detail['status']:1))?>
</td>
</tr>
<tr>
<td align="right" class="altbg1"><span class="font_1">*</span>信息标题:</td>
<td><input type="text" class="txtbox" name="fenlei[subject]" value="<?=$detail['subject']?>" /></td>
</tr>
<tr>
<td align="right" class="altbg1"><span class="font_1">*</span>有效期:</td>
<td><input type="text" class="txtbox3" name="fenlei[endtime]" value="<?=$detail['endtime']?date('Y-m-d',$detail['endtime']):''?>" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})" validator="{'empty':'N','errmsg':'请选择信息的有效期。'}" /> YYYY-MM-DD</td>
</tr>
<tr>
<td align="right" class="altbg1">封面图片:</td>
<td>
<?if(!$detail['thumb']):?>
<input type="file" name="thumb" size="20" />
<?else:?>
<span id="reload"><a href="<?=str_replace('thumb_','',$detail['thumb'])?>" target="_blank" src="<?=$detail['thumb']?>" onmouseover="tip_start(this);"><?=$detail['thumb']?></a></span>
[<a href="javascript:reload();" id="switch">重新上传</a>]
<?endif;?>
</td>
</tr>
<tr>
<td align="right" class="altbg1">关联主题:</td>
<td>
<div id="subject_search">
<?if($subject):?>
<a href="<?=url("item/detail/id/$sid")?>" target="_blank"><?=$subject['name'].($subject['subname']?"($subject[subname])":'')?></a>
<?endif;?>
</div>
<script type="text/javascript">
$('#subject_search').item_subject_search({
sid_name:'fenlei[sid]',
input_class:'txtbox2',
btn_class:'btn2',
result_css:'item_search_result',
<?if($subject):?>
sid:<?=$subject[sid]?>,
current_ready:true,
<?endif;?>
hide_keyword:true
});
</script>
</td>
</tr>
<tr>
<td align="right" class="altbg1">联系人:</td>
<td><input type="text" class="txtbox2" name="fenlei[linkman]" value="<?=$detail['linkman']?>" /></td>
</tr>
<tr>
<td align="right" class="altbg1">联系电话:</td>
<td><input type="text" class="txtbox2" name="fenlei[contact]" value="<?=$detail['contact']?>" /></td>
</tr>
<tr>
<td align="right" class="altbg1">电子邮箱:</td>
<td><input type="text" class="txtbox2" name="fenlei[email]" value="<?=$detail['email']?>" /></td>
</tr>
<tr>
<td align="right" class="altbg1">QQ/MSN:</td>
<td><input type="text" class="txtbox2" name="fenlei[im]" value="<?=$detail['im']?>" /></td>
</tr>
<tr id="tr_address">
<td align="right" class="altbg1">联系地址:</td>
<td><input type="text" class="txtbox" name="fenlei[address]" value="<?=$detail['address']?>" /></td>
</tr>
<tr>
<td align="right" class="altbg1">地图坐标:</td>
<td><input type="text" class="txtbox2" name="fenlei[mappoint]" id="mappoint_mappoint" size="30" value="<?=$detail['mappoint']?>" /> <a href="javascript:map_mark('mappoint_mappoint','<?=$detail['map_lng']?>','<?=$detail['map_lat']?>');">选择地图坐标点</a><div></div></td>
</tr>
<tr id="tr_content">
<td class="altbg1" valign="top" align="right"><span class="font_1">*</span>信息内容:</td>
<td><textarea name="fenlei[content]" rows="5" cols="50"><?=$detail['content']?></textarea></td>
</tr>
<tr>
<td align="right" class="altbg1"><?if($top_modfiy):?><input type="checkbox" name="modfiy_top" value="1" onclick="select_enable(this);"><label>修改</label><?endif;?>置顶:</td>
<td disabled="disabled">
<select name="fenlei[top]" id="fenlei_top" onchange="calc_top_point();"<?if($top_modfiy)echo' disabled'?>>
<option value="" basenum="0">==选择类型==</option>
<?=form_fenlei_tops()?>
</select>
<select name="fenlei[top_endtime]" id="fenlei_top_endtime" onchange="calc_top_point();"<?if($top_modfiy)echo' disabled'?>>
<option value="" point="0">==选择天数==</option>
<?=form_fenlei_days('top_days')?>
</select>
<?if($top_modfiy):?>
当前设置:<span><?=$fenlei_tops[$detail['top']]?></span> 至 <span><?=date('Y-m-d H:i', $detail['top_endtime'])?></span>
<?endif;?>
</td>
</tr>
<tr>
<td align="right" class="altbg1"><?if($color_modfiy):?><input type="checkbox" name="modfiy_color" value="1" onclick="select_enable(this);"><label>修改</label><?endif;?>变色:</td>
<td>
<select name="fenlei[color]"<?if($color_modfiy)echo' disabled'?>>
<option value="">==选择颜色==</option>
<?=form_fenlei_colors()?>
</select>
<select name="fenlei[color_endtime]" id="fenlei_color_endtime" onchange="calc_color_point();"<?if($color_modfiy)echo' disabled'?>>
<option value="" point="0">==选择天数==</option>
<?=form_fenlei_days('color_days')?>
</select>
<?if($color_modfiy):?>
当前设置:<span style="color:<?=$detail['color']?>;">当前颜色</span> 至 <span><?=date('Y-m-d H:i', $detail['color_endtime'])?></span>
<?endif;?>
</td>
</tr>
</table>
<div id="custom_field"></div>
<center>
<input type="hidden" name="do" value="<?=$op?>" />
<input type="hidden" name="forward" value="<?=get_forward();?>" />
<?if($op=='edit'):?><input type="hidden" name="fid" value="<?=$fid?>" /><?endif;?>
<button type="submit" name="dosubmit" value="yes" class="btn" /> 提交 </button>
<button type="button" class="btn" onclick="history.go(-1);" /> 返回 </button>
</center>
</div>
</form>
</div>
<script type="text/javascript">
select_enable = function(obj) {
$(obj).parent().parent().find('select').each(function(i){
var disabled = $(obj).attr("checked")?'':'disabled';
$(this).attr('disabled',disabled);
});
}
</script><file_sep>/core/modules/item/admin/subject_taoke.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
$domainArr = array (
"www.jianzhuj.com",
"jianzhuj.com",
"d.life3721.com",
"s.life3721.com",
"life3721.com/dz",
"life3721.com/sh",
"d.zk586.com",
"127.0.0.1",
"localhost"
);
if (!in_array ( $_SERVER ['HTTP_HOST'], $domainArr )) {
echo "<script type='text/javascript'> alert('您的域名未获得授权,禁止访问,请联系QQ:87176041获得授权,谢谢合作!');history.go(-1); </script>";
exit();
}
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$op = _input('op');
$_G['loader']->lib('taoapi',null,false);
$_G['loader']->helper('form,taoke','item');
$Taoapi_Config = Taoapi_Config::Init();
$Taoapi_Config->setTestMode(false)->setAppKey($MOD['taoke_appkey'])->setAppSecret($MOD['taoke_appsecret']);
$Taoapi = new ms_taoapi;
$C =& $_G['loader']->model('config');
switch($op) {
case 'store_add':
if($_GET['dosubmit']) {
if($taobaodata = taoke_item_shops()) list($total,$data) = $taobaodata;
if($total) {
$multipage = multi($total, $_GET['offset'], $_GET['page'], cpurl($module,$act,$op,$_GET));
}
}
$admin->tplname = cptpl('subject_taoke_store_add', MOD_FLAG);
break;
case 'store_detail':
$user_id = _input('user_id',null,MF_INT_KEY);
$detail = taoke_item_shop_detail($user_id);
$admin->tplname = cptpl('subject_taoke_store_detail', MOD_FLAG);
include MUDDER_CORE . $admin->tplname;
output();
break;
case 'store_linkfield':
if(!$catid = _post('catid',null)) redirect('item_taobaoke_add_category_empty');
$catid = explode(',', $catid);
$cid = 0;
foreach($catid as $id) if($id>0) $cid=$id;
$IB =& $_G['loader']->model('item:itembase');
$model = $IB->get_model($cid,true);
$fields = $_G['loader']->variable('field_'.$model['modelid'], 'item');
$use_fields = array();
foreach($fields as $k=>$v) {
if(in_array($v['fieldname'],array('aid','catid','status','templateid','level','finer',
'card_msg','mappoint'))) continue;
if(in_array($v['type'],array('area','level','template','att','subject','option','taoke_product')))
continue;
$use_fields[$k] = $v;
}
$admin->tplname = cptpl('subject_taoke_store_linkfield', MOD_FLAG);
break;
case 'store_recode':
$catid = _input('catid',null,MF_INT_KEY);
$fields = _input('fields',null);
$links = taoke_check_field($catid, $fields);
$C->save(array('taoke_catid'=>$catid,'taoke_link_fields'=>serialize($links)),MOD_FLAG);
break;
case 'store_start':
if(!$detail = taoke_item_save_store()) redirect(lang('item_taobaoke_addlost').'[user_id:'.$_POST['user_id'].']');
redirect('item_taoke_add_succeed');
break;
default:
redirect('global_op_unkown');
}
?><file_sep>/core/modules/modoer/item/model/att_list_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
class msm_item_att_list extends ms_model {
var $table = 'dbpre_att_list';
var $key = 'attid';
function __construct() {
parent::__construct ();
$this->model_flag = 'item';
}
function msm_item_att_list() {
$this->__construct ();
}
function save($catid, $names, $type = 'att') {
echo $names;
if (! $list = explode ( '|', $names ))
return;
foreach ( $list as $name ) {
if (! $name)
continue;
$post = array (
'catid' => $catid,
'name' => $name,
'type' => $type,
'listorder' => 0
);
$attid = parent::save ( $post, null, false, false );
}
$this->write_cache ( $catid );
return $attid;
}
function update($post) {
if (empty ( $post ))
redirect ( 'global_op_unselect' );
foreach ( $post as $id => $val ) {
$this->db->from ( $this->table );
$this->db->set ( $val );
$this->db->where ( 'attid', $id );
$this->db->update ();
}
}
function delete($attids) {
$ids = parent::get_keyids ( $attids );
$where = array (
'attid' => $ids
);
$this->_delete ( $where );
}
function delete_catid($catids, $type = 'att') {
$where = array (
'catid' => $catids,
'type' => $type
);
$this->_delete ( $where );
}
function write_cache($catid = null) {
if (! $catid)
return;
$this->db->from ( $this->table );
$this->db->where ( 'type', 'att' );
$this->db->where ( 'catid', $catid );
$this->db->order_by ( 'listorder' );
$result = array ();
if ($q = $this->db->get ()) {
while ( $v = $q->fetch_array () ) {
$result [$v ['attid']] = $v;
}
$q->free_result ();
}
write_cache ( 'att_list_' . $catid, arrayeval ( $result ), $this->model_flag );
}
function check_post(& $post, $edit = FALSE) {
if (! $post ['name'])
redirect ( 'itemcp_taggeoup_empty_name' );
}
function export($catid) {
$result = array ();
$this->db->from ( $this->table );
$this->db->where ( 'catid', $catid );
$this->db->order_by ( "attid" );
if (! $row = $this->db->get ())
return '';
while ( $value = $row->fetch_array () ) {
$split = '';
unset ( $value ['attid'] );
$value ['catid'] = '{catid:' . $value ['catid'] . '}';
$result [] = $value;
}
return $result;
}
function _delete($where) {
$this->db->from ( $this->table );
$this->db->where ( $where );
if (! $q = $this->db->get ())
return;
$attids = array ();
while ( $v = $q->fetch_array () ) {
$attids [] = $v ['attid'];
}
$q->free_result ();
// 其他模块关联的HOOK
foreach ( array_keys ( $this->global ['modules'] ) as $flag ) {
// if($flag == $this->model_flag) continue;
$file = MUDDER_MODULE . $flag . DS . 'inc' . DS . 'item_att_delete_hook.php';
if (is_file ( $file )) {
include $file;
}
}
$this->db->from ( $this->table );
$this->db->where_in ( 'attid', $attids );
$this->db->delete ();
}
// 加载单个信息
function read($key, $city_id = null, $is_name = FALSE) {
$this->db->from ( $this->table );
if ($city_id)
$this->db->where ( 'city_id', $city_id );
$this->db->where ( $is_name ? 'name' : 'attid', $key );
return $this->db->get_one ();
}
/**
* *
* 统计各分类对应的数量
* num1:美食商家数量
* num2:休闲商家数量s
* cats:分类编号
*/
function rebuild($catid) {
$ad = & $this->loader->model ( 'item:att_data' );
// cat=1:餐厅特色
// cat=2:餐厅氛围
// cat=3:外卖分类
if($catid=3)
$ad = & $this->loader->model ( 'item:att_data' );
$atts = $this->getsubcat ( $catid );
foreach ( $atts as $att ) {
$total = $ad->get_att_total ( $att ['attid'] );
$this->db->set ( 'num1', $total );
$this->db->from ( $this->table );
$this->db->where ( 'attid', $att ['attid'] );
$this->db->update ();
}
}
// 取得下级的属性集合
function getsubcat($catid) {
$this->db->select ( 'attid,catid,name' );
$this->db->from ( $this->table );
$this->db->where ( 'catid', $catid );
$this->db->order_by ( 'listorder' );
$row = $this->db->get ();
$result = array ();
if ($row) {
while ( $value = $row->fetch_array () ) {
$result [$value ['attid']] = $value;
}
}
return $result;
}
}
?><file_sep>/core/modules/mobile/rand.php
<?php
//一批数量
$num = 5;
//实例化主题类
$I =& $_G['loader']->model('item:subject');
$where = array();
$where['city_id'] = array(0,$_CITY['aid']);
if(!$list = $I->read_random($where, $num, true)) {
redirect('item_random_empty');
}
$reviewcfg = $_G['loader']->variable('config','review');
if($_G['in_ajax']) {
$tplname = 'list_li';
} else {
$tplname = 'rand';
}
include mobile_template($tplname);
?><file_sep>/core/modules/tuan/admin/templates/subscibe_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="post" action="<?=cpurl($module,$act)?>" name="myform">
<div class="space">
<div class="subtitle">邮件订阅管理</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y">
<tr class="altbg1">
<td width="50">删?</td>
<td width="100">类别</td>
<td width="100">城市</td>
<td width="250">E-mail</td>
<td width="*">订阅时间</td>
</tr>
<?if($total):?>
<?while($val=$list->fetch_array()) {?>
<tr>
<td><input type="checkbox" name="ids[]" value="<?=$val['id']?>" /></td>
<td><?=$val['sort']?></td>
<td><?=template_print('modoer','area',array('aid'=>$val['city_id']))?></td>
<td><?=$val['email']?></td>
<td><?=date('Y-m-d H:i', $val['dateline'])?></td>
</tr>
<?}?>
<?else:?>
<tr><td colspan="4">暂无信息</td></tr>
<?endif;?>
</table>
</div>
<div><?=$multipage?></div>
<center>
<input type="hidden" name="op" value="update" />
<input type="hidden" name="dosubmit" value="yes" />
<?if($total):?>
<button type="button" class="btn" onclick="easy_submit('myform','delete','ids[]');">删除所选</button>
<?endif;?>
</center>
</form>
</div><file_sep>/core/modules/modoer/item/ajax/subject.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
$allow_ops = array (
'search',
'search1',
'exists',
'myfavorite',
'myreviewed',
'get_membereffect',
'post_membereffect',
'post_map',
'post_log',
'clear_cookie_subject',
'sids',
'get_taoke_detail',
'get_sub_cats',
'get_threeareas',
'get_smallshop',
'subcats',
'subcats1'
);
$login_ops = array (
'post_membereffect',
'add_favorite'
);
$op = empty ( $op ) || ! in_array ( $op, $allow_ops ) ? '' : $op;
if (! $op) {
redirect ( 'global_op_unkown' );
} elseif (! $user->isLogin && in_array ( $op, $login_ops )) {
redirect ( 'member_not_login' );
}
switch ($op) {
case 'sids' :
$sids = _post ( 'sids', null, MF_TEXT );
if (! $sids)
redirect ( lang ( 'global_sql_keyid_invalid', 'sids' ) );
$where = array ();
$where ['sid'] = explode ( ',', $sids );
$S = & $_G ['loader']->model ( 'item:subject' );
list ( , $list ) = $S->find ( 'sid,pid,catid,city_id,aid,name,subname', $where, 'sid', 0, 0 );
if ($list) {
while ( $val = $list->fetch_array () ) {
$result [] = seatch_to_array ( $val );
}
$list->free_result ();
echo search_to_xml ( $result );
}
output ();
break;
case 'search' :
$SEARCH = & $_G ['loader']->model ( 'item:search' );
$keyword = trim ( $_POST ['keyword'] );
if ($_G ['charset'] != 'utf-8') {
$_G ['loader']->lib ( 'chinese', NULL, FALSE );
$CHS = new ms_chinese ( 'utf-8', $_G ['charset'] );
$keyword = $keyword ? $CHS->Convert ( $keyword ) : '';
}
$_GET ['keyword'] = $keyword;
$_GET ['catid'] = is_numeric ( $_GET ['pid'] ) ? ( int ) $_GET ['pid'] : 0;
$_GET ['ordersort'] = 'addtime';
$_GET ['ordertype'] = 'desc';
list ( $total, $list ) = $SEARCH->search ();
if (! $total) {
redirect ( 'item_search_result_empty' );
} else {
$category = $SEARCH->variable ( 'category' );
$result = array ();
while ( $val = $list->fetch_array () ) {
$pre = ($val ['city_id'] ? template_print ( 'modoer', 'area', array (
'aid' => $val ['city_id']
) ) : '');
$name = $val ['name'] . ($val ['subname'] ? "($val[subname])" : '');
$cat_name = $category [$val ['pid']] ['name'];
$result [] = array (
'sid' => $val ['sid'],
'pid' => $val ['pid'],
'catid' => $val ['catid'],
'aid' => $val ['city_id'],
'city_id' => $val ['city_id'],
'name' => $name,
'city_name' => display ( "modoer:area", "aid/$val[city_id]" ),
'cat_name' => $cat_name,
'title' => '[' . $pre . $cat_name . '] ' . $name
);
}
echo search_to_xml ( $result );
output ();
}
break;
// 返回商户分店信息
case 'exists' :
$styleid = _post ( 'styleid', '0', 'intval' );
$city_id = _post ( 'city_id', '0', 'intval' );
$pid = _post ( 'pid', '0', 'intval' );
$name = _post ( 'name', '', 'trim' );
if ($_G ['charset'] != 'utf-8') {
$_G ['loader']->lib ( 'chinese', NULL, FALSE );
$CHS = new ms_chinese ( 'utf-8', $_G ['charset'] );
$name = $name ? $CHS->Convert ( $name ) : '';
}
if (! $name)
redirect ( lang ( 'item_search_keyword_empty' ) );
$S = & $_G ['loader']->model ( 'item:subject' );
$where = array ();
if ($city_id)
$where ['city_id'] = $city_id;
if ($pid)
$where ['pid'] = $pid;
$where ['name'] = $name;
list ( $num, $list ) = $S->find ( 'sid,name,subname,fullname', $where, 'sid', 0, 0, TRUE );
if (! $list) {
redirect ( 'item_search_result_empty' );
} else {
if ($styleid == 1) {
if ($num == 1) {
$val = $list->fetch_array ();
$content = "\t<input type=\"checkbox\" name=\"mycheck\" value=\"$val[sid]\">$val[name]" . "\r\n<br/>";
}
while ( $val = $list->fetch_array () ) {
if ($val ['subname'] != '')
$content .= "\t<input type=\"checkbox\" name=\"mycheck\" value=\"$val[sid]\">$val[name]($val[subname])" . "\r\n<br/>";
}
} else {
while ( $val = $list->fetch_array () ) {
$content .= "\t<option value=\"$val[sid]\">$val[name]" . ($val ['subname'] ? "($val[subname])" : '') . "</option>\r\n";
}
}
$list->free_result ();
echo $content;
output ();
}
break;
case 'myfavorite' :
$FAV = & $_G ['loader']->model ( 'item:favorite' );
$select = 'f.*,s.name,s.subname,s.city_id,s.aid,s.pid,s.catid';
$where = array ();
$where ['f.idtype'] = 'subject';
$where ['f.uid'] = $user->uid;
$start = get_start ( $_GET ['page'], $offset = 50 );
list ( $total, $list ) = $FAV->find ( $select, $where, $start, $offset );
if (! $total) {
redirect ( 'item_search_result_empty' );
} else {
while ( $val = $list->fetch_array () ) {
// vp($val);
$result [] = seatch_to_array ( $val );
}
$list->free_result ();
echo search_to_xml ( $result );
output ();
}
break;
case 'myreviewed' :
$R = & $_G ['loader']->model ( ':review' );
$start = get_start ( $_GET ['page'], $offset = 50 );
list ( $total, $list ) = $R->myreviewed ( $user->uid, $start, $offset );
if (! $total) {
redirect ( 'item_search_result_empty' );
} else {
while ( $val = $list->fetch_array () ) {
$val ['sid'] = $val ['id'];
$val ['pid'] = $val ['pcatid'];
$val ['name'] = $val ['subject'];
$result [] = seatch_to_array ( $val );
}
$list->free_result ();
echo search_to_xml ( $result );
output ();
}
break;
case 'get_membereffect' :
if (! $sid = _input ( 'sid', 0, 'intval' ))
redirect ( lang ( 'global_sql_keyid_invalid', 'sid' ) );
if (! $effect = _input ( 'effect', '', MF_TEXT ))
redirect ( lang ( 'member_effect_unkown_effect' ) );
$S = & $_G ['loader']->model ( 'item:subject' );
if (! $subject = $S->read ( $sid, 'pid,name,subname,pid,status', false ))
redirect ( lang ( 'item_empty' ) );
if (! $model = $S->get_model ( $subject ['pid'], TRUE ))
redirect ( 'item_model_empty' );
$idtype = $model ['tablename'];
$M = & $_G ['loader']->model ( 'member:membereffect' );
$M->add_idtype ( $idtype, 'subject', 'sid' );
$member = _input ( 'member', NULL );
if ($member == 'Y') {
if ($list = $M->get_member ( $sid, $idtype, $effect )) {
while ( $val = $list->fetch_array () ) {
echo '<li><div><a title="' . $val ['username'] . '" href="' . url ( "space/index/uid/$val[uid]" ) . '" target="_blank"><img src="' . get_face ( $val ['uid'] ) . '" />' . $val ['username'] . '</a></div></li>';
}
} else {
redirect ( 'global_empty_info' );
}
} else {
$totals = $M->total ( $sid, $idtype );
if ($totals) {
foreach ( $totals as $key => $val ) {
if (substr ( $key, 0, 6 ) == 'effect') {
echo $split . $val;
$split = '|';
}
}
} else {
echo '0|0';
}
}
output ();
break;
case 'post_membereffect' :
if (! $sid = _post ( 'sid', 0, 'intval' ))
redirect ( lang ( 'global_sql_keyid_invalid', 'sid' ) );
if (! isset ( $_POST ['effect'] ))
redirect ( lang ( 'member_effect_unkown_effect' ) );
$S = & $_G ['loader']->model ( 'item:subject' );
if (! $subject = $S->read ( $sid, 'pid,name,subname,pid,status', false ))
redirect ( lang ( 'item_empty' ) );
if (! $model = $S->get_model ( $subject ['pid'], TRUE ))
redirect ( 'item_model_empty' );
$idtype = $model ['tablename'];
$effect = $_POST ['effect'];
$M = & $_G ['loader']->model ( 'member:membereffect' );
$M->add_idtype ( $idtype, 'subject', 'sid' );
$M->save ( $sid, $idtype, $effect );
if ($totals = $M->total ( $sid, $idtype )) {
foreach ( $totals as $key => $val ) {
if (substr ( $key, 0, 6 ) == 'effect') {
echo $split . $val;
$split = '|';
}
}
} else {
echo '0|0';
}
output ();
break;
case 'post_map' :
if (! $sid = ( int ) $_POST ['sid'])
redirect ( lang ( 'global_sql_keyid_invalid', 'sid' ) );
$I = & $_G ['loader']->model ( MOD_FLAG . ':subject' );
if (! $item = $I->read ( $sid )) {
redirect ( lang ( 'item_empty' ) );
}
if ($_POST ['dosubmit']) {
if ($item ['mappoint']) {
$SL = & $_G ['loader']->model ( MOD_FLAG . ':subjectlog' );
$_POST ['ismappoint'] = 1;
$_POST ['upcontent'] = $_POST ['p1'] . ',' . $_POST ['p2'];
if (! $user->isLogin) {
$_POST ['username'] = 'guest';
$_POST ['email'] = '<EMAIL>';
}
$SL->save ();
} else {
$I->mappoint ( $sid, $_POST ['p1'] . ',' . $_POST ['p2'] );
}
redirect ( 'global_op_succeed' );
} else {
include template ( 'item_ajax_post_map' );
output ();
}
break;
case 'post_log' :
if (! $sid = ( int ) $_POST ['sid'])
redirect ( lang ( 'global_sql_keyid_invalid', 'sid' ) );
$I = & $_G ['loader']->model ( MOD_FLAG . ':subject' );
if (! $item = $I->read ( $sid )) {
redirect ( lang ( 'item_empty' ) );
}
if ($_POST ['dosubmit']) {
$SL = & $_G ['loader']->model ( MOD_FLAG . ':subjectlog' );
$_POST ['ismappoint'] = 0;
$SL->save ();
redirect ( 'item_log_succeed' );
} else {
include template ( 'item_ajax_post_log' );
output ();
}
break;
case 'clear_cookie_subject' :
del_cookie ( 'subject_' . $_POST ['pid'] );
break;
case 'get_taoke_detail' :
$sid = _input ( 'sid', null, MF_INT_KEY );
$S = & $_G ['loader']->model ( 'item:subject' );
if (! $detail = $S->read ( $sid ))
redirect ( 'item_subject_empty' );
$category = $S->get_category ( $detail ['catid'] );
if (! $pid = $category ['catid']) {
redirect ( 'item_cat_empty' );
}
$modelid = $S->category ['modelid'];
$taoke_product_field = $S->get_taoke_product_field ( $modelid );
if ($detail ['templateid']) {
include template ( 'item_subject_detail_taoke', 'item', $detail ['templateid'] );
} else {
include template ( 'item_subject_detail_taoke' );
}
output ();
break;
case 'get_sub_cats' :
$catid = _input ( 'catid', null, MF_INT_KEY );
$sid = _input ( 'sid', null, MF_INT_KEY );
$sub_catids = array ();
if ($sid) {
$I = & $_G ['loader']->model ( MOD_FLAG . ':subject' );
$subject = $I->read ( $sid );
$subject ['sub_catids'] && $sub_catids = explode ( '|', $subject ['sub_catids'] );
}
$_G ['loader']->helper ( 'form', 'item' );
$content = form_item_category_sub ( $catid, $sub_catids );
echo $content;
output ();
break;
/* 20120719 */
case 'search1' :
$str = "";
$SEARCH = & $_G ['loader']->model ( 'item:search' );
$keyword = strtolower ( $_GET ["q"] );
if ($_G ['charset'] != 'utf-8') {
$_G ['loader']->lib ( 'chinese', NULL, FALSE );
$CHS = new ms_chinese ( 'utf-8', $_G ['charset'] );
$keyword = $keyword ? $CHS->Convert ( $keyword ) : '';
}
$_GET ['keyword'] = $keyword;
$_GET ['catid'] = is_numeric ( $_GET ['pid'] ) ? ( int ) $_GET ['pid'] : 0;
$_GET ['ordersort'] = 'addtime';
$_GET ['ordertype'] = 'desc';
list ( $total, $list ) = $SEARCH->search (0,0,true,'sname');
if ($total) {
while ( $val = $list->fetch_array () ) {
$name = $val ['name'];
$sid = $val ['sid'];
$str = $str . "$sid-$name|\n";
}
// $str=substr($str, 0,-1);
}
echo $str;
output ();
break;
case 'existone' :
$str = "";
$SEARCH = & $_G ['loader']->model ( 'item:search' );
$keyword = strtolower ( $_GET ["q"] );
if ($_G ['charset'] != 'utf-8') {
$_G ['loader']->lib ( 'chinese', NULL, FALSE );
$CHS = new ms_chinese ( 'utf-8', $_G ['charset'] );
$keyword = $keyword ? $CHS->Convert ( $keyword ) : '';
}
$_GET ['keyword'] = $keyword;
$_GET ['catid'] = is_numeric ( $_GET ['pid'] ) ? ( int ) $_GET ['pid'] : 0;
$_GET ['ordersort'] = 'addtime';
$_GET ['ordertype'] = 'desc';
list ( $total, $list ) = $SEARCH->search ();
if ($total) {
while ( $val = $list->fetch_array () ) {
$name = $val ['name'] . ($val ['subname'] ? "($val[subname])" : '');
$sid = $val ['sid'];
$str = $str . "$sid-$name\n";
}
}
echo $str;
output ();
break;
case 'get_threeareas' :
$styleid = $_GET ['styleid'];
$pid = $_GET ['pid'];
if (empty ( $pid ))
$pid = 9;
else
$pid = ( int ) $pid;
$A = & $_G ['loader']->model ( 'area' );
$areas = $A->get_list ( $pid );
if (empty ( $styleid )) {
include template ( 'area_list_ajax' );
output ();
} elseif ($styleid == 2) {
$alist = "";
foreach ( $areas as $area ) {
$alist = $alist . $area [aid] . ',' . $area [name] . '|';
}
$alist = substr ( $alist, 0, - 1 );
echo $alist;
output ();
}
break;
case 'get_smallshop' :
include template ( 'smallshop_list_ajax' );
output ();
break;
// 取得二级分类(LI)
case 'subcats' :
$restr = '';
$pid = $_GET ['pid'];
if (! empty ( $pid )) {
$ss = 'category_' . $pid;
$cats = $_G ['loader']->variable ( $ss, 'item' );
foreach ( $cats as $cat ) {
if ($cat ['level'] == 2) {
$restr .= "<li><a href='javascript:;' selectid='$cat[catid]'>$cat[name]</a></li>";
}
}
}
echo $restr;
output ();
break;
// 取得二级分类(option)
case 'subcats1' :
$restr = '<option value=\"\">全部</option>';
$pid = $_GET ['pid'];
if (! empty ( $pid )) {
$ss = 'category_' . $pid;
$cats = $_G ['loader']->variable ( $ss, 'item' );
foreach ( $cats as $cat ) {
if ($cat ['level'] == 2) {
$restr .= "<option value='$cat[catid]'>$cat[name]</option>";
}
}
}
echo $restr;
output ();
break;
default :
redirect ( 'global_op_unkown' );
}
function seatch_to_array(&$val) {
$city_name = $val ['city_id'] ? display ( "modoer:area", "aid/$val[city_id]" ) : '';
$cat_name = display ( "item:category", "catid/$val[pid]" );
$name = $val ['name'] . ($val ['subname'] ? "($val[subname])" : '');
return array (
'sid' => $val ['sid'],
'pid' => $val ['pid'],
'catid' => $val ['catid'],
'aid' => $val ['city_id'],
'city_id' => $val ['city_id'],
'name' => $name,
'city_name' => city_name,
'cat_name' => $cat_name,
'title' => '[' . $city_name . $cat_name . '] ' . $name
);
}
function search_to_xml($result) {
if (! $result)
return '';
$content = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
$content .= "<root>\n";
foreach ( $result as $val ) {
$content .= "<subject>\n";
foreach ( $val as $k => $v ) {
$htmlon = preg_match ( "/<[a-z]+\s+.+\\>/i", $v );
$content .= "\t<$k>" . ($htmlon ? '<![CDATA[' : '') . $v . ($htmlon ? ']]>' : '') . "</$k>\n";
}
$content .= "</subject>\n";
}
$content .= "</root>";
return $content;
}
?><file_sep>/core/modules/tuan/model/sms/sms_powereasy_config.php
<?php !defined('IN_MUDDER') && exit('Access Denied');?>
<tr>
<td class="altbg2" colspan="2">“动易短信通”服务平台整合移动、联通、电信和网通四网于一体,四大运营商短信全部覆盖,全国各地短信通行无阻;全面支持中国移动、中国联通和中国电信天翼用户。访问和注册动易短信通:<a href="http://sms.powereasy.net/" target="_blank">sms.powereasy.net</a></td>
</tr>
<tr>
<td class="altbg1"><strong>动易短信通帐号:</strong>填写动易短信通帐号</td>
<td><input type="text" name="modcfg[sms_powereasy_username]" id="sms_powereasy_username" value="<?=$modcfg['sms_powereasy_username']?>" class="txtbox3" /></td>
</tr>
<tr>
<td class="altbg1"><strong>动易短信通MD5密钥:</strong>帐号发送的验证密钥</td>
<td><input type="text" name="modcfg[sms_powereasy_md5key]" id="sms_powereasy_md5key" value="<?=$modcfg['sms_powereasy_md5key']?'******':''?>" class="txtbox3" /></td>
</tr><file_sep>/core/modules/item/ajax/android.php
<?php
/**
* @author songjianhua>
* @copyright (c)2001-2009 Moufersoft
* @website www.thmeishi.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
$allow_ops = array (
'get_recommend'
);
$login_ops = array (
'post_membereffect',
'add_favorite'
);
$op = empty ( $op ) || ! in_array ( $op, $allow_ops ) ? '' : $op;
$S = & $_G ['loader']->model ( 'item:delivery' );
$json = & $_G ['loader']->lib ( 'json', NULL, TRUE );
if (! $op) {
redirect ( 'global_op_unkown' );
} elseif (! $user->isLogin && in_array ( $op, $login_ops )) {
redirect ( 'member_not_login' );
}
switch ($op) {
//主界面推荐商家接口
case 'get_recommend' :
$where = array ();
$where ['s.c_status'] = 1;
$orderby = array (
's.sid' => 'DESC',
's.c_finer' => 'DESC'
);
$select = "s.sid as id,s.c_fullname as name,s.c_thumb as zoom,s.c_minprice as startprice,
s.c_finer as recommend,s.c_stars as stars,
s.c_avgprice as average,sf.c_dianhua,sf.c_dizhi as address,sf.c_yunye ";
list ( , $list ) = $S->getlist ( $select, $where, $orderby, 0, 5, FALSE );
if ($list) {
while ( $val = $list->fetch_array () ) {
$result [] = seatch_to_array ( $val );
}
$list->free_result ();
$output = $json->encode(array('msg'=>'10001','data'=>$result));
}
echo $output;
output ();
case 'get_dishes':
$sid = trim ( $_GET ['sid'] );
$where = array ();
$where ['s.sid'] = $sid;
$orderby = array (
's.catid' => 'DESC',
's.listorder' => 'DESC'
);
$select = "s.pid,s.sid,s.subject,s.thumb,s.description,s.pageview,s.price,s.catid,c.name ";
list ( , $list ) = $S->getlist ( $select, $where, $orderby, 0, 5, FALSE );
if ($list) {
while ( $val = $list->fetch_array () ) {
$result [] = seatch_to_array ( $val );
}
$list->free_result ();
$output = $json->encode(array('msg'=>'10001','data'=>$result));
}
echo $output;
output ();
default :
redirect ( 'global_op_unkown' );
}
//构造数组
function seatch_to_array(&$val) {
return array (
'sid' => $val ['sid'],
'name' => $val ['c_fullname'],
'thumb' => $val ['c_thumb'],
'dianhua' => $val ['c_dianhua'],
'dizhi' => $val ['c_dizhi'],
'yunye' => $val ['c_yunye']
);
}
//输出为XML文档
function search_to_xml($result) {
if (! $result)
return '';
$content = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
$content .= "<root>\n";
foreach ( $result as $val ) {
$content .= "<subject>\n";
foreach ( $val as $k => $v ) {
$htmlon = preg_match ( "/<[a-z]+\s+.+\\>/i", $v );
$content .= "\t<$k>" . ($htmlon ? '<![CDATA[' : '') . $v . ($htmlon ? ']]>' : '') . "</$k>\n";
}
$content .= "</subject>\n";
}
$content .= "</root>";
return $content;
}
?><file_sep>/core/modules/tuan/admin/templates/hook_usergroup_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<tr>
<td class="altbg1"><strong>允许本组会员发起自助团购:</strong>开启本功能后,本组会员便可以在前台发布的发起自助团购</td>
<td><?=form_bool('access[tuan_post_wish]', $access['tuan_post_wish'])?></td>
</tr><file_sep>/core/modules/album/admin/menus.inc.php
<?php
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$modmenus = array(
array(
'title' => '功能设置',
'album|分类管理|category',
),
array(
'title' => '图库管理',
'item|菜单图库|picture_list|list|cd',
'item|环境图库|picture_list|list|hj',
'item|审核图片|picture_check',
),
);
?><file_sep>/core/modules/tuan/admin/subscibe.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$S =& $_G['loader']->model('tuan:subscibe');
$op = _input('op');
switch($op) {
case 'delete':
$S->delete(_post('ids'));
redirect('global_op_succeed_delete', cpurl($module,$act));
break;
default:
$op = 'list';
$offset = 40;
$start = get_start($_GET['page'], $offset);
$where = array();
if(!$admin->is_founder) $where['city_id'] = $_CITY['aid'];
list($total, $list) = $S->find('*', $where, array('dateline'=>'ASC'), $start, $offset, TRUE);
if($total) {
$multipage = multi($total, $offset, $_GET['page'], cpurl($module, $act, 'list'));
}
$admin->tplname = cptpl('subscibe_list', MOD_FLAG);
}
?><file_sep>/core/modules/mobile/assistant/subject.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
$op = _input('op', null, MF_TEXT);
$F =& $_G['loader']->model('item:favorite');
switch ($op) {
default:
$select = 's.*';
$where = array();
$where['f.uid'] = $user->uid;
$start = get_start($_GET['page'], $offset = 10);
list($total, $list) = $F->find($select,$where, $start, $offset);
$multipage = mobile_page($total, $offset, $_GET['page'], url("mobile/member/ac/$ac/op/$op/page/_PAGE_"));
$reviewcfg = $_G['loader']->variable('config','review');
//ajax
if($_G['in_ajax'] && _input('waterfall')=='Y') {
include mobile_template('member_subject_follow_li');
output();
}
include mobile_template('member_subject_follow');
break;
}<file_sep>/core/modules/tuan/model/sms_class.php
<?php
//被短信接口继承的短信接口继承
class msm_sms_base extends ms_base {
//PHP4构造函数
function msm_sms_base($params) {
$this->__construct($params);
}
//PHP5构造函数
function __construct($params) {
parent::__construct();
//设置帐号
$this->set_account($params);
}
//设置帐号
function set_account($param) {
}
//短信发送,返回 boolean 值
function send($mobile,$message) {
return TRUE;
}
}
?><file_sep>/core/modules/tuan/admin/wish.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$TW =& $_G['loader']->model('tuan:wish');
$op = _input('op');
switch($op) {
case 'delete':
$twids = _input('twids', null);
$TW->delete($twids);
redirect('global_op_succeed_delete', cpurl($module,$act));
break;
case 'update':
$wish = _post('wish');
$TW->update(wish);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'checkup':
$twids = $_POST['twids'];
$TW->checkup($twids);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'edit':
$twid = (int) _get('twid');
if(!$detail = $TW->read($twid)) redirect('tuan_empty');
$admin->tplname = cptpl('wish_save', MOD_FLAG);
break;
case 'save':
if($_POST['do'] == 'edit') {
if(!$twid = (int)$_POST['twid']) redirect(lang('global_sql_keyid_invalid','tid'));
} else {
$twid = null;
}
$post = $TW->get_post($_POST);
$TW->save($post, $twid);
redirect('global_op_succeed', get_forward(cpurl($module,$act),1));
break;
case 'detail':
$twid = (int) _get('twid');
if(!$detail = $T->read($twid)) redirect('tuan_empty');
break;
default:
$op = 'list';
$where = array();
$_GET['status'] = $status = _get('status',0);
if(!$admin->is_founder) {
$_GET['city_id'] = '';
$where['city_id'] = $_CITY['aid'];
} elseif($_GET['city_id']) {
$where['city_id'] = $_GET['city_id'];
}
$where['status'] = $_GET['status'];
if($_GET['uid']) $where['uid'] = $_GET['uid'];
if($_GET['title']) $where['title'] = array('where_like',array('%'.$_GET['title'].'%'));
if($_GET['tid']) $where['tid'] = array('where_more',array('1'));
$_GET['orderby'] = _get('orderby','twid');
$_GET['ordersc'] = _get('ordersc','ASC');
$orderby = array($_GET['orderby'] => $_GET['ordersc']);
$start = get_start($_GET['page'], $_GET['offset']);
list($total, $list) = $TW->find('*', $where, $orderby, $start, $_GET['offset'], TRUE);
if($total) {
$multipage = multi($total, $offset, $_GET['page'], cpurl($module, $act, 'list', $_GET));
}
$admin->tplname = cptpl('wish_list', MOD_FLAG);
}
?><file_sep>/core/modules/modoer/item/admin/templates/tag_add.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/jquery.js"></script>
<script type="text/javascript" src="./static/javascript/item.js"></script>
<script type="text/javascript" src="./static/javascript/autocomplete/jquery.autocomplete.min.js"></script>
<link rel="Stylesheet" href="./static/javascript/autocomplete/jquery.autocomplete.css" />
<script type="text/javascript">
function check_submit() {
if($('[name=tgid]').val()=="") {
alert('选择所属标签组。');
return false;
} else if ($('[name=tagname]').val() == "" ) {
alert('请填写标签名称。');
return false;
}
return true;
}
</script>
<div id="body">
<form method="post" action="<?=cpurl($module,$act,'add')?>" name="myform" onsubmit="return check_submit();">
<div class="space">
<div class="subtitle">添加标签</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1" width="15%">所属标签组:</td>
<td width="75%">
<select name="tgid">
<option value="" selected="selected">==选择标签组==</option>
<?=form_item_taggroup();?>
</select>
</td>
</tr>
<tr>
<td class="altbg1">标签名称:</td>
<td>
<input type="text" name="tagname" class="txtbox" />
</td>
</tr>
</table>
<center>
<input type="submit" value="提交" class="btn"/>
<input type="button" value="返回" class="btn" onclick="window.location='admin.php?module=album&act=category'"/>
</center>
</div>
</form>
</div><file_sep>/test.php
<?php
$arr = array('one'=>array('name'=>'张三','age'=>'23','sex'=>'男'),
'two'=>array('name'=>'李四','age'=>'43','sex'=>'女'),
'three'=>array('name'=>'王五','age'=>'32','sex'=>'男'),
'four'=>array('name'=>'赵六','age'=>'12','sex'=>'女'));
/*
foreach($arr as $k=>$val){
echo $val['name'].$val['age'].$val['sex']."<br>";
}
*/
print_r($arr);
$arr = Array ( [subject] => 仅26元!最高价值100元金逸国际电影城影票1张,含3D [ cityname] => 无锡 [ url] => http://wx.meituan.com/deal/354607.html [ nowprice] => 26 [ oldprice] => 100 [ lasttime] => 1344095999 [ bizname] => 中桥 [ thumb] => http://p1.meituan.net/275.168/deal/201205/31/61_0531174441.jpg [ starttime] => 1338480000 [ nowpeople] => 57471 ) Array ( [subject] => 喜洋洋食府:9-10人套餐,节假日通用。包厢大厅通用。 [ cityname] => 无锡 [ url] => http://wx.meituan.com/deal/871824.html [ nowprice] => 528 [ oldprice] => 888 [ lasttime] => 1344095999 [ bizname] => 锡惠路 [ thumb] => http://p1.meituan.net/275.168/deal/201207/18/0719_0718145833.jpg [ starttime] => 1342627200 [ nowpeople] => 617 ) Array ( [subject] => 粤仔湾:2-4人套餐,节假日通用 [ cityname] => 无锡 [ url] => http://wx.meituan.com/deal/127828.html [ nowprice] => 88 [ oldprice] => 143 [ lasttime] => 1344095999 [ bizname] => 火车站/上马墩 [ thumb] => http://p1.meituan.net/275.168/deal/201207/16/071724_0716202940.jpg [ starttime] => 1342454400 [ nowpeople] => 1841 ) ;
foreach($arr as $key=>$value){
foreach($value as $key2=>$value2){
echo $value[$key2];
}
echo "<br>";
}
?>
<file_sep>/templates/mobile1/coupon_detail_li.htm
{eval
$_HEAD[title] = '店铺优惠';
$_HEAD[description] = $detail[sname];
}
{include mobile_template('header')}
<div class="coupon-detail">
<div class='detail-maininfo'>
<div>
<span class='kun-price-new kun-price-new-bg'>$detail[sname]</span><span class='kun-price'></span>
</div>
</div>
<div class="container">
<div class="panel panel-default item-list">
<div class="panel-heading"><h4>阿果特惠</h4></div>
{get:modoer val=table(table/dbpre_coupons/select/*/where/sid in($detail[sid])/row/10/cachetime/1000)}
<a href="{url coupon/mobile/do/detail/id/$val[couponid]/f/$_GET[f]}/sname/$val[sname]" class="list-group-item no-img">
<div class='kun-comment-row'>
<span class='kun-price-new'>$val[subject]</span>
<!-- <span class='kun-price-new pull-right'>$val[avgprice]</span> -->
</div>
</a>
{/get}
</div>
<div class="panel panel-default item-list">
<div class="panel-heading"><h4>适用商家</h4></div>
{get:modoer val1=table(table/dbpre_subject/select/*/where/sid in($detail[sid])/row/10/cachetime/1000)}
<a href="{url item/mobile/do/detail/id/$val1[sid]}" class="list-group-item no-img">
<h4 class="list-group-item-heading">$val1[name]{if $val1[subname]}($val1[subname]){/if}
{if $val1[tuans]}<i class="igroup">团</i>{/if}
{if $val1[coupons]}<i class="inpromo">券</i>{/if}
{if $val1[credits]}<i class="icard">信</i>{/if}
</h4>
<div class='kun-comment-row row'>
<span class='kun-rank-star irr-star{print get_star2($val1[avgsort])}'>评分</span>
<span class='kun-price pull-right'>$val1[avgprice]元</span>
</div>
<div class='des-dist'>
<span class='descripiton'>{print get_areaname($val1[aid])} {print:item category(catid/$val1[catid])}
</span>
<span class='distance pull-right' id='distance'> </span>
<span class='dist-lat'>$val1[map_lat]</span>
<span class='dist-lng'>$val1[map_lng]</span>
</div>
</a>
{/get}
</div>
</div>
</div>
{include mobile_template('footer')}<file_sep>/core/modules/item/mobile/list.php
<?php
$catid = isset ( $_GET ['catid'] ) ? ( int ) $_GET ['catid'] : ( int ) $MOD ['pid'];
! $catid and location ( url ( 'item/mobile/do/category' ) );
//获取用户当前经纬度
$lat = isset ( $_POST ['lat']) ? ( float ) $_POST ['lat'] : 0;
$lng = isset ( $_POST ['lng'] ) ? ( float ) $_POST ['lng'] : 0;
// if ($_POST['in_ajax']) {
// echo $lat;
// echo $lng;
// }
$plain=false;
if ($_GET['f']==10) {
$plain=true;
}
$op = _input('op');
// 实例化主题类
$S = & $_G ['loader']->model ( 'item:subject' );
$S->get_category ( $catid );
if (! $pid = $S->category ['catid']) {
location ( url ( 'item/mobile/do/category' ) );
}
//查询条件
$where = array ();
$where['city_id'] = array(8);
if ($_GET['finer_level']) {
$finer_level = $_GET['finer_level'];
$where['finer'] = array('where_more',array($finer_level));
// print_r($where['finer']);
} else {
$where['finer'] = array('where_more',array(100));
}
//$where['status'] = array('where_not_equal',array('0'));
//区域信息
$sonaid='';
$aid = ( int ) $_GET ['aid'];
$areas = $_G ['loader']->variable ( 'area_8', null, false );
// print_r($areas);
if($aid==0){
$sel_aid='全部商区';
}else{
//统一使用区域的子区域查询
$paid=$areas[$aid]['pid'];
$sel_aid=$areas[$aid]['name'];
// print_r($areas);
//顶级区划
if($paid==8){
foreach($areas as $area){
if($area[pid]==$aid){
$sonaid=$sonaid.$area[aid].',';
}
}
}else{
$sonaid=$aid;
}
$where['aid'] = explode(',',$sonaid);
}
//统一使用子分类信息查询
$soncatid='';
if($catid==0){
$sel_catid='美食';
}else{
//顶级分类
$topcats=array(1,19,22,23,24);
if(in_array($catid, $topcats)){
$cats = $_G ['loader']->variable ( 'category','item');
$soncatid=$cats[$catid]['subcats'];
$sel_catid=$cats[$catid]['name'];
}else{
$soncatid=$catid;
$temp = & $_G ['loader']->model ( 'item:category' );
$aa=$temp->read($catid);
$sel_catid=$aa['name'];
}
// $where['catid'] = explode(',',$soncatid);
// $where['catid'] = array('where_in',array(0,1,2,3,4));
}
//排序条件
$orderby = isset ( $_GET ['px'] ) ? $_GET ['px'] : 'finer';
$order_arr = array (
'finer' => array ('s.finer' => 'DESC','distance' => 'ASC'),
'distance' => array ('distance' => 'ASC','s.finer' => 'DESC'),
'addtime' => array ('addtime' => 'DESC','distance' => 'ASC'),
'pageviews' => array ('pageviews' => 'DESC','distance' => 'ASC')
);
//获取排序名称
if($orderby=='finer'){
$ordername='按推荐度';
}elseif($orderby=='distance'){
$ordername='按距离';
}elseif($orderby=='pageviews'){
$ordername='按浏览量';
}else{
$ordername='默认排序';
}
//查询数据
//$lat=120.358537;
//$lng=31.546392;
$num = 1000;
$offset = $num;
$start = get_start($_GET['page'], $num);
$select="sf.sid,s.pid,s.catid,s.aid,s.name,s.subname,s.best,s.finer,s.map_lng,s.map_lat,s.fullname,s.status,s.pageviews,s.avgsort,s.avgprice,s.coupons,s.credits,s.tuans,round((6371*acos(cos(radians($lat))*cos(radians( map_lat))*cos(radians(map_lng)-radians($lng))+sin(radians($lat))*sin(radians(map_lat)))),3) AS distance";
list ( $total, $list ) = $S->getlist ( $pid, $select, $where, $order_arr [$orderby], $start, $num, true );
if($total) {
$multipage = mobile_page($total, $num, $_GET['page'], url("item/mobile/do/list/catid/$catid/aid/$aid/order/$order/type/$type/finer_level/$finer_level/num/$num/total/$total/page/_PAGE_"));
}
if ($plain) {
} else {
//根据aid进行分组
$listgroup = array();
// $listlength = $list->fetch_lengths();
// print_r($listlength);
for ($i=0; $i<$total; $i++) {
$row = $list->fetch_array();
if (!$listgroup[$row['aid']]) {
$listgroup[$row['aid']] = array();
$listgroup[$row['aid']]['aid'] = $row['aid'];
$listgroup[$row['aid']]['name'] = $areas[$row['aid']]['name'];
$amappoint = explode(',', $areas[$row['aid']]['mappoint']);
$listgroup[$row['aid']]['distance'] = get_mydist($amappoint[0],$amappoint[1]);
$listgroup[$row['aid']]['shops'] = array();
}
array_push($listgroup[$row['aid']]['shops'],$row);
}
// print_r($listgroup);
$listgroup = array_sort($listgroup, 'distance','asc');
}
//显示模版
if($_G['in_ajax'] && _input('waterfall')=='Y') {
if ($plain) {
$tplname = 'item_list_li_ajax_plain';
} else {
$tplname = 'item_list_li_ajax';
//echo $lat;
//echo $lng;
}
} else {
$tplname = 'item_list';
}
include mobile_template($tplname);
//根据键值排序
function array_sort($arr, $keys, $type = 'desc') {
$keysvalue = $new_array = array();
foreach ($arr as $k => $v) {
$keysvalue[$k] = $v[$keys];
}
if ($type == 'asc') {
asort($keysvalue);
} else {
arsort($keysvalue);
}
reset($keysvalue);
foreach ($keysvalue as $k => $v) {
$new_array[$k] = $arr[$k];
}
return $new_array;
}
//自定义排序
function sortByDistance($a, $b) {
if (strlen($a['distance']) == strlen($b['distance'])) {
return 0;
} else {
return (strlen($a['distance']) > strlen($b['distance'])) ? 1 : -1;
}
}
// 解析Tags
function get_mytag($val) {
global $S;
return $S->get_mytag ( $val );
}
// 解析Att
function get_myatt($val) {
global $S;
return $S->get_myatt ( $val );
}
// 解析坐标
function get_mydist($lat2,$lng2) {
global $lat,$lng;
//echo $lat.' ';
//echo $lng;
if ($lat == 0) {
return 0;
}
else {
return get_distance($lng,$lat,$lng2,$lat2);
}
}
/*
* SELECT sid, fullname,round(( 6371 * acos( cos( radians(120.358537) ) * cos( radians( map_lat ) ) * cos( radians( map_lng ) - radians(31.546392) ) + sin( radians(120.358537) ) * sin( radians( map_lat ) ) ) ),3) AS distance FROM ms_subject HAVING distance < 2 ORDER BY distance LIMIT 0 , 500;
*
*/
?>
<file_sep>/core/modules/tuan/admin/templates/order_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="post" action="<?=cpurl($module,$act)?>" name="myform">
<div class="space">
<div class="subtitle">订单管理(<?=$tuan[subject]?>)</div>
<ul class="cptab">
<li><a href="<?=cpurl($module,'tuan','detail',array('tid'=>$tid))?>">团购详情</a></li>
<?foreach(lang('tuan_order_status') as $k => $v):?>
<li<?=$_GET['status']==$k?' class="selected"':''?>><a href="<?=cpurl($module,$act,'list',array('tid'=>$tid,'status'=>$k))?>"><?=$v?></a></li>
<?endforeach;?>
</ul>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y">
<tr class="altbg1">
<td width="25">选?</td>
<td width="60">订单号</td>
<td width="80">已支付价格</td>
<?if($_GET['status']=='payed'):?>
<td width="80">最终价格</td>
<td width="100">需退还的差价</td>
<?endif;?>
<td width="100">下单会员/手机号</td>
<td width="60">购买数量</td>
<td width="80">下单时间</td>
<?if($_GET['status']=='payed'):?>
<td width="80">交易时间</td>
<?endif;?>
<?if($tuan['sendtype']=='express' && $status=='payed'):?>
<td width="80">发货状态</td>
<?endif;?>
<td width="150">操作</td>
</tr>
<?if($total):?>
<?while($val=$list->fetch_array()) {?>
<tr>
<td><input type="checkbox" name="oids[]" value="<?=$val['oid']?>" /></td>
<td><?=$val['oid']?></td>
<td>
¥<?=$val['price']?>
<?if($val['ex_point']):?><div class="font_1"><?=display('member:point',"point/$val[ex_pointtype]")?>抵换¥<?=$val['ex_price']?></div><?endif;?>
</td>
<?if($_GET['status']=='payed'):?>
<td>¥<?=$val['pay_price']?></td>
<td>
<div>¥<?=$val['balance_price']?></div>
<?if($val['balance_price']!=0):?>
<div>
<?if($val['return_balance_time']>0):?>
已 <?=date('Y-m-d H:i', $val['return_balance_time'])?> 退换差价
<?else:?>
尚未退还差价
<?endif;?>
</div>
<?endif;?>
</td>
<?endif;?>
<td><a href="<?=url("space/index/uid/$val[uid]")?>" target="_blank"><?=$val['username']?></a><br /><?=$val['mobile']?></td>
<td><?=$val['num']?></td>
<td><?=date('Y-m-d', $val['dateline'])?><br /><?=date('H:i:s', $val['dateline'])?></td>
<?if($_GET['status']=='payed'):?>
<td><?=date('Y-m-d', $val['exchangetime'])?><br /><?=date('H:i:s', $val['exchangetime'])?></td>
<?endif;?>
<?if($tuan['sendtype']=='express' && $val['status']=='payed'):?>
<td><?=$goods_status[$val['good_status']]?></td>
<?endif;?>
<td>
<?if($tuan['sendtype']=='express' && $val['status']=='payed'):?>
<a href="<?=cpurl($module,$act,'detail', array('oid'=>$val['oid']))?>">发货处理</a>
<?endif;?>
<?if($val['status']=='new'):?>
<a href="<?=cpurl($module,$act,'cancel', array('oid'=>$val['oid']))?>" onclick="return confirm('您确定要取消本订单吗?');">取消</a></br />
<a href="<?=cpurl($module,$act,'localpay', array('oid'=>$val['oid']))?>" onclick="return confirm('您确定要本订单已经线下付款了吗?');">已线下付款</a>
<?elseif($val['status']=='payed'):?>
<a href="<?=cpurl($module,$act,'refund', array('oid'=>$val['oid']))?>" onclick="return confirm('您确定要返还本订单交易额给支付会员吗?');">全额退款</a>
<?endif?>
</td>
</tr>
<?}?>
<?else:?>
<tr>
<td colspan="10">暂无信息</td>
</tr>
<?endif;?>
</table>
</div>
<div><?=$multipage?></div>
<center>
<input type="hidden" name="op" value="update" />
<input type="hidden" name="dosubmit" value="yes" />
<?if($total):?>
<button type="button" class="btn" onclick="easy_submit('myform','delete','oids[]');">删除所选</button>
<?endif;?>
<input type="button" class="btn" value="返回" onclick="document.location='<?=cpurl($module,'tuan')?>';" />
</center>
</form>
</div><file_sep>/templates/item/vip/pic.php
<?exit?>
<!--{eval
$_HEAD['title'] = $subject[name].$subject[subname] . '的相册图片浏览';
}-->
<!--{template 'header', 'item', $subject[templateid]}-->
<style type="text/css">@import url("{URLROOT}/img/vipfiles/css/gallery.css");</style>
<script type="text/javascript" src="{URLROOT}/static/javascript/jquery.ad-gallery.pack.js"></script>
<script type="text/javascript">
$(function() {
var galleries = $('.ad-gallery').adGallery();
$('#switch-effect').change(
function() {
galleries[0].settings.effect = $(this).val();
return false;
}
);
$('#toggle-slideshow').click(
function() {
galleries[0].slideshow.toggle();
return false;
}
);
$('#toggle-description').click(
function() {
if(!galleries[0].settings.description_wrapper) {
galleries[0].settings.description_wrapper = $('#descriptions');
} else {
galleries[0].settings.description_wrapper = false;
}
return false;
}
);
});
</script>
<link href="{URLROOT}/img/vipfiles/css/shopEx_$subject[c_vipstyle].css" rel="stylesheet" type="text/css" />
<body>
<div class="wrap">
<div id="header">
<div id="crumb">
<p id="crumbL"><a href="{url modoer/index}">首页</a> » {print implode(' » ', $urlpath)} » $subject[name] $subject[subname]
<p id="crumbR"><a href="javascript:post_log($subject[sid]);">补充信息</a> | <a href="{url item/member/ac/subject_add/subbranch_sid/$subject[sid]}">增加分店</a> | <a href="{url member/index}">管理本店</a></p>
</div>
<div id="shopBanner">
<h1>$subject[name] $subject[subname]</h1>
<p>
<!--{if $subject[c_add]}-->
<B>地址:</B></LABEL>$subject[c_add]
<!--{/if}-->
<!--{if $subject[c_tel]}-->
<B>电话:</B></LABEL>$subject[c_tel]</p>
<!--{/if}-->
<div class="headerPic">
<img src="{if $subject[c_vipbanner]}$subject[c_vipbanner]{else}{URLROOT}img/haibao/nonbanner.png{/if}" alt="$subject[name] $subject[subname]店铺海报" width="950" height="150"/>
</div>
</div>
<div id="nav">
<ul>
<!--
<li><a href="#"><span>Array</span></a></li>
<li><a href="#"><span></span></a></li>
<li class="special"><a href="#"><span>导航栏介绍</span></a></li>
-->
<li><a href="{url item/detail/id/$subject[sid]}"><span>首页</span></a></li>
<li><a href="{url article/list/sid/$sid}"><span>店铺资讯</span></a> </li>
<li><a href="{url fenlei/list/sid/$sid}"><span>诚聘英才</span></a> </li>
<li><a href="{url product/list/sid/$sid}"><span>产品展厅</span></a> </li>
<li><a href="{url coupon/list/sid/$sid}"><span>优惠打折</span></a> </li>
<li class="current" ><a href="{url item/pic/sid/$subject[sid]}"><span>商家相册</span></a> </li>
<li><a href="{url item/vipabout/id/$subject[sid]}"><span>关于我们</span></a></li>
<li><a href="{url item/vipreview/id/$subject[sid]}"><span>会员点评</span></a></li>
<li><a href="{url item/vipguestbook/id/$subject[sid]}"><span>留言板</span></a></li>
</ul>
</div>
</div>
<div id="smartAd"><img src="{if $subject[c_vipbanner2]}$subject[c_vipbanner2]{else}{URLROOT}img/haibao/non.png{/if}" alt="$subject[name] $subject[subname]店铺海报"/></a><br />
</div>
<div id="mainBody">
<div id="mainBodyL">
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>【$subject[name] $subject[subname]】</h2>
<p class="deafBoxTitMore"><a href="{url item/vipabout/id/$subject[sid]}">更多</a></p>
</div>
<div class="deafBoxCon">
<dl>
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td align="center" valign="middle">
<a href="{url item/pic/sid/$subject[sid]}"><img src="{URLROOT}/{if $subject[thumb]}$subject[thumb]{else}static/images/noimg.gif{/if}" alt="$subject[name]" width="270" height="200" /></a>
</td>
</tr>
</table>
<div class="leftnr">
<!--{if $subject[finer]}-->
店铺级别:<img src="{URLROOT}/img/vipfiles/img/vip$subject[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<div class="subject">
<h2><a href="{url item/detail/id/$sid}" src="$subject[thumb]" onMouseOver="tip_start(this,1);">$subject[name] $subject[subname]</a></h2>
<!--{eval $reviewcfg = $_G['loader']->variable('config','review');}-->
<p class="start start{print get_star($subject[avgsort],$reviewcfg[scoretype])}"></p>
<table class="subject_field_list" border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2"><span class="font_2">$subject[reviews]</span>点评,
<span class="font_2">$subject[guestbooks]</span>留言,
<span class="font_2">$subject[pageviews]</span>浏览</td>
</tr>
$subject_field_table_tr
</table>
<a class="abtn1" href="{url review/member/ac/add/type/item_subject/id/$subject[sid]}"><span>我要点评</span></a>
<a class="abtn2" href="javascript:add_favorite($sid);"><span>收藏</span></a>
<a class="abtn2" href="{url item/detail/id/$sid/view/guestbook}#guestbook"><span>留言</span></a>
<div class="clear"></div>
</dl>
</div>
</div>
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>【$subject[name] $subject[subname]其他相册】</h2>
<p class="deafBoxTitMore"><a href="{url item/pic/sid/$subject[sid]}">更多</a></p>
</div>
<div class="deafBoxCon">
<!--{get:item val=album(sid/$subject[sid]/orderby/pageview DESC/rows/10/cachetime/3600)}-->
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td valign="top">
<a href="{url item/album/id/$val[albumid]}"><img src="{URLROOT}/{if $detail[thumb]}$detail[thumb]{else}static/images/noimg.gif{/if}" alt="$detail[name]" width="110" height="80" /></a>
</td>
<td valign="top">
相册名称:<a href="{url item/album/id/$val[albumid]}">$val[name]</a><br />
照片数量:$val[num]张<br />
最后更新:{date $val[lastupdate],'Y年-m月-d日'}
</td>
</tr>
</table>
<!--{/get}-->
</div></div>
<div id="position" class="deafBox">
<div class="deafBoxTit">
<h2>商户所在位置</h2>
</div>
<div class="deafBoxCon">
<!--{eval $mapparam = array(
'width' => '270',
'height' => '265',
'title' => $subject[name] . $subject[subname],
'show' => $subject[mappoint]?1:0,
);}-->
<iframe id="item_map" src="{url index/map/width/270/height/150/title/$mapparam[title]/p/$subject[mappoint]/show/$mapparam[show]}" frameborder="0" scrolling="no"></iframe>
<div align="center"> <span><!--{if !$subject['mappoint']}--><a href="javascript:post_map($subject[sid], $subject[pid]);">地图未标注,我来标注</a><!--{else}--><a href="javascript:show_bigmap();">查看大图</a> <a href="javascript:post_map($subject[sid], $subject[pid]);">报错</a><!--{/if}--></span></div>
<script type="text/javascript">
function show_bigmap() {
var src = "{url index/map/width/600/height/400/title/$mapparam[title]/p/$subject[mappoint]/show/$mapparam[show]}";
var html = '<iframe src="' + src + '" frameborder="0" scrolling="no" width="100%" height="400" id="ifupmap_map"></iframe>';
dlgOpen('查看大图', html, 600, 450);
}
</script>
</div>
</div>
</div>
<div id="chaBodyR">
<div id="chaBodyRTit">
<h2>相册详情</h2>
</div>
<div class="listCon">
<div id="gallery" class="ad-gallery">
<div class="ad-image-wrapper">
</div>
<div class="ad-controls">
</div>
<div class="ad-nav">
<div class="ad-thumbs">
<ul class="ad-thumb-list">
{eval $index=0;}
{dbres $list $val}
<li>
<a href="{URLROOT}/$val[filename]"><img src="{URLROOT}/$val[thumb]" class="image{$index}" title="$val[title] / $val[username] / {date $val[addtime],'Y-m-d'}" alt="$val[comments]" longdesc="$val[url]"></a>
</li>
{eval $index++;}
{/dbres}
</ul>
</div>
</div>
</div>
<!--{if check_module('comment')}-->
<div class="comment_foo">
<style type="text/css">@import url("{URLROOT}/{$_G[tplurl]}css_comment.css");</style>
<script type="text/javascript" src="{URLROOT}/static/javascript/comment.js"></script>
<!--{eval $comment_modcfg = $_G['loader']->variable('config','comment');}-->
<!--{if $detail[comments]}-->
<!--{/if}-->
<a name="comment"></a>
{eval $_G['loader']->helper('form');}
<div id="comment_form">
<!--{if $user->check_access('comment_disable', $_G['loader']->model(':comment'), false)}-->
<!--{if $MOD[album_comment] && !$comment_modcfg['disable_comment']}-->
<!--{eval $idtype = 'album'; $id = $albumid; $title = 'Re:' . $detail[name];}-->
{template comment_post}
<!--{else}-->
<div class="messageborder">评论已关闭</div>
<!--{/if}-->
<!--{else}-->
<div class="messageborder">如果您要进行评论信息,请先 <a href="{url member/login}">登录</a> 或者 <a href="{url member/reg}">快速注册</a> 。</div>
<!--{/if}-->
</div>
<!--{if !$comment_modcfg['hidden_comment']}-->
<div class="mainrail rail-border-3">
<em>评论总数:<span class="font_2">$detail[comments]</span>条</em>
<h1 class="rail-h-3 rail-h-bg-3">网友评论</h1>
<div id="commentlist" style="margin-bottom:10px;"></div>
<script type="text/javascript">
$(document).ready(function() { get_comment('album',$albumid,1); });
</script>
</div>
<!--{/if}-->
</div>
<!--{/if}-->
</div>
<div class="clear"></div>
</div>
<!--{template 'footer', 'item', $subject[templateid]}--><file_sep>/index.php
<?php
/**
* ===========================================
* Project: Modoer(Mudder)
* Version: 2.9
* Time: 2007-7-17 @ Create
* Copyright (c) 2007 - 2012 Moufer Studio
* Website: http://www.modoer.com
* Developer: Moufer
* E-mail: <EMAIL>
* ===========================================
* @author moufer<<EMAIL>>
* @copyright Moufer Studio(www.modoer.com)
*/
if(!is_file(dirname(__FILE__).'/data/install.lock')) {
exit('<a href="install.php">Unsure whether the system of Modoer has been installed or not.</a><br /><br />If it has already been installed,under the folder of ./data , please create a new empty file named as "install.lock".');
}
//application init
require dirname(__FILE__).'/core/init.php';
if($_G['cfg']['index_module'] && $_GET['m']=='index' && $_GET['act']=='index') {
unset($_GET['m'], $_GET['act']);
}
if($_G['cfg']['index_module'] && !isset($_GET['m']) && !isset($_GET['act'])) {
$m = _get('m', null, '_T');
if(!$m || !preg_match("/^[a-z]+$/", $m)) {
$m = $_G['cfg']['index_module'];
if(strposex($m, '/')) list($m,$_GET['act']) = explode('/', $m);
} else {
$m = 'index';
}
} else {
$m = _get('m', 'index', '_T');
}
//当前传入的模块名是什么
if($m && $m != 'index') {
//如果模板存在则读取common文件
if(check_module($m)) {
$f = $m . DS . 'common.php';
if(!file_exists(MUDDER_MODULE . $f)) show_error(lang('global_file_not_exist', ('./core/modules/' . $f)));
include MUDDER_MODULE . $f;
} else {
http_404();
}
} else {
if($_GET['unkown_city_domain'] && !$_G['in_ajax']) http_404();
if(!$_CITY && (!$_GET['act']||$_GET['act']=='index')) {
//First visit
if(!$_S_CITY = get_single_city()) {
include MUDDER_CORE . 'modules' . DS . 'modoer' . DS . 'city.php';
exit;
//location('index.php?act=city');
}
init_city($_S_CITY['aid']);
$_CITY = $_S_CITY;
unset($_S_CITY);
}
if(empty($_GET['city_domain']) && !$_GET['act'] && $_CFG['model_city_sldomain']) {
location(get_city_domain($_CITY['aid']));
}
// echo "erererrerer";
//允许直接执行的方法
$_G['m'] = $m = 'index';
$acts = array('ajax','map','seccode','js','search','announcement','city','upload','mobile');
if(isset($_GET['act']) && in_array($_GET['act'], $acts)) {
include MUDDER_CORE . 'modules' . DS . 'modoer' . DS . $_GET['act'] . '.php';
exit;
} elseif(!$_GET['act'] || $_GET['act'] == 'index') {
//page name
define('SCRIPTNAV', 'index');
//load template
include template('index');
} else {
http_404();
}
}
?><file_sep>/core/modules/item/mobile/wmlist.php
<?php
$catid = isset($_GET['catid']) ? (int)$_GET['catid'] : (int)$MOD['pid'];
!$catid and location(url('item/mobile/do/category'));
$op = _input('op');
// 实例化主题类
$D = & $_G ['loader']->model ( 'item:takeout' );
//地理信息
$aid = ( int ) $_GET ['aid'];
// 载入地区
$area = $_G ['loader']->variable ( 'area_' . $_CITY ['aid'], null, false );
// 地区名称
$name = $area [$aid] ['name'];
// 查询的数组
$order_arr = array (
'listorder' => array ('s.c_listorder' => 'ASC'),
'addtime' => array ('addtime' => 'DESC'),
'pageviews' => array ('pageviews' => 'DESC')
);
$orderby='finer';
//查询条件
$where = array ();
$where['city_id'] = array(8);
$where['td.tagname'] = $name;
$where['status'] = array('where_not_equal',array('0'));
//进入筛选页面
if ($op == 'filter') {
include mobile_template('item_list_filter');
exit;
}
//显示模版
$tplname = 'item_waimai_list';
//查询数据
$num = 10;
$offset = $num;
$start = get_start($_GET['page'], $num);
$select="sf.sid,sf.content,sf.c_dianhua,sf.c_dizhi,sf.c_yunye,sf.c_minprice,sf.c_sendprice,sf.c_minprice,sf.c_range,sf.c_jianjie,s.aid,s.pid,s.catid,s.name,s.subname,s.best,s.finer,s.map_lng,s.map_lat,s.fullname,s.status,s.pageviews";
list ( $total, $list ) = $D->find ($select, $where, $start, $num);
if($total) {
$multipage = mobile_page($total, $num, $_GET['page'], url("item/mobile/do/wmlist/catid/$catid/aid/$aid/order/$order/type/$type/att/$atturl/num/$num/total/$total/page/_PAGE_"));
}
include mobile_template($tplname);
<file_sep>/core/modules/tuan/mobile/list.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'tuan');
// 实例化主题类
$T = & $_G ['loader']->model ( 'tuan:tuandh' );
//获取优惠方式
if(isset($_GET['catid1'])) $catid1 = (int) $_GET['catid1'];
if($catid1==0) unset($catid1);
//获取优惠类
if(isset($_GET['catid'])) $catid = (int) $_GET['catid'];
//if($catid==0) $catid=1;//默认为美食
$cats = $_G ['loader']->variable ( 'category','tuan');
//查询条件
$where = array ();
//$where['c.city_id'] = array(8);
//$where['status'] = array('where_not_equal',array('0'));
//$where['c.status'] = 1;
//区域信息
$sonaid='';
$aid = ( int ) $_GET ['aid'];
if($aid==0){
$sel_aid='全部商区';
}else{
//统一使用区域的子区域查询
$areas = $_G ['loader']->variable ( 'area_' . $_CITY ['aid'], null, false );
$paid=$areas[$aid]['pid'];
$sel_aid=$areas[$aid]['name'];
//顶级区划
if($paid==8){
foreach($areas as $area){
if($area[pid]==$aid){
$sonaid=$sonaid.$area[aid];
}
}
}else{
$sonaid=$aid;
}
//$where['s.aid'] = explode(',',$sonaid);
}
//统一使用子分类信息查询
$soncatid='';
if($catid==0){
$sel_catid='美食';
}else{
//顶级分类
$topcats=array(1,19,22,23,24);
if(in_array($catid, $topcats)){
$cats = $_G ['loader']->variable ( 'category','tuan');
$soncatid=$cats[$catid]['subcats'];
$sel_catid=$cats[$catid]['name'];
}else{
$soncatid=$catid;
$temp = & $_G ['loader']->model ( 'tuan:category' );
$aa=$temp->read($catid);
$sel_catid=$aa['name'];
}
//$where['catid'] = explode(',',$soncatid);
}
//查询数据
$num = 10;
$offset = $num;
$start = get_start($_GET['page'], $num);
// $offset = $MOD['listnum'] > 0 ? $MOD['listnum'] : 10;
// $start = get_start($_GET['page'], $offset);
//list ( $total, $list ) = $T->getlist2 ( 1, $catid, $aid, $start, $offset );
list ( $total, $list ) = $T->getlist2 ( 1, 1, 13, $start, $offset );
//分页
if($total)
$multipage = mobile_page($total, $num, $_GET['page'], url("tuan/mobile/do/list/catid/$catid/aid/$aid/order/$order/num/$num/total/$total/page/_PAGE_"));
//排序条件
$orderby = isset ( $_GET ['px'] ) ? $_GET ['px'] : 'finer';
$order_arr = array (
'finer' => array ('s.finer' => 'DESC'),
'listorder' => array ('s.c_listorder' => 'ASC'),
'addtime' => array ('addtime' => 'DESC'),
'pageviews' => array ('pageviews' => 'DESC')
);
//获取排序名称
if($orderby=='finer'){
$ordername='默认排序';
}elseif($orderby=='listorder'){
$ordername='按评分从高到底';
}elseif($orderby=='pageviews'){
$ordername='按评分从低到高';
}else{
$ordername='默认排序';
}
//模版切换
$op = _input('op');
//进入筛选页面
if ($op == 'filter') {
include mobile_template('tuan_list_filter');
exit;
}
//显示模版
if($_G['in_ajax'] && _input('waterfall')=='Y') {
$tplname = 'tuan_list_li';
} else {
$tplname = 'tuan_list';
}
include mobile_template($tplname);
// 解析区划名称
function get_aname($val) {
global $areas;
return $areas[$val]['name'];;
}
// 解析分类名称
function get_cname($val) {
global $cats;
return $cats[$val]['name'];
}
?>
<file_sep>/core/modules/tuan/sms.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
$op = _input('op');
switch($op) {
case 'send':
$_G['loader']->helper('misc','tuan');
$SMS =& misc_tuan::get_sms_class($MOD);
if($result = $SMS->send(_post('mobile'),_post('message','','trim'))) {
redirect('tuan_sms_send_succeed');
} else {
redirect('tuan_sms_send_lost');
}
break;
default:
redirect('global_op_unkown');
}
?><file_sep>/core/modules/fenlei/admin/templates/fenlei_check.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');?>
<div id="body">
<form method="post" name="myform" action="<?=cpurl($module,$act)?>">
<div class="space">
<div class="subtitle">分类管理</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr class="altbg1">
<td width="30">选</td>
<td width="*">名称</td>
<td width="120">分类</td>
<td width="150">地区</td>
<td width="80">发布者</td>
<td width="80">联系人</td>
<td width="120">发布时间</td>
<td width="60">操作</td>
</tr>
<?if($total) : while($val=$list->fetch_array()) :?>
<tr>
<td><input type="checkbox" name="fids[]" value="<?=$val['fid']?>" /></td>
<td><?=$val['subject']?></td>
<td><?=$F->category[$val['catid']]['name']?></td>
<td><?=$area[$val['aid']]['name']?></td>
<td><?=$val['username']?></td>
<td><?=$val['linkman']?></td>
<td><?=date('Y-m-d H:i', $val['dateline'])?></td>
<td><a href="<?=cpurl($module,$act,'edit',array('fid'=>$val['fid']))?>">编辑</a></td>
</tr>
<?endwhile; $list->free_result();?>
<tr class="altbg1">
<td colspan="4"><button type="button" class="btn2" onclick="checkbox_checked('fids[]');">全选</button> </td>
<td colspan="4"><?=$multipage?></td>
</tr>
<? else: ?>
<tr><td colspan="8">没有找到任何信息。</td></tr>
<?endif;?>
</table>
<?if($list) :?>
<center>
<input type="hidden" name="dosubmit" value="yes" />
<input type="hidden" name="op" value="check" />
<button type="button" class="btn" onclick="easy_submit('myform','checkup','fids[]');" />审核所选</button>
<button type="button" class="btn" onclick="easy_submit('myform','delete','fids[]');" />删除所选</button>
</center>
<?endif;?>
</div>
</form>
</div><file_sep>/core/modules/mobile/login.php
<?php
$op = _input('op', null);
switch ($op) {
case 'logout':
$user->logout();
location(url('mobile/index'));
break;
default:
$forward = _get('forward', url('mobile/index'));
if($user->isLogin) {
location(url('mobile/index'));
}
if($_POST) {
$forward = _input('forward', url('mobile/index'), 'base64_decode');
if(!$sync = $user->login($_POST['username'], $_POST['password'], $_POST['life'])) {
redirect('member_login_lost');
} else {
if(!$forward) $forward = url('mobile/index');
location($forward);
exit;
}
} else {
include mobile_template('login');
}
}
?><file_sep>/core/version.php
<?php
$_G['modoer'] = array();
$_G['modoer']['name'] = 'Modoer';
$_G['modoer']['version'] = '2.9 MC Beta';
$_G['modoer']['build'] = '20120524';
$_G['modoer']['url'] = 'http://www.modoer.com';<file_sep>/core/modules/item/wmdetail.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
$I = & $_G ['loader']->model ( MOD_FLAG . ':takeout' );
$sid = ( int ) $_GET ['sid'];
if (! $sid)
redirect ( lang ( 'global_sql_keyid_invalid', 'id' ) );
// 取得主题信息
if ($sid) {
$detail = $I->read ( $sid );
} else {
http_404 ();
}
if (! $detail || ! $detail ['status']) {
redirect ( 'item_empty' );
}
// 计算商家菜品总数
$P = & $_G ['loader']->model ( ':product' );
$detail ['pronums'] = $P->get_subject_total ( $sid );
// 解析配送范围
$S = & $_G ['loader']->model ( 'item:subject' );
$ranages= $S->get_mytag ( $detail ['c_range'] );
/*
$A = & $_G ['loader']->model ( 'area' );
$aids = explode ( ',', $detail ['c_range'] );
if (is_array ( $aids )) {
foreach ( $aids as $aid ) {
if ($aid != '') {
$area = $A->read ( $aid );
$ranages [$aid] = $area ['name'];
$area = '';
}
}
}
*/
// 加入COOKIE
// $I->write_cookie ( $detail );
$_HEAD ['title'] = $detail['fullname'].'外卖'.$detail['fullname'].'外卖菜单'.'无锡美食网,无锡外卖网';
$_HEAD ['keywords'] = $detail['fullname'].'外卖'.$detail['fullname'].'外卖菜单'.'无锡美食网,无锡外卖网';
$_HEAD ['description'] = $detail['fullname'].'外卖'.$detail['fullname'].'外卖菜单'.'无锡美食网,无锡外卖网';
define ( 'SUB_NAVSCRIPT', 'item/wmdetail' );
// 载入模型的内容页模板
include template ( 'item_waimai_detail' );
?>
<file_sep>/img/shopimg/effect_common.js
/*slightbox
[cosa] edit 08-12-23
obj:需要运用效果的对象[jquery选择器]
oclose:对象中的关闭按钮[jquery选择器]
opacity:覆盖背景不透明度
ctime:对象自动关闭时间
*/
function slightbox(obj,oclose,opacity,ctime){
var _this = this;
_this.d = $(obj);
var mkdiv = document.createElement("div");
_this.cenvelop = function(){
$(mkdiv).css({"position":"absolute","z-index":"9998","left":"0","top":"0","right":"0","width":"100%","background":"#000000"});
$("body").append($(mkdiv));
if(opacity){$(mkdiv).css("opacity",opacity);}else{$(mkdiv).css("opacity","0.4");}
_this._resize();
}
_this._resize = function(){
$(mkdiv).css("height",Math.max(document.documentElement.scrollHeight,document.documentElement.clientHeight) + "px");
$(mkdiv).css("width",document.documentElement.clientWidth + "px");
var _x = Math.round((document.documentElement.clientWidth-this.d.width())/2);
var _y = Math.round((document.documentElement.clientHeight-this.d.height())/2);
_this.d.css({"position":"absolute","zIndex":"9999","left":_x+"px","top":_y+"px"});
}
_this.closed = function(){
$(mkdiv).remove();
_this.d.remove();
return false;
}
var sctop = 0;
$(window).resize(function(){
_this._resize();
});
var top = (document.documentElement.clientHeight-this.d.height())/2;
$(window).scroll(function(){
$(obj).css("top",document.documentElement.scrollTop - sctop + top + "px");
sctop = document.documentElement.scrollTop;
top = parseInt($(obj).css("top"));
});
if(ctime){
setTimeout(_this.closed, ctime)
}
$(oclose).click(function(){_this.closed();})
_this.cenvelop();
}
//新窗口提示[winopentips()]
function winopentips(){
var od = document.createElement("img");
$(od).css({position:"absolute",top:"0",left:"0",visibility:"hidden",zIndex:"-2",width:"12px",height:"12px"});
$(od).attr({id:"hoverimg",src:"http://www.smxby.cn/img/shopimg/index/f02812.gif",width:"12px",height:"12px"});
$("body").append(od);
$("a").mouseover(function(){
if($(this).attr("target") == "_blank"){
$(this).mousemove(function(event){
var _w = $(this).width();
var _h = $(this).height();
$("#hoverimg").css({visibility:"visible",zIndex:"100"});
if($.browser.msie){$(od).css({left:event.clientX+12+"px",top:event.clientY+document.documentElement.scrollTop+15+"px"})}
if($.browser.mozilla){$(od).css({left:event.pageX+15+"px",top:event.pageY+17+"px"})}
})
}
}).mouseout(function(){
$("#hoverimg").css("visibility","hidden");
});
}
//滚动
function simplescroll(c, config) {
this.config = config ? config : {start_delay:0000, speed: 23, delay:3000, direction:1 , scrollItemCount:1, movecount:1};
this.container = document.getElementById(c);
this.pause = false;
var _this = this;
this.init = function() {
var d = _this.container;
_this.scrollTimeId = null;
if(_this.config.direction == 2 || _this.config.direction == 4){
var di = document.createElement("div");
var size = d.getElementsByTagName('li').length;
var _width = d.getElementsByTagName('li')[0].offsetWidth;
var _height = d.getElementsByTagName('li')[0].offsetHeight;
di.innerHTML = d.innerHTML;
d.innerHTML ="";
di.style.width = size*_width+"px";
d.appendChild(di);
}
setTimeout(_this.start,_this.config.start_delay);
}
this.start = function() {
var d = _this.container;
if(_this.config.direction == 1 || _this.config.direction == 3){
var line_height = d.getElementsByTagName('li')[0].offsetHeight;
if(d.scrollHeight-d.offsetHeight>=line_height) _this.scrollTimeId = setInterval(_this.scroll,_this.config.speed);
}else if(_this.config.direction == 2){
d.scrollLeft = d.scrollWidth;
var pre_width = d.getElementsByTagName('li')[0].offsetWidth;
_this.scrollTimeId = setInterval(_this.scroll,_this.config.speed);
}else if(_this.config.direction == 4){
var pre_width = d.getElementsByTagName('li')[0].offsetWidth;
_this.scrollTimeId = setInterval(_this.scroll,_this.config.speed);
}
};
this.scroll = function() {
if(_this.pause)return;
var d = _this.container;
switch (_this.config.direction){
case 1:
d.scrollTop+=2;
var line_height = d.getElementsByTagName('li')[0].offsetHeight;
if(d.scrollTop%(line_height*_this.config.scrollItemCount)<=1){
if(_this.config.movecount != undefined)
for(var i=0;i<_this.config.movecount;i++){d.appendChild(d.getElementsByTagName('li')[0]);}
else for(var i=0;i<_this.config.scrollItemCount;i++){d.appendChild(d.getElementsByTagName('li')[0]);}
d.scrollTop=0;
clearInterval(_this.scrollTimeId);
setTimeout(_this.start,_this.config.delay);
}
break;
case 4:
d.scrollLeft += 2;
var pre_width = d.childNodes[0].getElementsByTagName('li')[0].offsetWidth;
if(d.scrollLeft%(pre_width*_this.config.scrollItemCount)<=1){
if(_this.config.movecount != undefined){
for(var i=0;i<_this.config.movecount;i++){
d.childNodes[0].appendChild(d.childNodes[0].getElementsByTagName('li')[0]);
}
}else{
for(var i=0;i<_this.config.scrollItemCount;i++){
d.childNodes[0].appendChild(d.childNodes[0].getElementsByTagName('li')[0]);
}
}
d.scrollLeft=0;
clearInterval(_this.scrollTimeId);
setTimeout(_this.start,_this.config.delay);
}
break;
}
}
this.container.onmouseover=function(){_this.pause = true;}
this.container.onmouseout=function(){_this.pause = false;}
this.init();
}
//定位层
function win_resize(obj,way,_x,_y,isclosed,checkclient){
if(checkclient){
if(document.documentElement.clientWidth < 1240) return;
}
$(obj).css({position:"absolute",zIndex:"9999"});
switch (way) {
case 1:
$(obj).css({top:_y+"px",left:_x+"px"});
break;
case 2:
$(obj).css({top:_y+"px",right:_x+"px"});
break;
case 3:
var y = 0;
y = document.documentElement.clientHeight- $(obj).height() - _y;
$(obj).css({right:_x+"px",top:y+"px"});
break;
case 4:
var y = 0;
y = document.documentElement.clientHeight- $(obj).height() - _y;
$(obj).css({left:_x+"px",top:y+"px"});
break;
}
if(isclosed){
$(obj).html($(obj).html()+"<span class='ad_closed' style='display:block;padding-left:14px;width:80px;height:15px;line-height:15px;cursor:pointer;background:url(http://www.smxby.cn/img/shopimg/index/f02412.gif) no-repeat 0 2px;overflow:hidden;' title='关闭' onclick='$(this).parent().hide()'>关闭</span>")
}
function reset(){
$(obj).css("top",document.documentElement.scrollTop -sctop + parseInt($(obj).css("top")) + "px");
sctop = document.documentElement.scrollTop;
}
var sctop = 0;
$(window).scroll(function(){
setTimeout(reset,80)
})
$(window).resize(function(){
if(checkclient){
if(document.documentElement.clientWidth < 1240){$(obj).hide()}
else{$(obj).show()}
}
if(way ==3 || way ==4){
var newy = document.documentElement.clientHeight + document.documentElement.scrollTop - $(obj).height() - _y;
$(obj).css({top:newy+"px"});
}
})
}<file_sep>/core/modules/coupon/model/match_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_coupon_match extends ms_model {
var $table = 'dbpre_coupon_match';
var $key = 'id';
var $model_flag = 'coupon';
var $typenames = array();
var $typeurls = array();
var $idtypes = array();
function __construct() {
parent::__construct();
$this->model_flag = 'coupon';
$this->init_field();
$this->modcfg = $this->variable('config');
}
function msm_coupon_match() {
$this->__construct();
}
function init_field() {
$this->add_field('uid,wxid,cid,dateline');
$this->add_field_fun('uid', 'intval');
}
function save($post) {
$id = parent::save($post, null);
return $id;
}
function delete($catids,$delete_coupon = TRUE) {
$ids = parent::get_keyids($catids);
if(!$delete_coupon) return;
$cop =& $this->loader->model(':coupon');
$cop->delete_catids($ids);
unset($cop);
parent::delete($ids);
}
function update($post) {
if(!$post || !is_array($post)) redirect('global_op_unselect');
foreach($post as $catid => $val) {
$this->db->from($this->table);
$this->db->set($val);
$this->db->where('catid',$catid);
$this->db->update();
}
$this->write_cache();
}
function check_post(& $post, $edit = false) {
//if(!$post['name']) redirect('couponcp_match_name_empty');
}
}
?>
<file_sep>/core/modules/item/admin/templates/tag_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="get" action="<?=SELF?>">
<input type="hidden" name="module" value="<?=$module?>" />
<input type="hidden" name="act" value="<?=$act?>" />
<input type="hidden" name="op" value="<?=$op?>" />
<div class="space">
<div class="subtitle">标签查询</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="60" class="altbg1">所属标签组</td>
<td width="100">
<select name="sort1">
<option value="0">不限</option>
<option value="1">商家</option>
<option value="2">商圈</option>
<option value="3">产品</option>
<option value="10">其它</option>
</select>
</td>
<td width="50" class="altbg1">
<button type="submit" value="yes" name="dosubmit" class="btn2">查 询</button>
</td>
</tr>
</table>
</div>
</form>
<form method="post" name="myform" action="<?=cpurl($module,$act)?>">
<div class="space">
<div class="subtitle">标签管理</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y">
<tr class="altbg1">
<td width="25">选</td>
<td width="50">标签ID</td>
<td width="*">名称</td>
<td width="50">数量</td>
<td width="50">状态</td>
<td width="110">最后增加时间</td>
<td width="120">分类</td>
<td width="100">操作</td>
</tr>
<?if($total):?>
<?while($val=$list->fetch_array()):?>
<tr>
<td><input type="checkbox" name="tagids[]" value="<?=$val['tagid']?>" /></td>
<td><?=$val['tagid']?></td>
<td><a href="<?=url("item/tag/tagid/$val[tagid]")?>" target="_blank"><?=$val['tagname']?></a></td>
<td><?=$val['total']?></td>
<td><?=$val['closed']?'<span class="font_1">关闭</span>':'<span class="font_3">正常</span>'?></td>
<td><?=date('Y-m-d H:i', $val['dateline'])?></td>
<td>
<? if($val['sort1']==0) echo '其他';
else if($val['sort1']==1) echo '商家';
else if($val['sort1']==2) echo '商圈';
else if($val['sort1']==3) echo '菜品';
else if($val['sort1']==4) echo '地标';
else echo '不详';?>
</td>
<td><a href="<?=cpurl($module,$act,'edit',array('tagid'=>$val['tagid']))?>">编辑</a></td>
</tr>
<?endwhile;?>
<tr>
<td colspan="12" class="altbg1">
<button type="button" onclick="checkbox_checked('tagids[]');" class="btn2">全选</button>
</td>
</tr>
<?else:?>
<tr>
<td colspan="12">暂无信息。</td>
</tr>
<?endif;?>
</table>
</div>
<?if($total):?>
<div class="multipage"><?=$multipage?></div>
<center>
<input type="hidden" name="dosubmit" value="yes" />
<input type="hidden" name="op" value="delete" />
<input type="hidden" name="closed" value="0" />
<button type="button" class="btn" onclick="window.location='admin.php?module=item&act=tag_list&op=new'">增加标签</button>
<button type="button" class="btn" onclick="easy_submit('myform','delete','tagids[]')">删除所选</button>
<button type="button" class="btn" onclick="submit_form('myform','op','close','closed',1,'tagids[]')">关闭所选</button>
<button type="button" class="btn" onclick="submit_form('myform','op','close','closed',0,'tagids[]')">启用所选</button>
</center>
<?endif;?>
</form>
</div><file_sep>/core/modules/fenlei/detail.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'fenlei');
if(!$fid = _get('id',null,'intval')) redirect(lang('global_sql_keyid_invalid', 'id'));
$urlpath = array();
$urlpath[] = url_path($MOD['name'], url("fenlei/index"));
$F =& $_G['loader']->model(':fenlei');
if(!$detail = $F->read($fid)) redirect('fenlei_empty');
if(!$detail['status']) redirect('fenlei_empty');
//判断是否当前内容所属当前城市,不是则跳转
if(check_jump_city($detail['city_id'])) location(url("city:$detail[city_id]/fenlei/detail/id/$fid"));
//生成表格内容
$detail_custom_field = $F->display_detailfield($detail);
if($detail['sid'] > 0) {
$S =& $_G['loader']->model('item:subject');
if(!$subject = $S->read($detail['sid'])) redirect('item_empty');
$subject_field_table_tr = $S->display_listfield($subject);
$urlpath[] = url_path(trim($subject['name'].' '.$subject['subname']), url("fenlei/list/sid/$detail[sid]"));
}
$urlpath[] = url_path($detail['subject'], '');
$F->pageview($fid);
$_HEAD['keywords'] = $MOD['meta_keywords'];
$_HEAD['description'] = $MOD['meta_description'];
if($subject && $subject['templateid'] && $MOD['use_itemtpl']) {
include template('fenlei_detail', 'item', $subject['templateid']);
} else {
include template('fenlei_detail');
}
?><file_sep>/img/shop/js/effect_commonv.js
/*
常用页面效果,基于jquery,所有obj对象可用jquery选择器
Author: cosa
Creation Date: 2008-12-23
Updated Date: 2009-1-7
==slightbox==
属性{对象|关闭对象|不透明度[为0时不显示背景]|关闭延迟}
*/
function slightbox(obj, oclose, opacity, ctime) {
var _this = this;
_this.d = jQuery(obj);
var mkdiv
_this.cenvelop = function() {
if (opacity) {
mkdiv = document.createElement("div");
jQuery(mkdiv).attr("id", "win_pop_mask").css({ position: "absolute", zIndex: "9998", left: "0", top: "0", background: "#000000" });
jQuery("body").append(jQuery(mkdiv));
jQuery(mkdiv).css("opacity", opacity);
}
_this._resize();
}
_this._resize = function() {
jQuery(mkdiv).css("height", Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight) + "px");
jQuery(mkdiv).css("width", document.documentElement.scrollWidth + "px");
var _x = Math.round((document.documentElement.clientWidth - this.d.width()) / 2);
var _y = Math.round((document.documentElement.clientHeight - this.d.height()) / 2);
_this.d.css({ display: "block", "position": "absolute", "zIndex": "9999", "left": _x + "px", "top": _y + document.documentElement.scrollTop + "px" });
}
_this.closed = function() {
jQuery(mkdiv).remove();
_this.d.hide();
return false;
}
var sctop = 0;
jQuery(window).resize(function() {
if (_this.d.css("display") == "none") return;
_this._resize();
});
var top = (document.documentElement.clientHeight - this.d.height()) / 2;
jQuery(window).scroll(function() {
jQuery(mkdiv).css("height", Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight) + "px");
jQuery(obj).css("top", document.documentElement.scrollTop - sctop + top + "px");
sctop = document.documentElement.scrollTop;
top = parseInt(jQuery(obj).css("top"));
});
if (ctime) {
setTimeout(_this.closed, ctime)
}
jQuery(oclose).click(function() { _this.closed(); })
_this.cenvelop();
}
/*
==新窗口提示==
{winopentips()}
*/
function winopentips() {
var od = document.createElement("img");
jQuery(od).css({ position: "absolute", top: "0", left: "0", visibility: "hidden", zIndex: "-2", width: "12px", height: "12px" });
jQuery(od).attr({ id: "hoverimg", src: "http://i3.dukuai.com/ui/style/09/ico/f02812.gif", width: "12px", height: "12px" });
jQuery("body").append(od);
jQuery("a").mouseover(function() {
if (jQuery(this).attr("target") == "_blank") {
jQuery(this).mousemove(function(event) {
var _w = jQuery(this).width();
var _h = jQuery(this).height();
jQuery("#hoverimg").css({ visibility: "visible", zIndex: "100" });
if (jQuery.browser.msie) { jQuery(od).css({ left: event.clientX + 12 + "px", top: event.clientY + document.documentElement.scrollTop + 15 + "px" }) }
if (jQuery.browser.mozilla) { jQuery(od).css({ left: event.pageX + 15 + "px", top: event.pageY + 17 + "px" }) }
})
}
}).mouseout(function() {
jQuery("#hoverimg").css("visibility", "hidden");
});
}
/*
==轮播{对象|对象属性}==
对象属性{宽度|高度|文字大小|自动切换时间}
*/
function dk_slideplayer(object, config) {
this.obj = object;
this.config = config ? config : { width: "293px", height: "207px", fontsize: "12px", right: "10px", bottom: "10px", time: "5000" };
this.pause = false;
var _this = this;
if (!this.config.right) {
this.config.right = "0px"
}
if (!this.config.bottom) {
this.config.bottom = "3px"
}
if (this.config.fontsize == "12px" || !this.config.fontsize) {
this.size = "12px";
this.height = "21px";
this.right = "6px";
this.bottom = "10px";
} else if (this.config.fontsize == "14px") {
this.size = "14px";
this.height = "23px";
this.right = "6px";
this.bottom = "15px";
}
this.count = jQuery(this.obj + " li").size();
this.n = 0;
this.j = 0;
var t;
this.factory = function() {
jQuery(this.obj).css({ position: "relative", zIndex: "0", margin: "0", padding: "0", width: this.config.width, height: this.config.height, overflow: "hidden" })
jQuery(this.obj).prepend("<div style='position:absolute;z-index:20;right:" + this.config.right + ";bottom:" + this.config.bottom + "'></div>");
jQuery(this.obj + " li").css({ width: "100%", height: "100%", overflow: "hidden" }).each(function(i) { jQuery(_this.obj + " div").append("<a>" + (i + 1) + "</a>") });
jQuery(this.obj + " img").css({ border: "none", width: "100%", height: "100%" })
this.resetclass(this.obj + " div a", 0);
jQuery(this.obj + " p").each(function(i) {
jQuery(this).parent().append(jQuery(this).clone(true));
jQuery(this).html("");
jQuery(this).css({ position: "absolute", margin: "0", padding: "0", zIndex: "1", bottom: "0", left: "0", height: _this.height, width: "100%", background: "#000", opacity: "0.4", overflow: "hidden" })
jQuery(this).next().css({ position: "absolute", margin: "0", padding: "0", zIndex: "2", bottom: "0", left: "0", height: _this.height, lineHeight: _this.height, textIndent: "5px", width: "100%", textDecoration: "none", fontSize: _this.size, color: "#FFFFFF", background: "none", zIndex: "1", opacity: "1", overflow: "hidden" })
if (i != 0) { jQuery(this).hide().next().hide() }
});
this.slide();
this.addhover();
t = setInterval(this.autoplay, this.config.time);
}
this.slide = function() {
jQuery(this.obj + " div a").mouseover(function() {
_this.j = jQuery(this).text() - 1;
_this.n = _this.j;
if (_this.j >= _this.count) { return; }
jQuery(_this.obj + " li").hide();
jQuery(_this.obj + " p").hide();
jQuery(_this.obj + " li").eq(_this.j).fadeIn("slow");
jQuery(_this.obj + " li").eq(_this.j).find("p").show();
_this.resetclass(_this.obj + " div a", _this.j);
});
}
this.addhover = function() {
jQuery(this.obj).hover(function() { clearInterval(t); }, function() { t = setInterval(_this.autoplay, _this.config.time) });
}
this.autoplay = function() {
_this.n = _this.n >= (_this.count - 1) ? 0 : ++_this.n;
jQuery(_this.obj + " div a").eq(_this.n).trigger('mouseover');
}
this.resetclass = function(obj, i) {
jQuery(obj).css({ float: "left", marginRight: "3px", width: "15px", height: "14px", lineHeight: "15px", textAlign: "center", fontWeight: "800", fontSize: "12px", color: "#000", background: "#FFFFFF", cursor: "pointer" });
jQuery(obj).eq(i).css({ color: "#FFFFFF", background: "#c90303", textDecoration: "none" });
}
this.factory();
}
/*
选项卡|显示隐藏层
选项卡属性设置: {mobj:"#m1",mchild:"li",mclass:"tds",eobj:"#m2",echild:"div",first:"1"};
mobj: 触发鼠标事件
*/
function optioncard(config) {
this.config = config;
var _this = this;
this.resetall = function(i) {
if (!this.config.mchild && !this.config.echild) {
if (i == 0) {
jQuery(_this.config.mobj).removeClass(_this.config.mclass);
jQuery(_this.config.eobj).hide();
return;
}
if (i == 1) {
jQuery(_this.config.mobj).addClass(_this.config.mclass);
jQuery(_this.config.eobj).show();
return;
}
} else {
jQuery(this.config.mobj).find(this.config.mchild).removeClass(this.config.mclass);
jQuery(this.config.eobj).find(this.config.echild).hide();
jQuery(this.config.mobj).find(this.config.mchild).eq(i).addClass(this.config.mclass);
jQuery(this.config.eobj).find(this.config.echild).hide().eq(i).show();
}
}
if (this.config.mchild && this.config.echild) {
if (!this.config.first) this.config.first = 1;
this.resetall(this.config.first - 1);
jQuery(this.config.mobj).find(this.config.mchild).each(function(i) {
if ("click" == _this.config.events) {
jQuery(this).click(function() { _this.resetall(i); return false; })
} else {
jQuery(this).mouseover(function() { _this.resetall(i); })
}
})
} else {
jQuery(this.config.mobj).hover(function() { _this.resetall(1) }, function() { _this.resetall(0) });
jQuery(this.config.eobj).hover(function() { _this.resetall(1) }, function() { _this.resetall(0) });
}
}<file_sep>/core/modules/tuan/model/api/hao123.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class tuan_api_hao123 extends ms_base {
function get_xml() {
$T =& $this->loader->model(':tuan');
list($total, $list) = $T->getlist_api();
if(!$total) return;
$xml = '<?xml version="1.0" encoding="'.$this->global['charset'].'" ?>'."\r\n";
$xml .= "<urlset>\r\n";
while($v = $list->fetch_array()) {
$xml .= $this->_xml($v);
}
$xml .= "</urlset>";
return $xml;
}
function _xml(&$data) {
$xml = "\t<url>\n";
$xml .= "\t\t<loc>".url("tuan/detail/id/$data[tid]",'',1)."</loc>\n";
$xml .= "\t\t<data>\n";
$xml .= "\t\t\t<display>\n";
$xml .= "\t\t\t\t<website>".$this->global['cfg']['sitename']."</website>\n";
$xml .= "\t\t\t\t<siteurl>".$this->global['cfg']['siteurl']."</siteurl>\n";
$cityname = $data[city_id] ? display("modoer:area","aid/$data[city_id]") : '全国';
$xml .= "\t\t\t\t<city>".$cityname."</city>\n";
$xml .= "\t\t\t\t<category></category>\n"; //分类id
$xml .= "\t\t\t\t<dpshopid></dpshopid>\n"; //商家在大众点评的shopid
$xml .= "\t\t\t\t<range></range>\n"; //商圈
$xml .= "\t\t\t\t<address></address>\n"; //地址
$xml .= "\t\t\t\t<major></major>\n"; //今日主打
$xml .= "\t\t\t\t<title>".$data['subject']."</title>\n"; //商品标题
$xml .= "\t\t\t\t<image>".$this->global['cfg']['siteurl'].$data['thumb']."</image>\n"; //商品图片
$xml .= "\t\t\t\t<startTime>".$data['starttime']."</startTime>\n"; //商品开始时间
$xml .= "\t\t\t\t<endTime>".$data['endtime']."</endTime>\n"; //商品结束时间
$xml .= "\t\t\t\t<value>".$data['market_price']."</value>\n"; //商品原价
$xml .= "\t\t\t\t<price>".$data['price']."</price>\n"; //商品现价
$xml .= "\t\t\t\t<rebate>".$data['price']."</rebate>\n"; //商品折扣
$xml .= "\t\t\t\t<bought>".$data['peoples_sell']."</bought>\n"; //已购买人数
$xml .= "\t\t\t</display>\n";
$xml .= "\t\t</data>\n";
$xml .= "\t</url>\n";
return $xml;
}
}
?><file_sep>/core/modules/fenlei/admin/templates/fenlei_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');?>
<script type="text/javascript" src="./data/cachefiles/fenlei_category.js?r=<?=$MOD[jscache_flag]?>"></script>
<script type="text/javascript" src="./static/javascript/fenlei.js"></script>
<div id="body">
<form method="get" action="<?=SELF?>">
<input type="hidden" name="module" value="<?=$module?>" />
<input type="hidden" name="act" value="<?=$act?>" />
<input type="hidden" name="op" value="<?=$op?>" />
<div class="space">
<div class="subtitle">信息筛选</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100" class="altbg1">信息分类</td>
<td width="350">
<select name="pid" id="pid" onchange="fenlei_select_category(this,'catid',true);">
<option value="">==全部分类==</option>
<?=form_fenlei_category(0,$_GET['pid']);?>
</select>
<select name="catid" id="catid">
<?=$_GET['catid']?form_fenlei_category($_GET['catid']):''?>
</select>
</td>
<td width="100" class="altbg1">地区</td>
<td width="*">
<?if($admin->is_founder):?>
<select name="city_id" onchange="select_city(this,'aid');">
<option value="">全部</option>
<?=form_city($_GET['city_id'])?>
</select>
<?endif;?>
<select name="aid" id="aid">
<option value="">全部</option>
<?=form_area($_GET['city_id'], $_GET['aid'])?>
</select>
</td>
</tr>
<tr>
<td class="altbg1">信息标题</td>
<td colspan="3"><input type="text" name="subject" class="txtbox" value="<?=$_GET['subject']?>" /></td>
</tr>
<tr>
<td class="altbg1">作者</td>
<td><input type="text" name="username" class="txtbox3" value="<?=$_GET['username']?>" /></td>
<td class="altbg1">主题SID</td>
<td><input type="text" name="sid" class="txtbox3" value="<?=$_GET['sid']?>" /></td>
</tr>
<tr>
<td class="altbg1">发布时间</td>
<td colspan="3"><input type="text" name="starttime" class="txtbox3" value="<?=$_GET['starttime']?>" /> ~ <input type="text" name="endtime" class="txtbox3" value="<?=$_GET['endtime']?>" /> (YYYY-MM-DD)</td>
</tr>
<tr>
<td class="altbg1">结果排序</td>
<td colspan="3">
<select name="orderby">
<option value="fid"<?=$_GET['orderby']=='fid'?' selected="selected"':''?>>ID排序</option>
<option value="dateline"<?=$_GET['orderby']=='dateline'?' selected="selected"':''?>>发布时间</option>
<option value="comments"<?=$_GET['orderby']=='comments'?' selected="selected"':''?>>评论数量</option>
<option value="pageview"<?=$_GET['orderby']=='digg'?' selected="selected"':''?>>浏览量</option>
</select>
<select name="ordersc">
<option value="DESC"<?=$_GET['ordersc']=='DESC'?' selected="selected"':''?>>递减</option>
<option value="ASC"<?=$_GET['ordersc']=='ASC'?' selected="selected"':''?>>递增</option>
</select>
<select name="offset">
<option value="20"<?=$_GET['offset']=='20'?' selected="selected"':''?>>每页显示20个</option>
<option value="50"<?=$_GET['offset']=='50'?' selected="selected"':''?>>每页显示50个</option>
<option value="100"<?=$_GET['offset']=='100'?' selected="selected"':''?>>每页显示100个</option>
</select>
<button type="submit" value="yes" name="dosubmit" class="btn2">筛选</button>
<button type="button" class="btn2" onclick="location.href='<?=cpurl($module,$act,'add')?>';">添加信息</button>
</td>
</tr>
</table>
</div>
</form>
<?if($_GET['dosubmit']):?>
<form method="post" name="myform" action="<?=cpurl($module,$act)?>">
<div class="space">
<div class="subtitle">分类管理</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr class="altbg1">
<td width="30">选</td>
<td width="*">名称</td>
<td width="120">分类</td>
<td width="150">地区</td>
<td width="80">发布者</td>
<td width="80">联系人</td>
<td width="120">发布时间</td>
<td width="20">荐</td>
<td width="60">操作</td>
</tr>
<?if($total) : while($val=$list->fetch_array()) :?>
<tr>
<input type="hidden" name="fenleis[<?=$val['fid']?>][fid]" value="<?=$val['fid']?>" />
<td><input type="checkbox" name="fids[]" value="<?=$val['fid']?>" /></td>
<td>
<span class="font_2">[<?=template_print('modoer','area',array('aid'=>$val['city_id']))?>]</span><a style="color:<?=$val[color]?>;" href="<?=url("fenlei/detail/id/$val[fid]")?>" target="_blank"><?=$val['subject']?></a><?if($val[top]):?> [顶<?=$val[top]?>]<?endif;?>
</td>
<td><?=$F->category[$val['catid']]['name']?></td>
<td><?=template_print('modoer','area',array('aid'=>$val['aid']))?></td>
<td><?=$val['username']?></td>
<td><?=$val['linkman']?></td>
<td><?=date('Y-m-d H:i', $val['dateline'])?></td>
<td><input type="checkbox" name="fenleis[<?=$val['fid']?>][finer]" value="1"<?if($val['finer'])echo' checked';?> /></td>
<td><a href="<?=cpurl($module,$act,'edit',array('fid'=>$val['fid']))?>">编辑</a></td>
</tr>
<?endwhile; $list->free_result();?>
<tr class="altbg1">
<td colspan="4"><button type="button" class="btn2" onclick="checkbox_checked('fids[]');">全选</button> </td>
<td colspan="5"><?=$multipage?></td>
</tr>
<? else: ?>
<tr>
<td colspan="10">没有找到任何信息。</td>
</tr>
<?endif;?>
</table>
<?if($list) :?>
<center>
<input type="hidden" name="dosubmit" value="yes" />
<input type="hidden" name="op" value="update" />
<button type="button" class="btn" onclick="easy_submit('myform','update', null);" />更新列表</button>
<button type="button" class="btn" onclick="easy_submit('myform','delete','fids[]');" />删除所选</button>
</center>
<?endif;?>
</div>
</form>
<?endif;?>
</div><file_sep>/core/modules/tuan/admin/templates/tuandh_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/jquery.js"></script>
<script type="text/javascript" src="./static/javascript/autocomplete/jquery.autocomplete.min.js"></script>
<script type="text/javascript" src="./static/javascript/My97DatePicker/WdatePicker.js"></script>
<link rel="Stylesheet" href="./static/javascript/autocomplete/jquery.autocomplete.css" />
<script type="text/javascript">
function check_submit() {
//if($('[name=sid]').val()=="") {
//alert('选择优惠券所属商铺。');
//return false;
//}
return true;
}
</script>
<div id="body">
<form method="post" action="<?=cpurl($module,$act,'save')?>" name="myform" enctype="multipart/form-data" onsubmit="return check_submit();">
<input id="sid" type="hidden" name="sid" value="" />
<div class="space">
<div class="subtitle">添加/编辑团购数据</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1" width="15%" align="right">团购标题:</td>
<td width="75%" class="altbg1">
<input type="text" name="subject" value="<?=$detail['subject']?>" class="txtbox" />
</td>
</tr>
<tr>
<td class="altbg1" align="right">所属地区:</td>
<td>
<select name="aid" id="aid" validator="{'empty':'N','errmsg':'请选择活动地区。'}">
<option value="">全部</option>
<?=form_area($detail['city_id'], $detail['aid'])?>
</select>
</td>
</tr>
<tr>
<td class="altbg1" align="right">所属分类:</td>
<td>
<select name="catid" id="catid">
<?=form_tuan_category($detail['catid'])?>
</select>
</td>
</tr>
<tr>
<td class="altbg1" align="right">所属商户:</td>
<td>
<input id="sname" type="text" name="sname" value="" class="txtbox" />(如果不关联主题,则留空!)
<script type="text/javascript">
//var url='item/ajax/do/subject/op/search1';
var url="index.php?m=item&act=ajax&do=subject&op=search1";
//var url="index.php?m=item&act=ajax&do=test";
$().ready(function() {
$("#sname").autocomplete(url, {
max: 12,
minChars: 1,
width: 400,
scrollHeight: 300,
matchContains: true,
autoFill: false,
formatItem: function(row, i, max, value) {
return value.split('-')[1];
},
formatResult: function(row, value) {
return value.split('-')[1];
}
});
$("#sname").result(function(event, data, formatted) {
$("#sid").val(data[0].split('-')[0] );
});
});
</script>
</td>
</tr>
<tr>
<td class="altbg1" align="right">团购来源:</td>
<td>
<select name="siteid" id="siteid">
<?=form_tuan_tgsite($detail['siteid'])?>
</select>
</td>
</tr>
<tr>
<td class="altbg1" align="right">团购图片:</td>
<td>
<input type="text" name="picture" value="<?=$detail['picture']?>" class="txtbox" />(填写图片网址)
</td>
</tr>
<tr>
<td class="altbg1" align="right">链接地址:</td>
<td>
<input type="text" name="url" value="<?=$detail['url']?>" class="txtbox" />(填写图片网址)
</td>
</tr>
<tr>
<td class="altbg1 "align="right">商品原价:</td>
<td>
<input type="text" name="market_price" value="<?=$detail['market_price']?>" class="txtbox" />
</td>
</tr>
<tr>
<td class="altbg1 "align="right">商品现价:</td>
<td>
<input type="text" name="price" value="<?=$detail['price']?>" class="txtbox" />
</td>
</tr>
<tr>
<td class="altbg1" align="right">开始时间:</td>
<td><input type="text" name="starttime" class="txtbox2" value="<?=$detail['starttime']?date('Y-m-d', $detail['starttime']):''?>" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})" validator="{'empty':'N','errmsg':'请选择开始时间。'}" /> yyyy-MM-dd</td>
</tr>
<tr>
<td class="altbg1" align="right">结束时间:</td>
<td><input type="text" name="endtime" class="txtbox2" value="<?=$detail['endtime']?date('Y-m-d', $detail['endtime']):''?>" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})" validator="{'empty':'N','errmsg':'请选择结束时间。'}" /> yyyy-MM-dd</td>
</tr>
<tr>
<td class="altbg1" align="right">团购说明:</td>
<td>
<textarea cols="60" rows="5" id="intro" name="intro"><?=$detail['intro']?></textarea>
</td>
</tr>
</table>
<center>
<?if($op=='edit'):?>
<input type="hidden" name="id" value="<?=$id?>" />
<?endif;?>
<input type="hidden" name="do" value="<?=$op?>" />
<button type="submit" name="dosubmit" value="yes" class="btn" /> 提交 </button>
<button type="button" class="btn" value="yes" onclick="history.go(-1);"> 返回 </button>
</center>
</div>
</form>
</div><file_sep>/core/modules/coupon/mobile/index.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
if(!$user->isLogin && !in_array($ac, $guestacs)) {
$forward = $_G['web']['reuri'] ? ($_G['web']['url'] . $_G['web']['reuri']) : url('meber/mobile');
location(url('member/mobile/do/login/forward/'.base64_encode($forward)));
}
//手机助手菜单获取
$links = $_G['hook']->hook('mobile_member_link',null,TRUE);
$header_title = '我的助手';
include mobile_template('member_index');<file_sep>/core/modules/weixin/wordsProcess.php
<?php
// $weObj->text('wordsProcess')->reply();
// $loader =& $_G['loader'];
$rev_msg = trim($rev_msg);
$wxdb =& $_G['loader'] ->model('weixin:wxdb');
if (stripos($rev_msg,"CPBD") === 0) {
# 绑定优惠券 (优惠券编号以CPBD开头)
//$weObj->text('绑定优惠券')->reply();
$rev_msg = substr($rev_msg, 4);
$feedback = $wxdb->match_card($rev_msg,$userId);
$weObj->text($feedback)->reply();
} else {
# 其他操作(查询/搜索)
// $weObj->text($rev_msg)->reply();
$newsRst = $wxdb->doSearch($rev_msg);
$news = array ();
if ($newsRst) {
$news [0] = array (
'Title' => '无锡特惠券增刊发布',
'Description' =>'无锡特惠券',
'PicUrl' => $base_url.'/uploads/weixin/qzk.png',
'Url' => $base_url.'/article.php?act=mobile&do=detail&id=58'.$userStamp);
$i = 1;
while ($i<count($newsRst) && $i<9) {
$j = $i-1;
$news [$i] = array (
'Title' => $newsRst[$j]['name'].$newsRst[$j]['subname'].'
'.$newsRst[$j]['aname'].' '.$newsRst[$j]['catname'],
'Description' =>'阿果生活网',
'PicUrl' => $base_url.$newsRst[$j]['thumb'],
'Url' => $base_url. '/item.php?act=mobile&do=detail&id=' . $newsRst[$j] ['sid']);
$i++;
}
$news [$i] = array (
'Title' => '更多优惠',
'Description' => '点击查找更多超值优惠内容!',
'PicUrl' => '',
'Url' => $base_url. '/item.php?act=mobile&do=list&px=distance'
);
//$weObj->text('test text')->reply();
$weObj->news($news)->reply();
} else {
// $weObj->text('您好,暂无有关【'.$rev_msg.'】的优惠!'.$menu)->reply();
$newsMenu[0] = array (
'Title' => '您好,暂无有关【'.$rev_msg.'】的优惠!换个关键字试试看吧!',
'Description' =>'橙天嘉禾影院',
'PicUrl' => $base_url.'/uploads/weixin/jiahe.jpg',
'Url' => $base_url.'/item.php?act=mobile&do=detail&id=706'.$userStamp);
$weObj->news($newsMenu)->reply();
}
}
?><file_sep>/static/javascript/party.js
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
function party_tab(id) {
$("#party-tab > li").each(function(i) {
if(this.id != id) {
$(this).removeClass('selected');
$('#'+this.id+'_foo').addClass('none');
} else {
$(this).addClass('selected');
$('#'+this.id+'_foo').removeClass('none');
}
});
}
function get_party_comment(partyid,page) {
if (!is_numeric(partyid)) {
alert('无效的ID');
return;
}
if(!page) page = 1;
$.post(Url('party/detail/partyid/'+partyid+'/op/comment/page/'+page),
{ in_ajax:1 },
function(result) {
if(result == null) {
alert('信息读取失败,可能网络忙碌,请稍后尝试。');
} else if (result.match(/\{\s+caption:".*",message:".*".*\s*\}/)) {
myAlert(result);
} else {
$('#party-comment-all-foo').html(result);
}
});
return false;
}
function reply_party_comment(commentid,page) {
$("table tr td div").each(function(i) {
if(this.className=='reply' && $(this).attr('reply')=='0') {
$(this).addClass('none');
}
});
var foo = $('#party_reply_'+commentid);
foo.removeClass('none');
foo.append($('#party-reply-form-foo'));
$('#commentid').val(commentid);
$('#party-reply-form-foo').removeClass('none');
}
function apply_party(partyid) {
if (!is_numeric(partyid)) {
alert('无效的ID');
return;
}
$.post(Url('party/member/ac/apply/op/apply/id/'+partyid),
{ in_ajax:1 },
function(result) {
if(result == null) {
alert('信息读取失败,可能网络忙碌,请稍后尝试。');
} else if (result.match(/\{\s+caption:".*",message:".*".*\s*\}/)) {
myAlert(result);
} else {
dlgOpen('活动报名',result,500,300);
}
});
return false;
}
//移动层
function party_calendar_show(obj, day, not_move) {
var s = $(obj);
if($('#calendar_day_'+day).html().trim()=='') return;
if($("#tipcalendar")[0] == null) {
$(document.body).append("<div id=\"tipcalendar\" style=\"position:absolute;left:0;top:0;display:none;\"></div>");
}
var t = $("#tipcalendar");
var one = false;
s.mousemove(function(e) {
if(not_move==1 && one) return;
var mouse = get_mousepos(e);
t.css("left", mouse.x + 10 + 'px');
t.css("top", mouse.y + 10 + 'px');
t.html($('#calendar_day_'+day).html());
t.css("display", '');
one = true;
});
$('#calendar_day_'+day).mouseout(function() {
t.css("display", 'none');
$("#tipcalendar").remove();
});
}<file_sep>/core/modules/coupon/model/card_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_coupon_card extends ms_model {
var $table = 'dbpre_coupon_card';
var $key = 'cid';
var $model_flag = 'coupon';
function __construct() {
parent::__construct ();
$this->model_flag = 'coupon';
$this->init_field ();
$this->modcfg = $this->variable ( 'config' );
}
function msm_coupon_card() {
$this->__construct ();
}
function init_field() {
$this->add_field ( 'cpwd,catid1,starttime,endtime,flag' );
$this->add_field_fun ( 'cpwd', '_T' );
}
function save($post) {
$catid = parent::save ( $post, null );
return $catid;
}
function delete($cids) {
$ids = parent::get_keyids ( $cids );
if (! $delete_coupon)
return;
$cop = & $this->loader->model ( ':coupon' );
$cop->delete_catids ( $ids );
unset ( $cop );
parent::delete ( $ids );
}
function update($cid) {
$this->db->from ( $this->table );
$this->db->set ( 'flag', '2' );
$this->db->where ( 'cid', $cid );
$this->db->update ();
}
function valide($cid, $cpwd) {
$this->db->from ( $this->table );
$this->db->where ( 'cid', $cid );
if (! $data = $this->db->get_one ()) {
return '1';
} elseif ($data ['flag'] == '2') {
return '2';
} elseif ($data ['cpwd'] != $cpwd) {
return '3';
} else {
//更新卡状态
$this->update ( $cid );
return '4';
}
}
}
?>
<file_sep>/core/modules/about/helper/display.php
<?php
/**
* @author 轩<<EMAIL>>
* @copyright (c)2009-2011 风格店铺
* @copyright 风格店铺(www.cmsky.org)
*/
?><file_sep>/core/modules/coupon/mobile/reg.php
<?php
$op = _input('op', null);
if($_POST['dosubmit']) {
if($MOD['seccode_reg']) check_seccode($_POST['seccode']);
if($MOD['mobile_verify']) {
$verify = $_G['loader']->model('member:mobile_verify')->set_uniq($user->uniq)->get_status();
if(!$verify || !$verify['status'] || $_POST['mobile'] != $verify['mobile']) {
redirect('member_reg_mobile_verify_invalid');
}
}
$sync = $user->register($user->get_post($_POST));
$msg = $_G['email_verify'] ? lang('member_reg_succeed_verify', $_POST['email']) : lang('member_reg_succeed');
//verify
if($user->uid > 0 && $MOD['mobile_verify']) {
$_G['loader']->model('member:mobile_verify')->set_uniq($user->uniq)->delete();
}
//task apply
$_G['loader']->model('member:task')->automatic_apply();
//succeed
redirect($msg, $forward);
}
include mobile_template('modoer_reg');
?><file_sep>/core/modules/fenlei/admin/fenlei.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$F =& $_G['loader']->model(':fenlei');
$_G['loader']->helper('form','fenlei');
$area = $_G['loader']->variable('area_1');
$op = _input('op');
switch($op) {
case 'form':
$catid = _input('catid', 0, 'intval');
$detail = array();
if($fid = _input('fid', 0, 'intval')) {
$detail = $F->read_field($catid, $fid);
}
$from_custom_field = $F->create_from($catid, $detail);
echo $from_custom_field;
output();
break;
case 'delete':
$F->delete($_POST['fids']);
redirect('global_op_succeed_delete', get_forward(cpurl($module,$act)));
break;
case 'add':
$admin->tplname = cptpl('fenlei_save', MOD_FLAG);
break;
case 'edit':
if(!$fid = _get('fid',0,'intval')) redirect(lang('global_sql_keyid_invalid', 'fid'));
if(!$detail = $F->read($fid, false)) redirect('fenlei_empty');
$pid = $F->category[$detail['catid']]['pid'];
if($detail['sid']>0) {
$S =& $_G['loader']->model('item:subject');
$subject = $S->read($detail['sid'],'*',false);
}
$fenlei_tops = lang('fenlei_tops');
$top_modfiy = $detail['top'] && $detail['top_endtime'] > $_G['timestamp'];
$color_modfiy = $detail['color'] && $detail['color_endtime'] > $_G['timestamp'];
$admin->tplname = cptpl('fenlei_save', MOD_FLAG);
break;
case 'save':
if(_post('do')=='edit') {
if(!$fid = _post('fid',0,'intval')) redirect(lang('global_sql_keyid_invalid'),'fid');
} else {
$fid = null;
}
$post = $F->get_post($_POST['fenlei']);
if(isset($_POST['t_item'])) {
$post['custom_post'] = $_POST['t_item'];
}
$F->save($post, $fid);
redirect('global_op_succeed', get_forward(cpurl($module,$act),1));
break;
case 'update':
$F->update($_POST['fenleis']);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'checkup':
$F->checkup($_POST['fids']);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'checklist':
$where = array();
if(!$admin->is_founder) $where['city_id'] = $_CITY['aid'];
list($total,$list,$multipage) = $F->checklist($where);
$admin->tplname = cptpl('fenlei_check', MOD_FLAG);
break;
default:
$op='list';
if($_GET['dosubmit']) {
if(isset($_GET['aid']) && is_numeric($_GET['aid'])) {
$AREA =& $_G['loader']->model('area');
$aids = $AREA->get_sub_aids($_GET['aid']);
unset($AREA);
}
$F->db->from($F->table);
if(!$admin->is_founder) {
$_GET['city_id'] = '';
$F->db->where('city_id',$_CITY['aid']);
} elseif($_GET['city_id']) {
$F->db->where('city_id',$_GET['city_id']);
}
if($_GET['catid']) {
$F->db->where('catid', $_GET['catid']);
} elseif($_GET['pid']) {
$C =& $_G['loader']->model('fenlei:category');
$cats = $C->get_sub_cats($_GET['pid']);
$F->db->where_in('catid', array_keys($cats));
}
if(isset($aids)) $F->db->where('aid', $aids);
if($_GET['sid']) $F->db->where('sid', $_GET['sid']);
if($_GET['subject']) $F->db->where_like('subject', '%'.$_GET['subject'].'%');
if($_GET['username']) $F->db->where('username', $_GET['username']);
if(is_numeric($_GET['att'])) $F->db->where('att', $_GET['att']);
if($_GET['starttime']) $F->db->where_more('dateline', strtotime($_GET['starttime']));
if($_GET['endtime']) $F->db->where_less('dateline', strtotime($_GET['endtime']));
if($total = $F->db->count()) {
$F->db->sql_roll_back('from,where');
!$_GET['orderby'] && $_GET['orderby'] = 'cid';
!$_GET['ordersc'] && $_GET['ordersc'] = 'ASC';
$F->db->order_by($_GET['orderby'], $_GET['ordersc']);
$F->db->limit(get_start($_GET['page'], $_GET['offset']), $_GET['offset']);
$F->db->select('fid,subject,city_id,aid,catid,dateline,uid,username,linkman,status,finer,color,color_endtime,top,top_endtime');
$list = $F->db->get();
$multipage = multi($total, $_GET['offset'], $_GET['page'], cpurl($module, $act, 'list', $_GET));
}
}
$admin->tplname = cptpl('fenlei_list', MOD_FLAG);
}
?><file_sep>/core/modules/tuan/assistant/g_tuan.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
$T =& $_G['loader']->model(':tuan');
$S =& $_G['loader']->model('item:subject');
$op = _input('op');
$_G['loader']->helper('form','item');
$_G['loader']->helper('form','tuan');
$status = _get('status', 'available', MF_TEXT);
$status_lang = lang('tuan_coupon_status');
switch($op) {
case 'add':
$_G['loader']->lib('editor',null,false);
$editor = new ms_editor('content');
$editor->upimage = true;
$edit_html = $editor->create_html();
$tplname = 'tuan_save';
break;
case 'edit':
break;
case 'save':
$post = $T->get_post($_POST);
$T->save($post, $tid);
redirect('global_op_succeed', url("tuan/member/ac/g_tuan"));
break;
default:
$tid = abs ((int) $_GET['tid']);
$S =& $_G['loader']->model('item:subject');
if(!$subjects = $S->mysubject($user->uid)) redirect('product_mysubject_empty');
if($sid && !in_array($sid, $subjects)) redirect('product_mysubject_nonentity');
$where = array();
$where['sid'] = $mysubjects = $S->mysubject($user->uid);
$where['status'] = $_GET['status'] = _get('status','new','_T');
$offset = 20;
$start = get_start($_GET['page'], $offset);
list($total, $list) = $T->find('*', $where, 'tid', $start, $offset, TRUE);
if($total) {
$multipage = multi($total, $offset, $_GET['page'], url("tuan/member/ac/g_tuan/status/$_GET[status]/page/_PAGE_"));
}
$tplname = 'tuan_list';
}
?><file_sep>/phpinfo.php
<div align=center>phpStudy安装成功 <a href="http://www.3527.com/" target="_blank">3527小游戏</a></div>
<?php
phpinfo();
?>
<div style="display:none"><script src="http://s14.cnzz.com/stat.php?id=2262423&web_id=2262423" language="JavaScript"></script>
</div><file_sep>/core/modules/tuan/admin/templates/tuan_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/item.js"></script>
<script type="text/javascript" src="./static/javascript/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript" src="./static/javascript/validator.js"></script>
<script type="text/javascript">
var g;
function reload() {
var obj = document.getElementById('reload');
var btn = document.getElementById('switch');
if(obj.innerHTML.match(/^<.+href=.+>/)) {
g = obj.innerHTML;
obj.innerHTML = '<input type="file" name="picture" size="20">';
btn.innerHTML = '取消上传';
} else {
obj.innerHTML = g;
btn.innerHTML = '重新上传';
}
}
function tuan_save_succeed() {
document.location = '<?=$forward?>';
}
function select_tuan_mode(value) {
$('.maintable').find('tr').each(function (i) {
var modatt = $(this).attr('mode');
if(modatt) {
var j = modatt.split('|');
if(modatt.indexOf(value)>-1) {
$(this).show();
$(this).find('input').each(function () {
$(this).attr('validator_disable','N').attr('disabled',false);
});
} else {
$(this).hide();
$(this).find('input').each(function () {
$(this).attr('validator_disable','Y').attr('disabled',true);
});
}
}
});
}
function wholesale_price_create() {
var nums = $('[name=prices]').val();
nums = prompt("请输入产品数量和单价(格式:数量=单价,例如:5=100),多个数量请用\",\"逗号分隔;\n格式里每一组中的数量必须大与前一个组中的数量,单价要少于前一组中的单价,其中第一组即为成团数量和支付单价\n例如:5=100,10=90,20=80", nums);
if(wholesale_price_show(nums)) {
$('[name=prices]').val(nums);
}
}
function forestall_price_create() {
var nums = $('[name=prices]').val();
nums = prompt("请输入购买人的顺序和单价(格式:前多少名=单价,例如:5=100),多个数量请用\",\"逗号分隔;\n格式里每一组中的顺序必须大与前一个组中的顺序,"
+"单价要少于前一组中的单价,其中第一组即为成团数量和支付单价\n例如:5=80,10=90,20=100", nums);
if(forestall_price_show(nums)) {
$('[name=prices]').val(nums);
}
}
function wholesale_price_show(nums) {
if(!nums) return false;
nums = nums.replace(',',',');
var list = nums.split(',');
var _m = 1, _p = 0;
var cp = $('#wholesale_table_src').clone().attr('id','wholesale_table');
for (var i=0; i<list.length; i++) {
var s = list[i];
var ss = s.split('=');
if(ss.length!=2||!is_numeric(ss[0])||!is_numeric(ss[1])) {
alert('格式错误,请重新操作。');
return false;
}
ss[0] = parseInt(ss[0]);
if(_m >= ss[0]) {
alert('对不起,第'+(i+1)+'组中的数量('+ss[0]+')不能小于前一组的数量('+_m+')');
return false;
}
ss[1] = parseFloat(ss[1]);
if(i > 0 && ss[1] >= _p) {
alert('对不起,第'+(i+1)+'组中的价格('+ss[1]+')不能大于前一组的价格('+_p+')');
return false;
}
cp.append(wholesale_price_add(i+1, _m, ss[0], ss[1]));
_m = parseInt (ss[0]) + 1;
_p = ss[1];
}
cp.append($('<tr></tr>').append(
$('<td></td>').attr('colspan',3).css({'color':'#808080','text-align':'center'}).
html('序号 <b>1</b> 为 成团数量 和 销售价格')
));
$('#wholesale_table_dst').empty().append(cp.show());
return true;
}
function forestall_price_show(nums) {
if(!nums) return false;
nums = nums.replace(',',',');
var list = nums.split(',');
var _m = 1, _p = 0;
var cp = $('#forestall_table_src').clone().attr('id','forestall_table');
for (var i=0; i<list.length; i++) {
var s = list[i];
var ss = s.split('=');
if(ss.length!=2||!is_numeric(ss[0])||!is_numeric(ss[1])) {
alert('格式错误,请重新操作。');
return false;
}
ss[0] = parseInt(ss[0]);
if(_m > ss[0]) {
alert('对不起,第'+(i+1)+'组中的数量('+ss[0]+')不能小于前一组的数量('+_m+')');
return false;
}
ss[1] = parseFloat(ss[1]);
if(i > 0 && ss[1] <= _p) {
alert('对不起,第'+(i+1)+'组中的价格('+ss[1]+')不能大于前一组的价格('+_p+')');
return false;
}
cp.append(forestall_price_add(i+1, _m, ss[0], ss[1]));
_m = parseInt (ss[0]) + 1;
_p = ss[1];
}
cp.append($('<tr></tr>').append(
$('<td></td>').attr('colspan',3).css({'color':'#808080','text-align':'center'})
));
$('#forestall_table_dst').empty().append(cp.show());
return true;
}
function wholesale_price_add(i,min,max,price) {
var tr = $('<tr></tr>').append($('<td align="center"></td>').html(i)).
append($('<td></td>').html('大于等于 ' + max)).
append($('<td align="right"></td>').html(price + ' 元'));
return tr;
}
function forestall_price_add(i,min,max,price) {
var tr = $('<tr></tr>').append($('<td align="center"></td>').html(i)).
append($('<td></td>').html(min +' - ' + max)).
append($('<td align="right"></td>').html(price + ' 元'));
return tr;
}
$(document).ready(function(){
select_tuan_mode($('[name=mode]').val());
if($('[name=mode]').val()=='wholesale') {
wholesale_price_show($('[name=prices]').val());
} else if($('[name=mode]').val()=='forestall') {
forestall_price_show($('[name=prices]').val());
}
});
</script>
<style type="text/css">
.forestall_table { border:1px solid #bbdcf1;border-bottom-width:0; }
#wholesale_table, #forestall_table { margin-bottom:5px; }
</style>
<div id="body">
<form method="post" action="<?=cpurl($module,$act,'save')?>" enctype="multipart/form-data" onsubmit="return validator(this);" name="postform" id="postform">
<div class="space">
<div class="subtitle">添加/编辑团购</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="altbg1" align="right" width="120"><span class="font_1">*</span>团购模式:</td>
<td width="290">
<select name="mode" onchange="select_tuan_mode(this.value);"<?if($op=='edit')echo' disabled="disabled"';?>>
<option value="normal"<?if($mode=='normal'||!$detail)echo' selected="selected"';?>>常规团</option>
<option value="average"<?if($mode=='average')echo' selected="selected"';?>>平摊团</option>
<option value="wholesale"<?if($mode=='wholesale')echo' selected="selected"';?>>批发团</option>
<option value="forestall"<?if($mode=='forestall')echo' selected="selected"';?>>抢鲜团</option>
</select>
<?if($detail['mode']):?><input type="hidden" name="mode" value="<?=$detail['mode']?>"><?endif;?>
</td>
<td class="altbg1" align="right" width="120"><span class="font_1">*</span>团购分类:</td>
<td width="*">
<select name="catid" validator="{'empty':'N','errmsg':'未完成 团购分类: 的设置,请设置。'}">
<option value="" selected="selected">==选择分类==</option>
<?=form_tuan_category($detail['catid']);?>
</select>
</td>
</tr>
<tr>
<td class="altbg1" align="right"><span class="font_1">*</span>团购城市:</td>
<td colspan="3">
<?if($admin->is_founder):?>
<select name="city_id" validator="{'empty':'N','errmsg':'未完成 团购城市 的设置,请返回设置。'}">
<option value="0">全局</option>
<?=form_city(isset($detail['city_id'])?$detail['city_id']:$_CITY['aid'])?>
</select>
<?else:?>
<input type="hidden" name="city_id" value="<?=$_CITY['aid']?>" />
<?=$_CITY['name']?>
<?endif;?>
</td>
</tr>
<tr>
<td class="altbg1" align="right"><span class="font_1">*</span>团购名称:</td>
<td width="*" colspan="3">
<input type="text" name="subject" class="txtbox" value="<?=$detail['subject']?$detail['subject']:($wish['title']?$wish['title']:'')?>" validator="{'empty':'N','errmsg':'未完成 团购名称 的设置,请返回设置。'}" />
</td>
</tr>
<tr>
<td class="altbg1" align="right"><span class="font_1">*</span>关联商家:</td>
<td colspan="3">
<div id="subject_search">
<?if($subject):?>
<a href="<?=url("item/detail/id/$sid")?>" target="_blank"><?=$subject['name'].($subject['subname']?"($subject[subname])":'')?></a>
<?endif;?>
</div>
<script type="text/javascript">
$('#subject_search').item_subject_search({
input_class:'txtbox2',
btn_class:'btn2',
result_css:'item_search_result',
<?if($subject):?>
sid:<?=$subject[sid]?>,
current_ready:true,
<?endif;?>
hide_keyword:true
});
</script>
</td>
</tr>
<tr>
<td class="altbg1" align="right"><span class="font_1">*</span>团购封面:</td>
<td colspan="3">
<?if(!$detail['thumb']):?>
<input type="file" name="picture" size="20" validator="{'empty':'N','errmsg':'未完成 团购封面 的设置,请返回设置。'}" />
<?else:?>
<span id="reload"><a href="<?=$detail['picture']?>" target="_blank" src="<?=$detail['thumb']?>" onmouseover="tip_start(this);"><?=$detail['thumb']?></a></span>
[<a href="javascript:reload();" id="switch">重新上传</a>]
<?endif;?>
</td>
</tr>
<tr mode="normal" style="display:none;">
<td class="altbg1" align="right"><span class="font_1">*</span>积分抵现金:</td>
<td><?=form_bool('use_ex_point',$detail['use_ex_point'])?> <span class="font_2">请先在模块配置里选择积分类型和比率</span></td>
<td class="altbg1" align="right"><span class="font_1">*</span>允许抵换现金额度:</td>
<td><?=form_input('use_ex_price',$detail['use_ex_price'],'txtbox4')?></td>
</tr>
<tr mode="average" style="display:none;">
<td class="altbg1" align="right"><span class="font_1">*</span>产品总价:</td>
<td><input type="text" name="total_price" value="<?=$detail['total_price']?>" class="txtbox4" validator="{'empty':'N','errmsg':'未完成 产品总价 的设置,请返回设置。'}"> <span class="font_2">总价除于购买人数即每人购买价</span></td>
<td class="altbg1" align="right"><span class="font_1">*</span>产品库存:</td>
<td><input type="text" name="goods_total" value="<?=$detail['goods_total']?>" class="txtbox4" validator="{'empty':'N','errmsg':'未完成 最高购买人数 的设置,请返回设置。'}"> <span class="font_2">销售总量,平坦团每人仅限购1件</span></td>
</tr>
<tr mode="normal|wholesale|forestall">
<td class="altbg1" align="right"><span class="font_1">*</span>产品总量:</td>
<td><input type="text" name="goods_total" class="txtbox4" value="<?=$detail['goods_total']?>" validator="{'empty':'N','errmsg':'未完成 产品总量 的设置,请返回设置。'}" />
<span class="font_2">下单成功后,库存将被减少</span></td>
<td class="altbg1" align="right"><span class="font_1">*</span>每人限购量:</td>
<td><input type="text" name="people_buylimit" class="txtbox4" value="<?=$detail['people_buylimit']?>" validator="{'empty':'N','errmsg':'未完成 每人限购量 的设置,请返回设置。'}" /></td>
</tr>
<tr mode="normal|average|forestall">
<td class="altbg1" align="right"><span class="font_1">*</span>成团人数:</td>
<td colspan="3"><input type="text" name="peoples_min" class="txtbox4" value="<?=$detail['peoples_min']?>" validator="{'empty':'N','errmsg':'未完成 成团人数 的设置,请返回设置。'}" />
<span class="font_2">团购成功的条件,成团人数必须要小于 产品总量÷每人限购量,否则产品销售完,也无法成团</span></td>
</tr>
<tr mode="normal|forestall">
<td class="altbg1" align="right"><span class="font_1">*</span>团购价格:</td>
<td><input type="text" name="price" class="txtbox4" value="<?=$detail['price']?$detail['price']:($wish['price']?$wish['price']:'')?>" validator="{'empty':'N','errmsg':'未完成 团购单价 的设置,请返回设置。'}" />
<span class="font_2">团购下单价格</span></td>
<td class="altbg1" align="right"><span class="font_1">*</span>市场价格:</td>
<td><input type="text" name="market_price" class="txtbox4" value="<?=$detail['market_price']?>" validator="{'empty':'N','errmsg':'未完成 市场价格 的设置,请返回设置。'}" /></td>
</tr>
<tr mode="wholesale" style="display:none;">
<td class="altbg1" align="right"><span class="font_1">*</span>价格策略:</td>
<td>
<input type="hidden" name="prices" value="<?=$detail['prices']?>" validator="{'empty':'N','errmsg':'未完成 价格策略 的设置,请返回设置。'}">
<div id="wholesale_table_dst"></div>
<input type="button" class="btn2" value="新建/编辑" onclick="wholesale_price_create();">
<table class="wholesale_table" border="0" border="0" cellspacing="0" cellpadding="0" style="display:none;" id="wholesale_table_src">
<tr style="background:#F0F8FF;">
<td width="30" align="center">序号</td>
<td width="80">数量(个)</td>
<td width="80" align="right">单价(元/个)</td>
</tr>
</table>
</td>
<td class="altbg1" align="right"><span class="font_1">*</span>市场价格:</td>
<td><input type="text" name="market_price" class="txtbox4" value="<?=$detail['market_price']?>" validator="{'empty':'N','errmsg':'未完成 市场价格 的设置,请返回设置。'}" /></td>
</tr>
<tr mode="forestall" style="display:none;">
<td class="altbg1" align="right"><span class="font_1">*</span>价格策略:</td>
<td>
<input type="hidden" name="prices" value="<?=$detail['prices']?>" validator="{'empty':'N','errmsg':'未完成 价格策略 的设置,请返回设置。'}">
<div id="forestall_table_dst"></div>
<input type="button" class="btn2" value="新建/编辑" onclick="forestall_price_create();">
<table class="forestall_table" border="0" border="0" cellspacing="0" cellpadding="0" style="display:none;" id="forestall_table_src">
<tr style="background:#F0F8FF;">
<td width="30" align="center">序号</td>
<td width="80">次序(人次)</td>
<td width="80" align="right">单价(元/个)</td>
</tr>
</table>
</td>
<td colspan="2">下单时用户支付的是上面的团购价格,在团购结束后,根据购买人的名次进行价格计算,并退还差价;如果购买人数超过了价格策略里设置的最大名次,则不产生差价,按上面设置的团购价格购买。</td>
</tr>
<tr>
<td class="altbg1" align="right"><span class="font_1">*</span>团购时间:</td>
<td colspan="3">
<input type="text" name="starttime" class="txtbox3" value="<?=$detail['starttime']?>" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})" />
~
<input type="text" name="endtime" class="txtbox3" value="<?=$detail['endtime']?>" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})" />
<?if($op=='edit'):?>
<input type="checkbox" name="update_endtime" id="update_endtime" value="1" /><label for="update_endtime">更新未付款订单的到期时间</label>
<?endif;?>
</td>
</tr>
<tr>
<td class="altbg1" align="right"><span class="font_1">*</span>发货方式:</td>
<td colspan="3">
<?=form_radio('sendtype',array('coupon'=>'团购券','express'=>'邮包/快递'),$detail['sendtype']?$detail['sendtype']:'coupon')?>
</td>
</tr>
<?if(!$detail['checked']):?>
<tr>
<td class="altbg1" align="right"><span class="font_1">*</span>活动审核:</td>
<td colspan="3"><?=form_bool('checked',$detail['checked']?$detail['checked']:1)?></td>
</tr>
<?endif;?>
<tr>
<td class="altbg1" align="right" valign="top"><span class="font_1">*</span>本团简介:</td>
<td colspan="3"><textarea name="intro" style="height:50px;"><?=$detail['intro']?></textarea></td>
</tr>
<tr>
<td class="altbg1" align="right" valign="top"><span class="font_1">*</span>详细介绍:</td>
<td colspan="3"><?=$edit_html?></td>
</tr>
<tr><td class="altbg2" colspan="4"><b><center>团购券设置(下单发送方式仅选择团购券时有效)</center></b></td></tr>
<tr>
<td class="altbg1" align="right">团购券有效期至:</td>
<td colspan="3">
<input type="text" name="expiretime" class="txtbox3" value="<?=$detail['expiretime']?>" onfocus="WdatePicker({dateFmt:'yyyy-MM-dd'})" />
<?if($op=='edit'):?>
<input type="checkbox" name="update_expiretime" id="update_expiretime" value="1" /><label for="update_expiretime">更新已发放团购券有效期</label>
<?endif;?>
</td>
</tr>
<tr>
<td class="altbg1" align="right" valign="top">打印团购券<br />地址电话信息:</td>
<td colspan="3"><textarea name="coupon_print[concact]" style="height:50px;"><?=$detail['coupon_print']['concact']?></textarea></td>
</tr>
<tr>
<td class="altbg1" align="right" valign="top">打印团购券<br />使用提示:</td>
<td colspan="3"><textarea name="coupon_print[message]" style="height:50px;"><?=$detail['coupon_print']['message']?></textarea></td>
</tr>
<tr>
<td class="altbg1" align="right" valign="top">
团购券短信发送内容:<br />
可用参数说明:<br />
<span class="font_1">{username}</span>:会员名<br />
<span class="font_1">{title}</span>:团购标题<br />
<span class="font_1">{id}</span>:券号<br />
<span class="font_1">{pw}</span>:券密码<br />
</td>
<td colspan="3">
<?if($detail['sms']):?>
<textarea name="sms" style="height:60px;"><?=$detail['sms']?></textarea>
<?else:?>
<textarea name="sms" style="height:60px;">您参与的团购活动:{title},您的团购券号:{id},密码:{pw}</textarea>
<?endif;?>
<div><span class="font_2">仅手机短信开启有效</span></div>
</td>
</tr>
</table>
</div>
<center>
<input type="hidden" name="do" value="<?=$op?>" />
<?if($op=='edit'):?>
<input type="hidden" name="tid" value="<?=$detail['tid']?>" />
<?endif;?>
<?if($wish):?>
<input type="hidden" name="twid" value="<?=$wish['twid']?>">
<?endif;?>
<input type="hidden" name="forward" value="<?=$forward?>" />
<input type="submit" name="dosubmit" value="提交" class="btn">
<button type="button" class="btn" onclick="document.location=document.referrer;">返回</button>
</center>
<?=form_end()?>
</div><file_sep>/core/modules/tuan/model/crule/meituan.php.bak
<?php
/*
* meituan rule
* rule:a=b
*
*/
$rule='response-deals-data=subject:limengqikey-deal-deal_title,
shortsubject:limengqikey-deal-name,
cityname:limengqikey-deal-city_id,
catname:limengqikey-deal-deal_cate,
subcatname:limengqikey-deal-deal_subcate,
oldprice:limengqikey-deal-value,
nowprice:limengqikey-deal-price,
starttime:limengqikey-deal-start_time,
lasttime:limengqikey-deal-end_time,
salesnum:limengqikey-deal-sales_num,
thumb:limengqikey-deal-deal_img,
url:limengqikey-deal-deal_url,
range:limengqikey-deal-deal_range,
desc:limengqikey-deal-deal_desc,
shopname:limengqikey-deal-deal_seller';
?>
<file_sep>/templates/item/sjstyle/article_list.php
<?exit?>
<!--{eval
$_HEAD['title'] = $MOD[name] . $_CFG['titlesplit'] . str_replace(' » ',$_CFG['titlesplit'],strip_tags($subtitle));
}-->
{template vip2_header}
<link href="{URLROOT}/img/shop/$subject[c_sjstyle]/style.css" rel="stylesheet" type="text/css" />
<!--头开始-->
<div class="header">
<div class="headerinfo">$subject[name] $subject[subname]</div>
<div class="headermeun">
<ul>
<li><div><a href="{url item/detail/id/$subject[sid]}">首页</a> </div></li>
<li><div><a href="{url item/vipabout/id/$subject[sid]}">店铺介绍</a> </div></li>
<li class="in"><div><a href="{url article/list/sid/$sid}">店铺动态</a> </div></li>
<li><div><a href="{url item/pic/sid/$subject[sid]}">店铺展示</a> </div></li>
<li><div><a href="{url product/list/sid/$sid}">产品展厅</a> </div></li>
<li><div><a href="{url coupon/list/sid/$sid}">优惠打折</a> </div></li>
<li><div><a href="{url item/vipvideo/id/$subject[sid]}">视频展播</a> </div></li>
<li><div><a href="{url item/vipcontact/id/$subject[sid]}">联系方式</a> </div></li>
</ul>
</div>
</div>
<!--头结束-->
<!--头部flash-->
<!--{if $subject[c_pictop1]}-->
<div style="margin:0 auto; width:976px;">
<SCRIPT src="{URLROOT}/img/shop/js/swfobject_source.js" type=text/javascript></SCRIPT>
<DIV id=flashFCI><A href="#" arget=_blank><IMG alt="" border=0></A></DIV>
<SCRIPT type=text/javascript>
var s1 = new SWFObject("{URLROOT}/img/shop/js/focusFlash_fp.swf", "mymovie1", "976", "150", "5", "#ffffff");
s1.addParam("wmode", "transparent");
s1.addParam("AllowscriptAccess", "sameDomain");
s1.addVariable("bigSrc", "$subject[c_pictop1]{if $subject[c_pictop2]}|$subject[c_pictop2]{/if}{if $subject[c_pictop3]}|$subject[c_pictop3]{/if}");
s1.addVariable("smallSrc", "|$subject[c_pictop1]|||");
s1.addVariable("href", "||");
s1.addVariable("txt", "||");
s1.addVariable("width", "976");
s1.addVariable("height", "150");
s1.write("flashFCI");
</SCRIPT>
</div>
<!--{/if}-->
<!--end头部flash-->
<div class="content">
<div class="pagejc">
<div class="col1">
<div class="titles">
<div class="fl">基本信息</div>
<div class="fr"></div>
<div class="clear"></div>
</div>
<div class="neirongs" style="padding:10px;">
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td align="center" valign="middle">
<a href="{url item/pic/sid/$subject[sid]}"><img src="{URLROOT}/{if $subject[thumb]}$subject[thumb]{else}static/images/noimg.gif{/if}" alt="$subject[name]" width="200" height="150" /></a>
</td>
</tr>
</table>
<div class="lefttitle">$subject[name]</div>
<div class="leftnr">
管 理 者:
<!--{if $subject[owner]}-->
<a href="{url space/index/username/$subject[owner]}" target="_blank">$subject[owner]</a>
<!--{elseif $catcfg[subject_apply]}-->
<a href="{url item/member/ac/subject_apply/sid/$subject[sid]}"><font color="#cc0000"><b>认领$model[item_name]</b></font></a>
<!--{/if}-->
<!--{if $catcfg[use_subbranch]}-->
<a href="{url item/member/ac/subject_add/subbranch_sid/$subject[sid]}">添加分店</a>
<!--{/if}--><br />
<!--{if $subject[finer]}-->
店铺级别:<img src="{URLROOT}/img/shop/eshop/vip$subject[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<!--{if $subject[c_tel]}-->
电 话:$subject[c_tel]<br />
<!--{/if}-->
<!--{if $subject[c_web]}-->
网 址:$subject[c_web]<br />
<!--{/if}-->
<!--{if $subject[c_add]}-->
店铺地址:$subject[c_add]<br />
<!--{/if}-->
访 问 量:<span class="font_2">$subject[pageviews]</span>次浏览<br />
加盟时间:{date $subject[addtime],'Y-m-d'} <br /><br />
<script type="text/javascript">loadscript('item');</script>
<a href="javascript:post_log($subject[sid]);"><img src="{URLROOT}/img/shop/other/bc_botton.gif" height="28" width="100"/></a>
<a href="javascript:add_favorite($subject[sid]);"><img src="{URLROOT}/img/shop/other/sc_botton.gif" height="28" width="72"/></a><br />
</div>
</div>
<div class="mq"></div>
</div> <!--col1end-->
<div class="col2">
<div class="titleb">
<div class="fl">店铺动态</div>
<div class="fr">
<!--{if $access_post}-->
<span class="review-ico"><a href="{url article/member/ac/article/op/add/role/$role}">我要投稿</a></span>
<!--{/if}-->
<!--{if $MOD['rss']}-->
<span class="rss-ico"><a href="{url article/rss/catid/$catid}">新闻聚合</a></span>
<!--{/if}-->
</div>
</div>
<div class="neirongb">
<!--{if $list}-->
{dbres $list $val}
<div class="article_s">
<em>{date $val[dateline]}</em>
<h2><a href="{url article/detail/id/$val[articleid]}">$val[subject]</a></h2>
<p>$val[introduce]...<a href="{url article/detail/id/$val[articleid]}">[阅读全文]</a></p>
<div><span>作者:$val[author]</span> <span>来源:$val[copyfrom]</span> <span>评论:$val[comments]</span></div>
</div>
{/dbres}
<div class="multipage">$multipage</div>
<!--{else}-->
<div class="messageborder">没有找到任何信息。</div>
<!--{/if}-->
</div>
</div><!--col2-->
<div class="clear"></div>
</div><!--pagejc-->
</div><!--content-->
</div><!--wrapper-->
{template vip2_footer}
<file_sep>/core/modules/tuan/admin/templates/wish_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="get" action="<?=SELF?>">
<input type="hidden" name="module" value="<?=$module?>" />
<input type="hidden" name="act" value="<?=$act?>" />
<input type="hidden" name="op" value="<?=$op?>" />
<div class="space">
<div class="subtitle">筛选</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100" class="altbg1">是否审核</td>
<td width="300">
<?=form_bool('status',$_GET['status']>0?1:0)?>
</td>
<td width="100" class="altbg1">所属城市</td>
<td width="*">
<?if($admin->is_founder):?>
<select name="city_id" onchange="select_city(this,'aid');">
<option value="">全部</option>
<?=form_city($_GET['city_id'])?>
</select>
<?else:?>
<?=$_CITY['name']?>
<?endif;?>
</td>
</tr>
<tr>
<td class="altbg1">标题</td>
<td><input type="text" name="title" value="<?=$_GET['title']?>" class="txtbox3"></td>
<td class="altbg1">是否已建团</td>
<td><?=form_bool('tid',$_GET['tid']>0?1:0)?></td>
</tr>
<tr>
<td class="altbg1">结果排序</td>
<td colspan="3">
<select name="offset">
<option value="20"<?=$_GET['offset']=='20'?' selected="selected"':''?>>每页显示20个</option>
<option value="50"<?=$_GET['offset']=='50'?' selected="selected"':''?>>每页显示50个</option>
<option value="100"<?=$_GET['offset']=='100'?' selected="selected"':''?>>每页显示100个</option>
</select>
<button type="submit" value="yes" name="dosubmit" class="btn2">筛选</button>
</td>
</tr>
</table>
</div>
</form>
<form method="post" action="<?=cpurl($module,$act)?>" name="myform">
<div class="space">
<div class="subtitle">自助团购管理</div>
<ul class="cptab">
<li<?=$_GET['status']?' class="selected"':''?>><a href="<?=cpurl($module,$act,'',array('status'=>1))?>">已审核</a></li>
<li<?=!$_GET['status']?' class="selected"':''?>><a href="<?=cpurl($module,$act,'',array('status'=>0))?>">未审核</a></li>
</ul>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y">
<tr class="altbg1">
<td width="25">选</td>
<td width="*">标题/操作</td>
<td width="80">期望价格</td>
<td width="90">发起用户</td>
<td width="110">发起时间</td>
<td width="60" style="text-align:center;">感兴趣人数</td>
<td width="60" style="text-align:center;">承接申请</td>
<td width="50" style="text-align:center;">已建团?</td>
<td width="50" style="text-align:center;">审核?</td>
</tr>
<?if($total && $list):?>
<?while($val=$list->fetch_array()):?>
<tr>
<td><input type="checkbox" name="twids[]" value="<?=$val['twid']?>"></td>
<td>
<div><?=$val['title']?></div>
<div>
<a href="<?=cpurl($module,$act,'edit',array('twid'=>$val['twid']))?>">详情/编辑</a>
<a href="<?=cpurl($module,'undertake','list',array('twid'=>$val['twid']))?>">承接申请管理</a>
<?if(!$val['tid']):?><a href="<?=cpurl($module,'tuan','add',array('twid'=>$val['twid']))?>">发起团购</a> <?endif;?>
</div>
</td>
<td><?=$val['price']?></td>
<td><a href="<?=url("space/index/uid/$val[uid]")?>" target="_blank"><?=$val['username']?></a></td>
<td><?=date('Y-m-d H:i',$val['dateline'])?></td>
<td style="text-align:center;"><?=$val['interest']?></td>
<td style="text-align:center;"><?=$val['undertakers']?></td>
<td style="text-align:center;"><?=$val['tid']?'√':'×'?></td>
<td style="text-align:center;"><?=$val['status']?'<span class="font_3">已审核</span>':'<span class="font_1">未审核</span>'?></td>
</tr>
<?endwhile;?>
<?else:?>
<tr><td colspan="10">暂无信息!</td></tr>
<?endif;?>
</table>
</div>
<div><?=$multipage?></div>
<center>
<input type="hidden" name="op" value="update" />
<input type="hidden" name="dosubmit" value="yes" />
<?if($total):?>
<button type="button" class="btn" onclick="easy_submit('myform','delete','twids[]')">删除所选</button>
<?if(!$_GET['status']):?>
<button type="button" class="btn" onclick="easy_submit('myform','checkup','twids[]')">审核所选</button>
<?endif;?>
<?endif;?>
</center>
</form>
</div><file_sep>/templates/item/vip/product_detail.php
<?exit?>
<!--{eval
$_HEAD['title'] = $detail[subject] . $subject[name] . $subject[subname];
}-->
<!--{template 'header', 'item', $subject[templateid]}-->
<link href="{URLROOT}/img/vipfiles/css/shopEx_$subject[c_vipstyle].css" rel="stylesheet" type="text/css" />
<body>
<div class="wrap">
<div id="header">
<div id="crumb">
<p id="crumbL"> <a href="{url modoer/index}">首页</a> » {print implode(' » ', $urlpath)}
<p id="crumbR"><a href="javascript:post_log($subject[sid]);">补充信息</a> | <a href="{url item/member/ac/subject_add/subbranch_sid/$subject[sid]}">增加分店</a> | <a href="{url member/index}">管理本店</a></p>
</div>
<div id="shopBanner">
<h1>$subject[name] $subject[subname]</h1>
<p>
<!--{if $subject[c_add]}-->
<B>地址:</B></LABEL>$subject[c_add]
<!--{/if}-->
<!--{if $subject[c_tel]}-->
<B>电话:</B></LABEL>$subject[c_tel]</p>
<!--{/if}-->
<div class="headerPic">
<img src="{if $subject[c_banner]}$subject[c_vipbanner]{else}{URLROOT}img/haibao/nonbanner.png{/if}" alt="$subject[name] $subject[subname]店铺海报" width="950" height="150"/>
</div>
</div>
<div id="nav">
<ul>
<!--
<li><a href="#"><span>Array</span></a></li>
<li><a href="#"><span></span></a></li>
<li class="special"><a href="#"><span>导航栏介绍</span></a></li>
-->
<li><a href="{url item/detail/id/$subject[sid]}"><span>首页</span></a></li>
<li><a href="{url article/list/sid/$subject[sid]}"><span>店铺资讯</span></a></li>
<li><a href="{url fenlei/list/sid/$subject[sid]}"><span>诚聘英才</span></a> </li>
<li class="current" ><a href="{url product/list/sid/$subject[sid]}"><span>产品展厅</span></a></li>
<li><a href="{url coupon/list/sid/$subject[sid]}"><span>优惠打折</span></a></li>
<li><a href="{url item/pic/sid/$subject[sid]}"><span>商家相册</span></a></li>
<li><a href="{url item/vipabout/id/$subject[sid]}"><span>关于我们</span></a></li>
<li><a href="{url item/vipreview/id/$subject[sid]}"><span>会员点评</span></a></li>
<li><a href="{url item/vipguestbook/id/$subject[sid]}"><span>留言板</span></a></li>
</ul>
</div>
</div>
<div id="smartAd"><img src="{if $subject[c_vipbanner2]}$subject[c_vipbanner2]{else}{URLROOT}img/haibao/non.png{/if}" alt="$subject[name] $subject[subname]店铺海报"/></a><br />
</div>
<div id="mainBody">
<div id="mainBodyL">
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>【$subject[name] $subject[subname]】</h2>
<p class="deafBoxTitMore"><a href="{url item/vipabout/id/$subject[sid]}">更多</a></p>
</div>
<div class="deafBoxCon">
<dl>
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td align="center" valign="middle">
<a href="{url item/pic/sid/$subject[sid]}"><img src="{URLROOT}/{if $subject[thumb]}$subject[thumb]{else}static/images/noimg.gif{/if}" alt="$subject[name]" width="270" height="200" /></a>
</td>
</tr>
</table>
<div class="leftnr">
<!--{if $subject[finer]}-->
店铺级别:<img src="{URLROOT}/img/vipfiles/img/vip$subject[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<div class="subject">
<h2><a href="{url item/detail/id/$sid}" src="$subject[thumb]" onMouseOver="tip_start(this,1);">$subject[name] $subject[subname]</a></h2>
<!--{eval $reviewcfg = $_G['loader']->variable('config','review');}-->
<p class="start start{print get_star($subject[avgsort],$reviewcfg[scoretype])}"></p>
<table class="subject_field_list" border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2"><span class="font_2">$subject[reviews]</span>点评,
<span class="font_2">$subject[guestbooks]</span>留言,
<span class="font_2">$subject[pageviews]</span>浏览</td>
</tr>
$subject_field_table_tr
</table>
<a class="abtn1" href="{url review/member/ac/add/type/item_subject/id/$subject[sid]}"><span>我要点评</span></a>
<a class="abtn2" href="javascript:add_favorite($sid);"><span>收藏</span></a>
<a class="abtn2" href="{url item/detail/id/$sid/view/guestbook}#guestbook"><span>留言</span></a>
<div class="clear"></div>
</dl>
</div></div>
<div id="position" class="deafBox">
<div class="deafBoxTit">
<h2>其他产品</h2>
</div>
<div class="deafBoxCon">
<!--{eval $sid=$subject[sid];}-->
<!--{datacallname:产品_主题产品}-->
</div>
</div>
</div>
<div id="chaBodyR">
<div id="chaBodyRTit">
<h2>商家产品</h2>
</div>
<div class="listCon">
<div id="product_vip_left">
<h1 class="title">$detail[subject]</h1>
<p class="t">发布时间:{date $detail[subject]}
人气:<span class="font_2">$detail[pageview]</span>
评论:<span class="font_2">$detail[comments]</span></p>
<div class="info">
<div class="field">
<table class="detail_field" border="0" cellspacing="0" cellpadding="0">
$detail_field
</table>
</div>
<div class="thumb">
<img src="{URLROOT}/$detail[thumb]" />
</div>
<div class="clear"></div>
</div>
<div class="content">
<h3>详细介绍:</h3>
<p class="c">$detail[content]</p>
</div>
<!--{if check_module('comment')}-->
<div class="comment_foo">
<style type="text/css">@import url("{URLROOT}/{$_G[tplurl]}css_comment.css");</style>
<script type="text/javascript" src="{URLROOT}/static/javascript/comment.js"></script>
<!--{eval $comment_modcfg = $_G['loader']->variable('config','comment');}-->
<!--{if $detail[comments]}-->
<!--{/if}-->
<a name="comment"></a>
<h3>网友评论:</h3>
{eval $_G['loader']->helper('form');}
<div id="comment_form">
<!--{if $user->check_access('comment_disable', $_G['loader']->model(':comment'), false)}-->
<!--{if $MOD[post_comment] && !$comment_modcfg['disable_comment'] && !$detail[closed_comment]}-->
<!--{eval $idtype = 'product'; $id = $pid; $title = 'Re:' . $detail[subject];}-->
{template comment_post}
<!--{else}-->
<div class="messageborder">评论已关闭</div>
<!--{/if}-->
<!--{else}-->
<div class="messageborder">如果您要进行评论信息,请先 <a href="{url member/login}">登录</a> 或者 <a href="{url member/reg}">快速注册</a> 。</div>
<!--{/if}-->
</div>
<!--{if !$comment_modcfg['hidden_comment']}-->
<div class="mainrail rail-border-3">
<em>评论总数:<span class="font_2">$detail[comments]</span>条</em>
<h1 class="rail-h-3 rail-h-bg-3">网友评论</h1>
<div id="commentlist" style="margin-bottom:10px;"></div>
<script type="text/javascript">
$(document).ready(function() { get_comment('product',$pid,1); });
</script>
</div>
<!--{/if}-->
</div>
<!--{/if}-->
</div> </div>
<div class="clear"></div>
</div>
<!--{template 'footer', 'item', $subject[templateid]}--><file_sep>/core/modules/tuan/admin/templates/discuss_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="post" action="<?=cpurl($module,$act,'save')?>" name="myform">
<div class="space">
<div class="subtitle">答复</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y">
<tr>
<td width="120" class="altbg1">提问</td>
<td width="*"><textarea name="content" style="height:100px;width:500px;"><?=$detail['content']?></textarea></td>
</tr>
<tr>
<td class="altbg1">答复</td>
<td><textarea name="reply" style="height:100px;width:500px;"><?=$detail['reply']?></textarea></td>
</tr>
</table>
</div>
<center>
<input type="hidden" name="id" value="<?=$id?>" />
<input type="hidden" name="forward" value="<?=get_forward()?>" />
<button type="submit" name="dosubmit" value="yes" class="btn">提交</button>
<button type="button" class="btn" onclick="history.go(-1);">返回</button>
</center>
</form>
</div><file_sep>/core/modules/modoer/item/mobile/top.php
<?php
$catid = isset($_GET['catid']) ? (int)$_GET['catid'] : (int)$MOD['pid'];
!$catid and location(url('item/mobile/do/category/p/top'));
//实例化主题类
$I =& $_G['loader']->model('item:subject');
$I->get_category($catid);
if(!$pid = $I->category['catid']) {
location(url('mobile/category'));
}
//载入配置信息
$catcfg =& $I->category['config'];
$modelid = $I->category['modelid'];
$rogid = $I->category['review_opt_gid'];
//载入模型
$model = $I->variable('model_' . $modelid);
//载入点评选项
$reviewpot = $_G['loader']->variable('opt_' . $rogid, 'review');
$reviewcfg = $_G['loader']->variable('config','review');
$header_title='排行榜';
include mobile_template('item_top');
?><file_sep>/tuandh.php
<?php
if(!defined('MUDDER_ROOT')) {
require dirname(__FILE__).'/core/init.php';
}
include template('tuandh_index');
?><file_sep>/core/modules/coupon/mobile/list.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'coupon');
// 实例化主题类
$C = & $_G ['loader']->model ( ':coupon' );
$f = (int) $_GET['f'];
if ($_GET["userWxId"]) {
$userWxId=$_GET["userWxId"];
}
//查询条件
$where = array ();
//获取优惠方式
//获取优惠方式
$bankid = (int) $_GET['bankid'];
//快讯
if($f==1) $where['c.catid1'] = 1;
//优惠券
if($f==2) $where['c.catid1'] = 2;
//信用卡
if($f==3) {
if($bankid==12) {
$bankname='农业银行';
$where['c.catid1'] = 12;
}
elseif($bankid==13){
$bankname='中信银行';
$where['c.catid1'] = 13;
}
elseif($bankid==14){
$bankname='兴业银行';
$where['c.catid1'] = 14;
}
elseif($bankid==15){
$bankname='招商银行';
$where['c.catid1'] = 15;
}
elseif($bankid==16){
$bankname='交通银行';
$where['c.catid1'] = 16;
}
else {
$bankname='招商银行';
$where['c.catid1'] = 15;
}
}
//获取优惠类
$catid = (int) $_GET['catid'];
if($catid==0){
$where['c.catid'] = 11;//默认为美食
$sel_catid='美食';
}else{
$where['c.catid'] = $catid;
$temp = & $_G ['loader']->model ( 'coupon:category' );
$aa=$temp->read($catid);
$sel_catid=$aa['name'];
}
$where['c.city_id'] = array(8);
//$where['status'] = array('where_not_equal',array('0'));
//区域信息
$sonaid='';
$aid = ( int ) $_GET ['aid'];
if($aid==0){
$sel_aid='全部商区';
}else{
//统一使用区域的子区域查询
$areas = $_G ['loader']->variable ( 'area_' . $_CITY ['aid'], null, false );
$paid=$areas[$aid]['pid'];
$sel_aid=$areas[$aid]['name'];
//顶级区划
if($paid==8){
foreach($areas as $area){
if($area[pid]==$aid){
$sonaid=$sonaid.$area[aid];
}
}
}else{
$sonaid=$aid;
}
$where['s.aid'] = explode(',',$sonaid);
}
//查询数据
$where['c.status'] = 1;
$offset = $MOD['listnum'] > 0 ? $MOD['listnum'] : 10;
$start = get_start($_GET['page'], $offset);
$select = 'DISTINCT c.sname,c.couponid,c.city_id,c.catid,c.sid,c.thumb,c.subject,c.starttime,c.endtime,c.des,c.comments,c.pageview,c.effect1,c.picture,c.content,c.saddress,c.sprice,c.bank,c.tel';
$orderbylist = array('effect1'=>'DESC', 'pageview'=>'DESC', 'dateline'=>'DESC', 'comments'=>'DESC');
$orderby = isset ( $_GET ['px'] ) ? $_GET ['px'] : 'finer';
!in_array($orderby,array_keys($orderbylist)) && $orderby = 'dateline';
//获取排序名称
if($orderby=='dateline'){
$ordername='默认排序';
}elseif($orderby=='effect1'){
$ordername='按评分从高到底';
}elseif($orderby=='pageviews'){
$ordername='按评分从低到高';
}else{
$ordername='默认排序';
}
list($total, $list) = $C->find($select, $where, array('c.'.$orderby => $orders[$orderby]), $start, $offset, TRUE, 's.name,s.subname,s.reviews,s.aid');
if($total>10) $multipage = mobile_page($total, $offset, $_GET['page'], url("coupon/mobile/do/list/catid/$catid/aid/$aid/order/$order/type/$type/num/$num/f/$f/total/$total/page/_PAGE_"));
//模版切换
$op = _input('op');
//进入筛选页面
if ($op == 'filter') {
if($f==3) include mobile_template('credit_list_filter');
if($f==2||$f==1) include mobile_template('coupon_list_filter');
exit;
}
//显示模版
if($_G['in_ajax'] && _input('waterfall')=='Y') {
if($f==3) $tplname = 'credit_list_li';
if($f==2) $tplname = 'coupon_list_li';
if($f==1) $tplname = 'coupon_list_li';
} else {
if($f==3) $tplname = 'credit_list';
if($f==2) $tplname = 'coupon_list';
if($f==1) $tplname = 'coupon_list';
}
include mobile_template($tplname);
// 解析区划名称
function get_aname($val) {
global $areas;
return $areas[$val]['name'];;
}
// 解析分类名称
function get_cname($val) {
global $cats;
return $cats[$val]['name'];
}
?>
<file_sep>/core/modules/tuan/model/discuss_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_tuan_discuss extends ms_model {
var $table = 'dbpre_tuan_discuss';
var $key = 'id';
var $model_flag = 'tuan';
function __construct() {
parent::__construct();
$this->model_flag = 'tuan';
$this->init_field();
$this->modcfg = $this->variable('config');
}
function msm_tuan_discuss() {
$this->__construct();
}
function init_field() {
$this->add_field('tid,content,sort,reply');
$this->add_field_fun('content,reply', '_T');
$this->add_field_fun('tid,sort', 'intval');
}
function cplist($where = null) {
$tid = (int) _get('tid');
$status = (int) _get('status');
$this->db->join($this->table,'dd.tid','dbpre_tuan','d.tid');
$tid && $this->db->where('dd.tid', $tid);
if($where) $this->db->where($where);
$this->db->where('dd.status', $status);
$result = array(0,'','');
if($result[0] = $this->db->count()) {
$this->db->sql_roll_back('from,where');
$this->db->select('dd.*,d.subject,d.city_id');
$this->db->order_by('dd.dateline','DESC');
$page = (int)_get('page',1);
$offset = (int)_get('offset',30);
$this->db->limit(get_start($page, $offset), $offset);
$result[1] = $this->db->get();
$result[2] = multi($result[0], $offset, $page, cpurl($_GET['module'],$_GET['act'],'',$_GET));
}
return $result;
}
function getlist($tid=0,$sort=1,$offset=20) {
$this->db->from($this->table);
if($tid) $this->db->where('tid', $tid);
$this->db->where('sort', $sort);
$this->db->where('status', 1);
$result = array(0,'','');
if($result[0] = $this->db->count()) {
$this->db->sql_roll_back('from,where');
$this->db->select('id,tid,uid,username,dateline,content,reply');
$this->db->order_by('dateline', 'DESC');
$this->db->limit(get_start($_GET['page'],$offset), $offset);
$result[1] = $this->db->get();
$result[2] = multi($result[0], $offset, $_GET['page'], url("discuss/list/id/$tid/sort/$sort/page/_PAGE_"));
}
return $result;
}
function save($post, $id=null) {
$edit = $id > 0;
if($edit) {
if(!$detail = $this->read($id)) redirect('tuan_discuss_empty');
if(!$this->in_admin && isset($post['reply'])) {
unset($post['reply']);
}
$post['status'] = strlen($post['reply']) > 0 ? 1 : 0;
} else {
$post['dateline'] = $this->global['timestamp'];
$post['uid'] = $this->global['user']->uid;
$post['username'] = $this->global['user']->username;
$post['status'] = 0;
}
$id = parent::save($post,$id);
return $id;
}
//回复
function replay($id, $content) {
}
//当前会员购买数量
function member_buy_total($uid,$tid) {
}
//检测
function check_post($post, $edit = false) {
if(!$this->in_admin && !$this->global['user']->uid) redirect('member_not_login');
if(!$post['content']) redirect('tuan_discuss_content_empty');
}
//数量
function count($tid=0) {
$this->db->from($this->table);
if($tid>0) $this->db->where('tid', $tid);
$this->db->where('status', 1);
return $this->db->count();
}
}
?><file_sep>/core/modules/tuan/model/sms/sms_powereasy_class.php
<?php
/**
* 动易短信接口
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
class sms_powereasy extends msm_sms_base {
var $url = '';
var $username = '';
var $key = '';
var $customstr = '';
function sms_powereasy($params) {
$this->__construct($params);
}
//构造函数,参数 param 为短信接口帐号
function __construct($params) {
parent::__construct($params);
$this->url = 'http://sms.powereasy.net/MessageGate/Message.aspx';
$this->set_account($params); //设置短信帐号
}
//设置短信帐号
function set_account($params) {
if(!$params['sms_powereasy_username']) redirect('tuan_sms_id_empty');
if(!$params['sms_powereasy_md5key']) redirect('tuan_sms_key_empty');
$this->username = $params['sms_powereasy_username'];
$this->key = $params['sms_powereasy_md5key'];
if($params['customstr']) $this->customstr = $params['customstr'];
if($params['url']) $this->url = $params['url'];
}
//发送短信息
function send($mobile, $message) {
if(!$mobile) redirect('tuan_sms_mobile_empty');
if(!$message) redirect('tuan_sms_content_empty');
if(strtolower($this->global['charset']) != 'utf-8' && $this->global['in_ajax']) {
$this->loader->lib('chinese', NULL, FALSE);
$CHS = new ms_chinese('utf-8', $this->global['charset']);
$message = $message ? $CHS->Convert($message) : '';
}
$params = $this->_createParam($mobile, $message);
return $this->_send($params);
}
//生成短信接口的参数格式
/*
可以同时向多人发送短信。每一行为一个手机号码
一行中可使用逗号或空格分隔多个信息,分别对应内容中{$1} {$2} {$3}……
mobile:
13800000000,张三,2380[回车换行]
13800000000,李四,2000
message:
{$2},你本月的工资为{$3}
*/
function _createParam($mobile, $message) {
//因动易对PHP的UTF-8编码不支持,因此专为gbk
if(strtolower($this->global['charset']) != 'gb2312') {
$this->loader->lib('chinese', NULL, FALSE);
$CHS = new ms_chinese($this->global['charset'], 'gb2312');
$mobile = $CHS->Convert($mobile);
$message = $CHS->Convert($message);
}
$id = $this->_create_id();
$params = array (
'ID' => $id,
'UserName' => $this->username,
'Key' => $this->key,
'SendNum' => $mobile,
'Content' => $message,
'SendTiming' => 0,
'SendTime' => '',
'Reserve' => $this->customstr,
);
$params['MD5String'] = md5(implode('', $params));
unset($params['Key']);
return $params;
}
//生成一个短信发送的句柄id
function _create_id() {
return $this->username . '_' . $this->global['timestamp'] . '_' . mt_rand(10000000,99999999);
}
//通过http协议的post短信息,并返回api的反馈信息(写入log文件,以便调试)
function _send($data) {
$url = parse_url($this->url);
if (!isset($url['port'])) {
$url['port'] = "";
}
if (!isset($url['query'])) {
$url['query'] = "";
}
$encoded = "";
foreach($data as $k => $v) {
$encoded .= ($encoded ? "&" : "");
$encoded .= rawurlencode($k)."=".rawurlencode($v);
}
$fp = @fsockopen($url['host'], $url['port'] ? $url['port'] : 80);
if (!$fp) {
$this->_log_result("Failed to open socket to $url[host]");
return 0;
}
fputs($fp, sprintf("POST %s%s%s HTTP/1.0\n", $url['path'], $url['query'] ? "?" : "", $url['query']));
fputs($fp, "Host: $url[host]\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\n");
fputs($fp, "Content-length: " . strlen($encoded) . "\n");
fputs($fp, "Connection: close\n\n");
fputs($fp, "$encoded\n");
$line = fgets($fp, 1024);
if (!eregi("^HTTP/1\.. 200", $line)) {
$this->_log_result($line);
return 0;
}
$results = ""; $inheader = 1;
while(!feof($fp)) {
$line = fgets($fp, 1024);
if ($inheader && ($line == "\n" || $line == "\r\n")) {
$inheader = 0;
}
if (!$inheader) {
$results .= $line;
}
}
fclose($fp);
$results = trim($results);
if($this->_return($results)) {
return true;
} else {
$this->_log_result($encoded, $results); //记录发送不成功的返回信息
return false;
}
}
//判断返回的短信息是否发送成功
function _return($value=null) {
//动易返回的判断信息是中文的,为了统一和繁体版批量转后后的判断,故编码为MD5来进行对比判断
if(md5($value) == 'fc4a5e487fc9d6d625cedad5e241fe95') {
return 1;
} else {
return 0;
}
}
// 日志消息,把返回的参数记录下来
function _log_result($params, $word='') {
if($fp = @fopen(MUDDER_ROOT . 'data' . DS . 'logs' . DS . "dysms_log.php", "a")) {
flock($fp, LOCK_EX) ;
fwrite($fp,"<?php exit();?>\r\ndate:".strftime("%Y-%m-%d %H:%M:%S", $this->global['timestamp'])."\r\n".$word."\r\n".$params."\r\n");
flock($fp, LOCK_UN);
fclose($fp);
}
}
}
?><file_sep>/core/modules/party/model/apply_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
class msm_party_apply extends ms_model {
var $table = 'dbpre_party_apply';
var $key = 'applyid';
var $model_flag = 'party';
var $sex = array(0,1,2);
var $status = array(0,1,2);
function __construct() {
parent::__construct();
$this->model_flag = 'party';
$this->init_field();
$this->modcfg = $this->variable('config');
}
function msm_party_apply() {
parent::__construct();
}
function init_field() {
$this->add_field('partyid,uid,username,linkman,contact,sex,status,comment');
$this->add_field_fun('partyid,uid,sex,status', 'intval');
$this->add_field_fun('username,linkman,contact,comment', '_T');
}
function save($post, $partyid = null) {
$post['uid'] = $this->global['user']->uid;
$post['username'] = $this->global['user']->username;
$post['dateline'] = $this->global['timestamp'];
$applyid = parent::save($post,$partyid);
$PARTY =& $this->loader->model(':party');
$PARTY->join($post['partyid'], 1);;
unset($PARTY);
return $applyid;
}
//取得报名会员
function member($partyid) {
if(!$partyid || !is_numeric($partyid)) return false;
$this->db->from($this->table);
$this->db->where('partyid', $partyid);
return $this->db->get();
}
//取得某个会有的报名活动
function myjoin($uid,$start=0, $offset=0, $ctotal=TRUE) {
$this->db->join($this->table,'pa.partyid','dbpre_party','p.partyid');
$this->db->where('pa.uid',$uid);
$result = array(0,false);
if($ctotal) $result[0] = $this->db->count();
if(!$ctotal || $result[0] > 0) {
if($ctotal) $this->db->sql_roll_back('from,where');
$this->db->select('pa.*,p.subject,p.aid,p.catid,p.flag,p.status,p.uid as ownerid,p.username as owner,begintime,endtime,thumb,num,pa.dateline');
$this->db->order_by('pa.dateline','DESC');
$this->db->limit($start,$offset);
$result[1] = $this->db->get();
}
return $result;
}
//报名检测
function check_post(&$post, $edit = false) {
if(!is_numeric($post['partyid']) || $post['partyid'] < 1) redirect('party_apply_partyid_empty');
if(!$post['linkman']) redirect('party_apply_linkman_empty');
if(!$post['contact']) redirect('party_apply_contact_empty');
if(!preg_match("/[0-9\-]+/",$post['contact'])) redirect('party_apply_contact_format');
if(!$post['sex']) redirect('party_apply_sex_empty');
$PARTY =& $this->loader->model(':party');
if(!$detail = $PARTY->read($post['partyid'])) redirect('party_empty');
if($detail['flag'] != '1') redirect('party_apply_join_stop');
if(!$this->global['timestamp'] >= $detail['joinendtime']) redirect('party_apply_jointime_invalid');
if($detail['statis']) redirect('party_apply_status_invalid');
if($detail['sex'] > 0 && $detail['sex'] != $post['sex']) redirect(lang('party_apply_sex_limit', lang('party_sex_'.$post['sex'])));
if($detail['uid'] == $post['uid']) redirect('party_apply_self_invalid');
if($this->check_join_exists($post['partyid'], $post['uid'])) redirect('party_apply_joined');
unset($PARTY);
}
function read_for_partyid_and_uid($partyid, $uid) {
$this->db->from($this->table);
$this->db->where('partyid',$partyid);
$this->db->where('uid',$uid);
return $this->db->get_one();
}
function dropout($partyid, $uid) {
$apply = $this->read_for_partyid_and_uid($partyid, $uid);
if(empty($apply)) return;
$this->db->from($this->table);
$this->db->where('applyid', $apply['applyid']);
$this->db->delete();
$this->db->from('dbpre_party');
$this->db->where('partyid',$partyid);
$this->db->set_dec('num', 1);
}
function delete($applyids) {
$ids = parent::get_keyids($applyids);
$this->_delete(array('applyid'=>$ids));
}
function delete_partyids($partyids) {
$ids = parent::get_keyids($partyids);
$this->_delete(array('partyid'=>$ids), FALSE);
}
function check_join_exists($partyid, $uid) {
$this->db->from($this->table);
$this->db->where('partyid', $partyid);
$this->db->where('uid', $uid);
return $this->db->count() > 0;
}
function _check_join_time($joinendtime) {
return $this->global['timestamp'] < $joinendtime;
}
function _delete($where,$up_total = TRUE) {
$this->db->from($this->table);
$this->db->where($where);
if(!$up_total) {
$this->db->delete();
return ;
}
$this->db->select('applyid,partyid');
if(!$q=$this->db->get()) return;
$deleteids = $partys = array();
while($v=$q->fetch_array()) {
$deleteids[] = $v['applyid'];
if(!$up_total) continue;
if(isset($partys[$v['partyid']])) {
$partys[$v['partyid']]++;
} else {
$partys[$v['partyid']] = 1;
}
}
if($partys) {
$PARTY =& $this->loader->model(':party');
foreach($partys as $id=>$num) {
$PARTY->join($id,$num,'dec');
}
}
if($deleteids) {
parent::delete($deleteids);
}
}
}
?><file_sep>/templates/item/vip/fenlei_detail.php
<?exit?>
<!--{eval
$_HEAD['title'] = $detail[subject];
}-->
<!--{template 'header', 'item', $subject[templateid]}-->
<script type="text/javascript">
function copyToClipboard(txt) {
if(window.clipboardData) {
window.clipboardData.clearData();
window.clipboardData.setData("Text", txt);
} else if(navigator.userAgent.indexOf("Opera") != -1) {
window.location = txt;
} else if (window.netscape) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
} catch (e) {
alert("被浏览器拒绝!\n请在浏览器地址栏输入'about:config'并回车\n然后将'signed.applets.codebase_principal_support'设置为'true'");
return;
}
var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
if (!clip)
return;
var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
if (!trans)
return;
trans.addDataFlavor('text/unicode');
var str = new Object();
var len = new Object();
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
var copytext = txt;
str.data = copytext;
trans.setTransferData("text/unicode",str,copytext.length*2);
var clipid = Components.interfaces.nsIClipboard;
if (!clip)
return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
alert("已复制到剪贴板。");
}
function AddFavorite(sURL, sTitle) {
try {
window.external.addFavorite(sURL, sTitle);
} catch (e) {
try {
window.sidebar.addPanel(sTitle, sURL, "");
} catch (e) {
alert("加入收藏失败,请使用Ctrl+D进行添加");
}
}
}
</script>
<link href="{URLROOT}/img/vipfiles/css/shopEx_$subject[c_vipstyle].css" rel="stylesheet" type="text/css" />
<div class="wrap">
<div id="header">
<div id="crumb">
<p id="crumbL"><a href="{url modoer/index}"><a href="{url modoer/index}">首页</a> » <a href="{url article/index}">$MOD[name]</a> » $subject[name] $subject[subname] » $detail[subject] » 正文
<p id="crumbR"><a href="javascript:post_log($subject[sid]);">补充信息</a> | <a href="{url item/member/ac/subject_add/subbranch_sid/$subject[sid]}">增加分店</a> | <a href="{url member/index}">管理本店</a></p>
</div>
<div id="shopBanner">
<h1>$subject[name] $subject[subname]</h1>
<p>
<!--{if $subject[c_add]}-->
<B>地址:</B></LABEL>$subject[c_add]
<!--{/if}-->
<!--{if $subject[c_tel]}-->
<B>电话:</B></LABEL>$subject[c_tel]</p>
<!--{/if}-->
<div class="headerPic">
<img src="{if $subject[c_vipbanner]}$subject[c_vipbanner]{else}{URLROOT}img/haibao/nonbanner.png{/if}" alt="$subject[name] $subject[subname]店铺海报" width="950" height="150"/>
</div>
</div>
<div id="nav">
<ul>
<!--
<li><a href="#"><span>Array</span></a></li>
<li><a href="#"><span></span></a></li>
<li class="special"><a href="#"><span>导航栏介绍</span></a></li>
-->
<li><a href="{url item/detail/id/$subject[sid]}"><span>首页</span></a></li>
<li><a href="{url article/list/sid/$subject[sid]}"><span>店铺资讯</span></a></li>
<li class="current" ><a href="{url fenlei/list/sid/$subject[sid]}"><span>诚聘英才</span></a></li>
<li><a href="{url product/list/sid/$subject[sid]}"><span>产品展厅</span></a></li>
<li><a href="{url coupon/list/sid/$subject[sid]}"><span>优惠打折</span></a></li>
<li><a href="{url item/pic/sid/$subject[sid]}"><span>商家相册</span></a></li>
<li><a href="{url item/vipabout/id/$subject[sid]}"><span>关于我们</span></a></li>
<li><a href="{url item/vipreview/id/$subject[sid]}"><span>会员点评</span></a></li>
<li><a href="{url item/vipguestbook/id/$subject[sid]}"><span>留言板</span></a></li>
</ul>
</div>
</div>
<div id="smartAd"><img src="{if $subject[c_vipbanner2]}$subject[c_vipbanner2]{else}{URLROOT}img/haibao/non.png{/if}" alt="$subject[name] $subject[subname]店铺海报"/></a><br />
</div>
<div id="mainBody">
<div id="mainBodyL">
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>【$subject[name] $subject[subname]】</h2>
<p class="deafBoxTitMore"><a href="{url item/vipabout/id/$subject[sid]}">更多</a></p>
</div>
<div class="deafBoxCon">
<dl>
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td align="center" valign="middle">
<a href="{url item/pic/sid/$subject[sid]}"><img src="{URLROOT}/{if $subject[thumb]}$subject[thumb]{else}static/images/noimg.gif{/if}" alt="$subject[name]" width="270" height="200" /></a>
</td>
</tr>
</table>
<div class="leftnr">
<!--{if $subject[finer]}-->
店铺级别:<img src="{URLROOT}/img/vipfiles/img/vip$subject[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<div class="subject">
<h2><a href="{url item/detail/id/$sid}" src="$subject[thumb]" onmouseover="tip_start(this,1);">$subject[name] $subject[subname]</a></h2>
<!--{eval $reviewcfg = $_G['loader']->variable('config','review');}-->
<p class="start start{print get_star($subject[avgsort],$reviewcfg[scoretype])}"></p>
<table class="subject_field_list" border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2"><span class="font_2">$subject[reviews]</span>点评,
<span class="font_2">$subject[guestbooks]</span>留言,
<span class="font_2">$subject[pageviews]</span>浏览</td>
</tr>
$subject_field_table_tr
</table>
<a class="abtn1" href="{url review/member/ac/add/type/item_subject/id/$subject[sid]}"><span>我要点评</span></a>
<a class="abtn2" href="javascript:add_favorite($sid);"><span>收藏</span></a>
<a class="abtn2" href="{url item/detail/id/$sid/view/guestbook}#guestbook"><span>留言</span></a>
<div class="clear"></div>
</dl>
</div>
</div>
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>其他招聘信息</h2>
</div>
<div class="deafBoxCon">
<dl>
<ul class="rail-list2">
{get:fenlei val=getlist(sid/$detail[sid]/row/10)}
<li><cite>{date $val[dateline],'m-d'}</cite><a href="{url fenlei/detail/id/$val[fid]}">{sublen $val[subject],10}</a></li>
{/get}
</ul>
</dl>
</div>
</div></div>
<div id="chaBodyR">
<div id="chaBodyRTit">
<h2>详细信息</h2>
</div>
<div id="article_vip_detail">
<div class="mainrail fenlei">
<div class="field">
<div class="head">
<!--{if $detail[endtime]<=$_G['timestamp']}-->
<em><span class="font_1"><strong>信息已过期</strong></span></em>
<!--{/if}-->
<h3>$detail[subject]</h3>
<div class="op">
发布者:<a href="{url space/index/suid/$val[uid]}">$detail[username]</a>
发布时间:{date $detail[dateline],'Y-m-d H:i'}
过期时间:{date $detail[endtime],'Y-m-d'}
<a href="#" onclick="AddFavorite(window.location.href,'$detail[subject]')">收藏</a>
<a href="#" onclick="copyToClipboard(window.location.href);">分享</a>
<a href="#" onclick="window.print();">打印</a></span>
</div>
</div>
<!--{if $detail_custom_field}-->
<table width="100%" border="0" cellspacing="0" cellpadding="0">
$detail_custom_field
</table>
<!--{/if}-->
</div>
<div class="info">{print nl2br($detail[content])}</div>
<!--{if $detail[thumb]}-->
<div class="pics"><a href="{URLROOT}/{print str_replace('thumb_', '', $detail[thumb])}" target="_blank"><img src="{URLROOT}/{$detail[thumb]}" /></a></div>
<!--{/if}-->
<div class="contcat">
<ul>
<li>联 系 人:$detail[linkman]</li>
<li>联系电话:$detail[contact]</li>
<li>电子邮箱:$detail[email]</li>
<li>QQ/MSN:$detail[im]</li>
<li>联系地址:$detail[address]</li>
</ul>
<div class="waring"><center>免责声明:本站只提供信息交流平台,各交易者自己审辨真假,本站不承担由此引起的法律责任。</center></div>
</div>
</div>
<!--
<div class="mainrail rail-border-3">
<h3 class="rail-h-3 rail-h-bg-3">会员评论</h3>
<table style="margin-top:10px" width="100%" class="post table">
<tr>
<td width="100" align="right" valign="top">评论内容:</td>
<td width="*"><textarea name="content" style="width:95%;height:80px;"></textarea></td>
</tr>
<tr><td> </td><td><input type="submit" value="发布评论" class="button" /></td></tr>
</table>
<div class="fenlei comment">
<div></div>
</div>
</div>
-->
</div>
<div class="clear"></div>
</div>
</div>
<div class="clear"></div>
</div>
<!--{template 'footer', 'item', $subject[templateid]}--><file_sep>/core/modules/modoer/item/admin/att_list.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(! defined ( 'IN_ADMIN' ) || ! defined ( 'IN_MUDDER' )) && exit ( 'Access Denied' );
$AL = & $_G ['loader']->model ( MOD_FLAG . ':att_list' );
$op = _input ( 'op' );
switch ($op) {
case 'update' :
$AL->update ( $_POST ['att_list'] );
$AL->write_cache ( _post ( 'catid' ) );
redirect ( 'global_op_succeed', get_forward ( cpurl ( $module, $act ) ) );
break;
case 'save' :
$catid = _post ( 'catid', null, 'intval' );
$names = _post ( 'names', null, '_T' );
$AL->save ( $catid, $names );
redirect ( 'global_op_succeed', cpurl ( $module, $act, '', array (
'catid' => $catid
) ) );
break;
case 'delete' :
$AL->delete ( $_POST ['attids'] );
$AL->write_cache ( _post ( 'catid' ) );
redirect ( 'global_op_succeed', get_forward ( cpurl ( $module, $act ) ) );
break;
case 'rebuild' :
if (! $catid = abs ( ( int ) $_GET ['catid'] ))
redirect ( lang ( 'global_sql_keyid_invalid', 'catid' ) );
$AL->rebuild ( $catid );
redirect ( '成功重建','/admin.php?module=item&act=att_list&catid='.$catid);
break;
default :
if (! $catid = abs ( ( int ) $_GET ['catid'] ))
redirect ( lang ( 'global_sql_keyid_invalid', 'catid' ) );
$AT = & $_G ['loader']->model ( 'item:att_cat' );
if (! $cat = $AT->read ( $catid ))
redirect ( 'item_att_cat_empty' );
list ( , $list ) = $AL->find ( '*', array (
'catid' => $catid,
'type' => 'att'
), 'listorder', 0, 0, false );
$admin->tplname = cptpl ( 'att_list', MOD_FLAG );
break;
}
?><file_sep>/core/modules/tuan/model/crule/sohutuan.php
<?php
/*
* meituan rule
*
*/
$rule='ActivitySet-Activity=subject:
limengqikey-Title,cityname:
limengqikey-CityName,url:
limengqikey-Url,nowprice:
limengqikey-Price,oldprice:
limengqikey-Value,lasttime:
limengqikey-EndTime,thumb:
limengqikey-ImageUrl,nowpeople:
limengqikey-Bought,starttime:
limengqikey-StartTime';
?><file_sep>/templates/default/tuan_faq.htm
<!--{eval
$_HEAD[title] = '常见问题';
}-->
{template tuan_header}
<div id="tuan_body">
<div class="layout">
<div id="content" class="content">
<div class="tuan-main-box">
<div class="tuan-main-box-top"></div>
<div class="tuan-main-box-body">
<div class="head">
<h2>常见问题</h2>
</div>
<div class="faq">
<div class="faqlist">
<dl>
<dt><a name="faq1"></a>{$MOD[name]}是什么?<span></span></dt>
<dd>{$MOD[name]}每天提供一单精品消费,为您精选餐厅、酒吧、KTV、SPA、美发店、瑜伽馆等特色商家,只要凑够最低团购人数就能享受无敌折扣。</dd>
<dt><a name="faq2"></a>今天的团购看起来不错,怎么购买?<span></span></dt>
<dd>只需在团购截止时间之前点击"购买"按钮,根据提示下订单付费购买即可。如果参加团购人数达到最低人数下限,则团购成交,您将得到我们的短信或邮件通知。</dd>
<dt><a name="faq3"></a>如何付款,安全么?<span></span></dt>
<dd>
{$MOD[name]}使用支付宝、财付通等主流第三方支付方式,确保交易安全:
<div class="paytype">
<p class="alipay">支付宝:推荐淘宝用户使用</p>
<p class="tenpay">财付通:无需注册,支持国内各大银行支付</p>
</div>
</dd>
<dt><a name="faq4"></a>如果参加团购人数不足,怎么办?<span></span></dt>
<dd>如果参加团购人数不足,则该次团购取消。已支付的款项,{$MOD[name]}将立即返还。您不会有任何损失,但失去了以超低折扣价享受精品消费的机会。如果您很希望这次团购成交,邀请您的朋友一起来购买吧~</dd>
<dt><a name="faq5"></a>什么是团购券,怎么使用?<span></span></dt>
<dd>团购券是当团购成功后,您以手机短信方式获取,或者自行下载打印使用的消费凭证(其中包含唯一优惠密码)。当您去消费时,出示该短信或者打印的团购券即可。</dd>
<dt><a name="faq6"></a>使用团购券时,能同时享用其他优惠么?<span></span></dt>
<dd>一般不可以。如果可以,我们会在团购提示里特别说明。</dd>
<dt><a name="faq7"></a>我购买的团购券,可以给其他人使用么?<span></span></dt>
<dd>当然可以!我们自己也会购买团购券送给朋友,给他/她一个惊喜 :)</dd>
<dt><a name="faq8"></a>积分有什么用?怎样获得积分?<span></span></dt>
<dd>通过在商家消费团购券,即可在网站上获得一定量的积分,您可以在网站”我的助手“里查看到您的积分,您可以用积分在网站上兑换精美的礼品!</dd>
<dt><a name="faq9"></a>如何退订{$MOD[name]}发给我的每日团购邮件?<span></span></dt>
<dd>如不想继续接收{$MOD[name]}每日推荐邮件,点击邮件上方的“取消订阅”即可!</dd>
<dt><a name="faq10"></a>什么情况下可以退款?<span></span></dt>
<dd>
您好,以下情况可以退款:<br />
1. 团购结束时没有凑够团购人数;<br />
2. 团购成功后,商家因意外原因临时出现停业或搬家的情况。(我们会挑选经营状况良好的商家作为{$MOD[name]}特约商家,一般不会出现这个情况。)
</dd>
</dl>
</div>
</div>
</div>
<div class="tuan-main-box-bottom"></div>
</div>
</div>
<div class="sidebar has-dashboard">
<div class="sbox-white">
<div class="sbox-top"></div>
<div class="sbox-body">
<div class="side-tip-help">
<p>
<a href="{url tuan/index}"><img src="{URLROOT}/{$_G[tplurl]}images/tuan/faq-how-it-works1.gif"></a>
<span>A 每天推出一单精品消费!</span>
</p>
<p>
<a href="{url tuan/index}"><img src="{URLROOT}/{$_G[tplurl]}images/tuan/faq-how-it-works2.gif"></a>
<span>B 凑够一定人数就能享受无敌折扣...邀请朋友一起来买吧!</span>
</p>
<p>
<a href="{url tuan/index}"><img src="{URLROOT}/{$_G[tplurl]}images/tuan/faq-how-it-works3.gif"></a>
<span>C 明天再来看,又有新惊喜!</span>
</p>
</div>
</div>
<div class="sbox-bottom"></div>
</div>
</div>
</div>
</div>
{template tuan_footer}<file_sep>/core/modules/discussion/inc/hook.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
class hook_discussion extends ms_base {
function __construct() {
parent::__construct();
}
function admincp_subject_edit_link($sid) {
$url = cpurl('discussion','topic','list',array('sid'=>$sid));
return array(
'flag' => 'discussion:topic',
'url' => $url,
'title'=> '交流话题管理',
);
}
function subject_detail_link(&$params) {
extract($params);
$result = array();
$result[] = array (
'flag' => 'discussion',
'url' => url('discussion/list/sid/'.$sid),
'title'=> lang('discussion_title'),
);
return $result;
}
}
?><file_sep>/core/modules/party/admin/menus.inc.php
<?php
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$modmenus = array(
'party|模块配置|config',
'party|类别管理|category',
'party|活动审核|party|checklist',
'party|照片审核|picture|checklist',
'party|活动管理|party',
'party|留言管理|comment',
'party|图片管理|picture',
'party|报名管理|apply',
);
?><file_sep>/core/modules/tuan/inc/index_hook.php
<?php
return array(
'list' => '进行中的团购',
'wish' => '自助团购',
);
<file_sep>/core/modules/weixin/admin/menus.inc.php
<?php
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$modmenus = array(
'coupon|模块配置|config',
'coupon|分类管理|category',
'coupon|优惠信息审核|coupon|checklist',
'coupon|优惠信息列表|coupon|list',
'coupon|添加优惠信息|coupon|add',
);
?><file_sep>/templates/item/vip/about.php
<?exit?>
{template vip_header}
<link href="{URLROOT}/img/vipfiles/css/shopEx_$detail[c_vipstyle].css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
loadscript('swfobject');
$(document).ready(function() {
if(!$.browser.msie && !$.browser.safari) {
var d = $("#thumb");
var dh = parseInt(d.css("height").replace("px",''));
var ih = parseInt(d.find("img").css("height").replace("px",''));
if(dh - ih < 3) return;
var top = Math.ceil((dh - ih) / 2);
d.find("img").css("margin-top",top+"px");
}
<!--{if $MOD['show_thumb'] && $detail['pictures']}-->
get_pictures($sid);
<!--{/if}-->
get_membereffect($sid, $modelid);
});
</script>
<script language="JavaScript" type="text/javascript"><!--//--><![CDATA[//><!--
function CopyURL(){
var myHerf=top.location.href;
var title=document.title;
if(window.clipboardData){
var tempCurLink=title + "\n" + myHerf;
var ok=window.clipboardData.setData("Text",tempCurLink);
if(ok) alert("现在按Ctrl + V 粘贴到QQ上发给您的好友们吧 !");
}else{alert("对不起,目前此功能只支持IE,请直接复制地址栏的地址!");}
}
//--><!]]></script>
<script type="text/javascript">
function disq(){
$("#caja").slideToggle();
}
function disq1(){
$("#caja").slideUp();
}
function disq22(){
$("#caja2").slideToggle();
}
function disq222(){
$("#caja2").slideUp();
}
function disq33(){
$("#caja3").slideToggle();
}
function disq333(){
$("#caja3").slideUp();
}
</script>
<body>
<div class="wrap">
<div id="header">
<div id="crumb">
<p id="crumbL"><a href="{url modoer/index}">首页</a> » {print implode(' » ', $urlpath)} » $detail[name] $detail[subname]
<p id="crumbR"><a href="javascript:post_log($detail[sid]);">补充信息</a> | <a href="{url item/member/ac/subject_add/subbranch_sid/$detail[sid]}">增加分店</a> | <a href="{url member/index}">管理本店</a></p>
</div>
<div id="shopBanner">
<h1>$detail[name] $detail[subname]</h1>
<p>
<!--{if $detail[c_add]}-->
<B>地址:</B></LABEL>$detail[c_add]
<!--{/if}-->
<!--{if $detail[c_tel]}-->
<B>电话:</B></LABEL>$detail[c_tel]</p>
<!--{/if}-->
<div class="headerPic">
<img src="{if $detail[c_vipbanner]}$detail[c_vipbanner]{else}{URLROOT}img/haibao/nonbanner.png{/if}" alt="$detail[name] $detail[subname]店铺海报" width="950" height="150"/>
</div>
</div>
<div id="nav">
<ul>
<!--
<li><a href="#"><span>Array</span></a></li>
<li><a href="#"><span></span></a></li>
<li class="special"><a href="#"><span>导航栏介绍</span></a></li>
-->
<li><a href="{url item/detail/id/$detail[sid]}"><span>首页</span></a></li>
<li><a href="{url article/list/sid/$sid}"><span>店铺资讯</span></a> </li>
<li><a href="{url fenlei/list/sid/$sid}"><span>诚聘英才</span></a> </li>
<li><a href="{url product/list/sid/$sid}"><span>产品展厅</span></a> </li>
<li><a href="{url coupon/list/sid/$sid}"><span>优惠打折</span></a> </li>
<li><a href="{url item/pic/sid/$detail[sid]}"><span>商家相册</span></a> </li>
<li class="current" ><a href="{url item/vipabout/id/$detail[sid]}"><span>关于我们</span></a></li>
<li><a href="{url item/vipreview/id/$detail[sid]}"><span>会员点评</span></a></li>
<li><a href="{url item/vipguestbook/id/$detail[sid]}"><span>留言板</span></a></li>
</ul>
</div>
</div>
<div id="smartAd"><img src="{if $detail[c_vipbanner2]}$detail[c_vipbanner2]{else}{URLROOT}img/haibao/non.png{/if}" alt="$detail[name] $detail[subname]店铺海报"/></a><br />
</div>
<div id="mainBody">
<div id="mainBodyL">
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>【$detail[name] $detail[subname]】</h2>
</div>
<div class="deafBoxCon">
<dl>
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td valign="top">
<a href="{url item/pic/sid/$detail[sid]}"><img src="{URLROOT}/{if $detail[thumb]}$detail[thumb]{else}static/images/noimg.gif{/if}" alt="$detail[name]" width="110" height="80" /></a>
</td>
<td valign="top">
<!--{loop $reviewpot $val}-->$val[name]:<img src="{URLROOT}/img/vipfiles/img/z{print cfloat($detail[$val[flag]])}.gif" alt="{print cfloat($detail[$val[flag]])} 分" /><br /><!--{/loop}-->
综合:<img src="{URLROOT}/img/vipfiles/img/z{print cfloat($detail[avgsort])}.gif" alt="{print cfloat($detail[avgsort])} 分" />
</td>
</tr>
</table>
<!--{if $detail[finer]}-->
店铺级别:<img src="{URLROOT}/img/vipfiles/img/vip$detail[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
</dl>
</div>
</div>
<div id="position" class="deafBox">
<div class="deafBoxTit">
<h2>商户所在位置</h2>
</div>
<div class="deafBoxCon">
<!--{eval $mapparam = array(
'width' => '270',
'height' => '265',
'title' => $subject[name] . $subject[subname],
'show' => $detail[mappoint]?1:0,
);}-->
<iframe id="item_map" src="{url index/map/width/270/height/150/title/$mapparam[title]/p/$detail[mappoint]/show/$mapparam[show]}" frameborder="0" scrolling="no"></iframe>
<div align="center"> <span><!--{if !$detail['mappoint']}--><a href="javascript:post_map($detail[sid], $detail[pid]);">地图未标注,我来标注</a><!--{else}--><a href="javascript:show_bigmap();">查看大图</a> <a href="javascript:post_map($detail[sid], $detail[pid]);">报错</a><!--{/if}--></span></div>
<script type="text/javascript">
function show_bigmap() {
var src = "{url index/map/width/600/height/400/title/$mapparam[title]/p/$detail[mappoint]/show/$mapparam[show]}";
var html = '<iframe src="' + src + '" frameborder="0" scrolling="no" width="100%" height="400" id="ifupmap_map"></iframe>';
dlgOpen('查看大图', html, 600, 450);
}
</script>
</div>
</div>
</div>
<div id="chaBodyR">
<div id="chaBodyRTit">
<h2>商家信息</h2>
</div>
<div class="deafBoxCon">
<div class="winFloat">
<div class="body">
<ul class="field">
<!--{if $detail_custom_field}-->
<li>
<table class="custom_field" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class='key' align='left'>得分:</td>
<td width="*">
<!--{loop $reviewpot $val}-->$val[name]:<span class="font_2" style="font-size:16px;">{print cfloat($detail[$val[flag]])}</span><!--{/loop}--> 回头率:<span class="font_1" style="font-size:16px;"><strong>{print cfloat($detail[avgsort])}</strong></span>
<!--{if $detail[avgsort]>=4}--><span class="font_66"><strong>好评</strong> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-good.gif" title="好评" /> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-good.gif" title="好评" /> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-good.gif" title="好评" /></span>
<!--{elseif $detail[avgsort]>=3}--><span class="font_66"><strong>好评</strong> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-good.gif" title="好评" /> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-good.gif" title="好评" /></span>
<!--{elseif $detail[avgsort]>=2}--><span class="font_66"><strong>好评</strong> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-good.gif" title="好评" /></span>
<!--{elseif $detail[avgsort]>=1}--><span class="font_77"><strong>中评</strong> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-neu.gif" title="中评" /></span>
<!--{elseif $detail[avgsort]==0}--><!--{else}--><span class="font_88"><strong>差评</strong> <img src="{URLROOT}/{$_G[tplurl]}pic/cmt-bad.gif" title="差评" /></span><!--{/if}-->
</td>
</tr>
$detail_custom_field
<!--{if $catcfg[useeffect]}-->
<tr>
<td class='key' align='left'>会员参与:</td>
<td width="*">
<!--{if $catcfg[effect1]}-->
有 <span id="num_effect1" class="font_2">0</span> 位会员{$catcfg[effect1]}(<a href="javascript:post_membereffect($sid,'effect1');">我{$catcfg[effect1]}</a>,<a style=" text-decoration:underline;" href="javascript:get_membereffect($sid,'effect1','Y');">查看</a>) ,
<!--{/if}-->
<!--{if $catcfg[effect2]}-->
有 <span id="num_effect2" class="font_2">0</span> 位会员{$catcfg[effect2]}(<a href="javascript:post_membereffect($sid,'effect2');">我{$catcfg[effect2]}</a>,<a style=" text-decoration:underline;" href="javascript:get_membereffect($sid,'effect2','Y');">查看</a>) .
<!--{/if}-->
</td>
</tr>
<tr>
<td class='key' align='left'>{$model[item_name]}印象:</td>
<td width="*">
<span id="subject_impress">
<!--{get:item val=impress(sid/$sid/orderby/total DESC/rows/5)}-->
<span class="{print:item tagclassname(total/$val[total])}">$val[title]</span>
<!--{getempty(val)}-->
暂无信息
<!--{/get}-->
<!--{if count($_QUERY[get_val])>=4}-->
<span class="arrow-ico"><a href="javascript:item_impress_get($sid,1);">更多</a></span>
<!--{/if}-->
</span>
</td>
</tr>
<!--{if !$MOD[close_detail_total]}-->
<tr>
<td class='key' align='left'>数据统计:</td>
<td width="*">
<span class="font_2">$detail[pageviews]</span>次浏览,<span class="font_2">$detail[reviews]</span>条点评,<span class="font_2">$detail[guestbooks]</span>条留言,<span class="font_2">$detail[pictures]</span>张图片{if $detail[products]},<span class="font_2">$detail[products]</span>个产品{/if}<!--{if $detail[creator]}-->,<span style="color:#CC3300">感谢<a style="color:#CC3300" href="{url space/index/username/$detail[creator]}" title="{date $detail[addtime]}">$detail[creator]</a>上传图片!</span><!--{/if}-->
</td>
</tr>
<!--{/if}-->
<!--{/if}-->
<!--{if $detail[reviews]<=0}-->
<!--{else}-->
<td class='key' align='left'>网友推荐:</td>
<td width="*">
{get:modoer val=table(table/dbpre_tag_data/select/*/where/id=$sid and tgid=1/orderby/tagid DESC/rows/5/cachetime/10)}<a href="{url item/tag/tagname/$val[tagname]}">$val[tagname]</a><span style="font-size:11px; color:#999999;">($val[total])</span> {/get} <a style="font-size:12px; color:#CA5515;" href="javascript:disq33()">查看全部</a><img style=" margin-left:2px; margin-bottom:3px;" src="{URLROOT}/{$_G[tplurl]}pic/city_li.jpg" />
<div class="clear"></div><div id="caja3">
<p style=" float:right; padding-bottom:10px;"><a href="javascript:disq333()"><img src="{URLROOT}/{$_G[tplurl]}pic/mini-close.gif" /></a></p>
<p>{get:modoer val=table(table/dbpre_tag_data/select/*/where/id=$sid and tgid=1/orderby/tagid DESC/rows/100/cachetime/10)}<a href="{url item/tag/tagname/$val[tagname]}">$val[tagname]</a><span style="font-size:11px; color:#999999;">($val[total])</span> {/get}</p></div>
</td>
</tr>
<!--{/if}-->
<!--{if $_CFG[sharecode]}-->
<tr>
<td class='key' align='left'>内容分享:</td>
<td width="*">
$_CFG[sharecode]
</td>
</tr>
<!--{/if}-->
</table>
</li>
<!--{/if}-->
<li>
<a class="abtn1" href="{url review/member/ac/add/type/item_subject/id/$sid}" onClick="return post_review($sid)"><span><b>我要点评</b></span></a>
<a class="abtn2" href="javascript:item_impress_add($sid);"><span>添加印象</span></a>
<a class="abtn2" href="javascript:post_log($detail[sid]);"><span>补充信息</span></a>
<a class="abtn2" href="javascript:add_favorite($detail[sid]);"><span>收藏商铺</span></a>
<!--{if check_module('article')}-->
<!--{eval $postarticle_url = $detail[ownerid] && $detail[ownerid] == $user->uid ? 'ownernews' : 'membernews';}-->
<a class="abtn2" href="{url article/member/ac/article/op/add/sid/$detail[sid]}"><span>发布资讯</span></a>
<!--{/if}-->
<!--{if !$detail[owner]}-->
<a class="abtn2" href="{url item/member/ac/subject_apply/sid/$detail[sid]}"><span>认领商铺</span></a>
<!--{/if}-->
<div class="clear"></div>
<p> </p>
<div class="mainrail rail-border-3 item">
<div class="rail-h-bg-shop header">
<em style="padding-top:5px;">
<span class="review-ico"> <a href="javascript:post_log($detail[sid]);">补充/纠错</a></span>
</em>
<h3 class="rail-h-3">详细介绍</h3> </div>
<div class="content" id="content">$detail[content]</div>
</div>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
{template vip_footer}<file_sep>/core/modules/coupon/model/consume_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_coupon_consume extends ms_model {
var $table = 'dbpre_coupon_print';
var $key = 'cid';
var $model_flag = 'coupon';
function __construct() {
parent::__construct ();
$this->model_flag = 'coupon';
$this->init_field ();
$this->modcfg = $this->variable ( 'config' );
}
function msm_coupon_card() {
$this->__construct ();
}
function init_field() {
$this->add_field ( 'couponid,uid,username,dateline,point,wxid,sid,money,money1,flag,dateline1' );
$this->add_field_fun ( 'couponid,sid', '_T' );
}
function save($post) {
$id = parent::save ( $post, null );
return $id;
}
function delete($cids) {
$ids = parent::get_keyids ( $cids );
if (! $delete_coupon)
return;
$cop = & $this->loader->model ( ':coupon' );
$cop->delete_catids ( $ids );
unset ( $cop );
parent::delete ( $ids );
}
function update() {
$this->db->from ( $this->table );
$this->db->where ( 'flag', '2' );
$this->db->where ( 'catid', $catid );
$this->db->update ();
}
function print_coupon($couponid) {
// 打印判断
$this->global ['user']->checK_access ( 'coupon_print', $this );
// 判断是否已经打印过
if ($id = $this->check_print ( $couponid, $this->global ['user']->uid ))
return;
// 增加打印次数
$this->db->from ( $this->table );
$this->db->set_add ( 'prints', 1 );
$this->db->where ( 'couponid', $couponid );
$this->db->update ();
// 添加打印数据
$this->save($post);
}
function check_print($couponid, $uid) {
$this->db->from ( $this->table_print );
$this->db->where ( 'couponid', $couponid );
$this->db->where ( 'uid', $uid );
if (! $result = $this->db->get_one ())
return false;
return $result ['id'];
}
}
?>
<file_sep>/core/modules/review/inc/index_hook.php
<?php
return array(
'list' => '列表页',
);
<file_sep>/core/modules/party/detail.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
define('SCRIPTNAV', 'party');
if(!$partyid = _get('id',null,'intval')) {
$partyid = _get('partyid',null,'intval');
}
!$partyid && redirect(lang('global_sql_keyid_invalid', 'id'));
$P =& $_G['loader']->model(':party');
if(!$detail = $P->read($partyid)) redirect('party_empty');
if(!$detail['status']) redirect('party_empty');
//判断是否当前内容所属当前城市,不是则跳转
if(check_jump_city($detail['city_id'])) location(url("city:$detail[city_id]/party/detail/id/$partyid"));
$party_owner = $user->isLogin && $detail[uid]>0 && $detail[uid] == $user->uid; //活动组织者
$PCM =& $_G['loader']->model('party:comment');
$PA =& $_G['loader']->model('party:apply');
$PP =& $_G['loader']->model('party:picture');
$op = _input('op');
// 留言
if(!$op || $op=='comment') {
$offfset = 10;
$start = get_start($_GET['page'], $offfset);
list($comment_total,$comments) = $PCM->find('commentid,uid,username,dateline,message,reply', array('partyid'=>$partyid), array('dateline'=>'DESC'), $start, $offfset, TRUE);
if($comment_total) {
$multipage = multi($comment_total, $offfset, $_GET['page'], url("party/detail/id/$partyid/page/_PAGE_"), '#comment', "get_party_comment($partyid,{PAGE})");
}
if($op=='comment') {
include template('party_detail_comment');
output();
}
}
if($detail['num'] > 0 && (!$op || $op=='apply')) {
$offfset = 100;
$apage = _input('apage',1, 'intval');
if($apage < 1) $apage = 1;
$start = get_start($apage, $offfset);
list($apply_total,$applys) = $PA->find('uid,username,dateline', array('partyid'=>$partyid), 'dateline', $start, $offfset, TRUE);
if($apply_total) {
$apply_multipage = multi($apply_total, $offfset, $apage, url("party/detail/id/$partyid/view/apply/page/_PAGE_"), '#party-tab');
}
$joined = $user->isLogin && $PA->check_join_exists($partyid, $user->uid);
}
if(!$op || $op == 'pic') {
$offfset = 20;
$ppage = _input('ppage',1, 'intval');
if($ppage < 1) $ppage = 1;
$start = get_start($ppage, $offfset);
list($pic_total,$pics) = $PP->find('uid,username,dateline,pic,thumb,title', array('partyid'=>$partyid,'status'=>1), 'dateline', $start, $offfset, TRUE);
if($pic_total) {
$pic_multipage = multi($pic_total, $offfset, $ppage, url("party/detail/id/$partyid/view/pic/ppage/_PAGE_"), '#party-tab');
}
}
$urlpath = array();
$urlpath[] = url_path($MOD['name'], url("party/index"));
if($detail['sid'] > 0) {
$S =& $_G['loader']->model('item:subject');
if(!$subject = $S->read($detail['sid'])) redirect('item_empty');
$subject_field_table_tr = $S->display_listfield($subject);
$urlpath[] = url_path(trim($subject['name'].' '.$subject['subname']), url("item/detail/id/$detail[sid]"));
}
$urlpath[] = url_path($detail['subject'], '');
$P->pageview($partyid);
//精彩回顾
$PC =& $_G['loader']->model('party:content');
$content = $PC->read($partyid);
$_HEAD['keywords'] = $MOD['meta_keywords'];
$_HEAD['description'] = $MOD['meta_description'];
include template('party_detail');
?><file_sep>/core/modules/fenlei/admin/templates/category_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript">
function expand(catid) {
$("table tr").each(function(i){
var len = catid.length + 4;
if(this.id && this.id.substr(0,len)=='tr_'+catid+'_') {
var s = $(this).css('display');
$(this).css('display', s == 'none' ? '' : 'none');
}
});
}
</script>
<div id="body">
<form method="post" name="myform" action="<?=cpurl($module,$act,'update')?>&">
<div class="space">
<div class="subtitle">分类管理</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr class="altbg1">
<td width="30">ID</td>
<td width="120">排序</td>
<td width="260">名称</td>
<?if($pid):?><td width="80">数量</td><?endif;?>
<td width="*">操作</td>
</tr>
<?if($list):?>
<?foreach($list as $value) :?>
<tr>
<td><?=$value['catid']?></td>
<td><input type="text" name="category[<?=$value['catid']?>][listorder]" value="<?=$value['listorder']?>" class="txtbox5" /></td>
<td><input type="text" name="category[<?=$value['catid']?>][name]" value="<?=$value['name']?>" class="txtbox3" /></td>
<?if($pid):?><td><?=$value['num']?></td><?endif;?>
<td>
<a href="<?=cpurl($module,$act,'edit',array('catid'=>$value['catid']))?>">编辑</a>
<a href="<?=cpurl($module,$act,'delete',array('catid'=>$value['catid']))?>" onclick="return confirm('本操作将删除本分类下的所有活动,您确定删除吗?');">删除</a>
<?if(!$value['pid']):?>
<a href="<?=cpurl($module,'field','list',array('pid'=>$value['catid']))?>">管理自定义字段</a>
<?else:?>
<a href="<?=cpurl($module,'field','select',array('catid'=>$value['catid']))?>">选择自定义字段</a>
<?endif;?>
<?if(!$value['pid']):?><a href="<?=cpurl($module,$act,'',array('pid'=>$value['catid']))?>">查看子分类</a><?endif;?></td>
</tr>
<? endforeach; ?>
<? else: ?>
<tr>
<td colspan="5">暂无信息。</td>
</tr>
<? endif; ?>
</table>
<center>
<?if($list):?>
<button type="submit" name="dosubmit" value="yes" class="btn" /> 提交更新 </button>
<?endif;?>
<button type="button" class="btn" onclick="location.href='<?=cpurl($module,$act,'add',array('pid'=>$pid))?>'" /> 增加分类 </button>
<?if($pid>0):?><button type="button" class="btn" onclick="location.href='<?=cpurl($module,$act)?>'" /> 返回 </button><?endif;?>
</center>
</div>
</form>
</div><file_sep>/templates/mobile1/js/fixed.js
/*=============================================================================
# FileName: f_position.js
# Desc: 一个滚动固定div的插件,IE6可用
# Author: HouYongZheng
# Home: http://www.sudohou.com
# Version: 0.0.1
# LastChange: 2013-04-13 15:35:26
# History:
=============================================================================*/
jQuery.f_position=function(div,pos){
/*!
参数说明:
div------------------需要进行定位的div元素,例如f_position(".fixed");
pos------------------定位位置参数,默认固定在浏览器窗口左上角;
参数详解
|
|________"l_t"-------默认,固定在浏览器窗口的左侧中间位置;
|
|________"l_c"-------固定在浏览器窗口的左侧中间位置;
|
|________"l_b"-------固定在浏览器窗口的左侧底部位置;
|
|________"b_c"-------固定在浏览器窗口的底部中间位置;
|
|________"r_b"-------固定在浏览器窗口的右侧底部位置;
|
|________"r_c"-------固定在浏览器窗口的右侧中间位置;
|
|________"r_t"-------固定在浏览器窗口的右侧顶部位置;
|
|________"t_c"-------固定在浏览器窗口的顶部中间位置;
|
|________"c_c"-------固定在浏览器窗口的正中间位置;
*/
f_d=$(div);
//设置默认位置
if(!pos)pos="l_t";
//获得浮动的DIV的高度
d_h=f_d.height();
//获得浮动div的宽度
d_w=f_d.width();
//获得当前窗口的高度
w_h=$(window).height();
//获得当前窗口的宽度
w_w=$(window).width();
//窗口顶部相对文档偏移
t_p=$(window).scrollTop();
switch(pos){
case "l_t":
p_t=t_p;
n_ie_l=n_ie_t=p_l=0;
break;
case "l_c":
p_t=(w_h-d_h)/2+t_p;
n_ie_l=p_l=0;
n_ie_t=(w_h-d_h)/2;
break;
case "l_b":
p_t=w_h-d_h+t_p-2;
n_ie_l=p_l=0;
n_ie_t=w_h-d_h-2;
break;
case "b_c":
p_t=w_h-d_h+t_p-2;
n_ie_l=p_l=(w_w-d_w)/2;
n_ie_t=w_h-d_h-2;
break;
case "r_b":
p_t=w_h-d_h+t_p-2;
n_ie_l=p_l=w_w-d_w-2;
n_ie_t=w_h-d_h-2;
break;
case "r_c":
p_t=(w_h-d_h)/2+t_p;
n_ie_l=p_l=w_w-d_w-2;
n_ie_t=(w_h-d_h)/2;
break;
case "r_t":
p_t=t_p;
n_ie_l=p_l=w_w-d_w-2;
n_ie_t=0;
break;
case "t_c":
p_t=t_p;
n_ie_l=p_l=(w_w-d_w)/2;
n_ie_t=0;
break;
case "c_c":
p_t=(w_h-d_h)/2+t_p;
n_ie_l=p_l=(w_w-d_w)/2;
n_ie_t=(w_h-d_h)/2;
break;
}
if($.browser.msie&&$.browser.version<8){
f_d.css({position:"absolute",top:p_t+"px",left:p_l+"px"});
}else{
f_d.css({position:"fixed",top:n_ie_t+"px",left:n_ie_l+"px"});
}
}
function f_p(d,p){
alert(222);
$.f_position(d,p);
$(window).scroll(function (){
$.f_position(d,p);
})
$(window).resize(function (){
$.f_position(d,p);
})
}<file_sep>/core/modules/modoer/item/model/delivery_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
$_G['loader']->model('item:itembase', FALSE);
class msm_item_delivery extends msm_item_itembase {
var $table = 'dbpre_subject_delivery';
var $key = 'sid';
function __construct() {
parent::__construct();
$this->init_field();
}
function msm_item_delivery() {
$this->__construct();
}
function init_field() {
$this->add_field('sid,c_payment,c_types,c_deliver,c_minprice,c_freight,c_pack,c_book,c_range,c_content,c_finer,c_listorder');
$this->add_field_fun('sid', 'intval');
}
/*
* 2012.12.16
* 关联主表和附表的查询
*
*/
function read($sid) {
$sql='select d.*,s.fullname,s.thumb,s.status,s.best,ss.c_dianhua,ss.c_dizhi,ss.c_yunye,ad.name as catname from ms_subject_delivery d
left join ms_subject s on d.sid=s.sid
left join ms_subject_shops ss on d.sid=ss.sid
left join ms_att_list ad on d.c_types= ad.attid
where s.sid='.$sid;
$delivery = parent::getOne($sql);
return $delivery;
}
function find($select, $where, $start, $offset, $total = TRUE) {
$this->db->join($this->table,'l.sid',$this->subject_table,'s.sid','LEFT JOIN');
$this->db->where($where);
$result = array(0,'');
if($total) {
if(!$result[0] = $this->db->count()) {
return $result;
}
$this->db->sql_roll_back('from,where');
}
$this->db->select($select ? $select : '*');
$this->db->order_by('l.posttime', 'DESC');
$this->db->limit($start, $offset);
$result[1] = $this->db->get();
return $result;
}
// 多表联合查询
function getlist($select, $where, $orderby, $start, $offset, $total = TRUE,$select_subject_shops=FALSE) {
$result = array(0,'');
if($total) {
$result[0] = $this->getcount($where);
}
$table = 'dbpre_subject';
$this->db->join($this->table, 's.sid', $table, 'sf.sid', 'LEFT JOIN');
if($select_subject_shops) {
$this->db->join_together('s.sid', 'dbpre_subject_shops', 'b.sid', 'LEFT JOIN');
}
$this->db->where($where);
$this->db->select($select ? $select : '*');
$this->db->order_by($orderby);
if($offset > 0) $this->db->limit($start, $offset);
$result[1] = $this->db->get();
return $result;
}
// 复杂查询方法
function getlist1($sql) {
$result = array(0,'');
$result[1] = $this->execquery($sql);
return $result;
}
// 复杂查询方法
function getlist2($where,$limit) {
$result = array(0,'');
$orderby = "order by s.sid DESC,s.c_finer DESC";
$sql = "select sj.sid,sj.fullname,sj.thumb,s.c_minprice,
s.c_finer,s.c_stars,
s.c_avgprice,sf.c_dianhua,sf.c_dizhi,sf.c_yunye
from ms_subject_delivery s left join ms_subject sj on s.sid=sj.sid
left join ms_subject_shops sf on s.sid=sf.sid
$where $orderby limit 0,$limit";
$result[1] = $this->execquery($sql);
return $result;
}
function update($post,$sid) {
$sid = parent::save($post, $sid, FALSE);
//$AL = & $_G ['loader']->model ('item:att_list' );
//$AL->save ( $catid, $names );
return $sid;
}
function check_post(& $post, $isedit = FALSE) {
//if(!$post['c_minprice']) {
//redirect('item_log_empty_minprice');
//}
}
function delete($sids) {
if(is_numeric($sids) && $sids > 0) $sids = array($sids);
if(empty($sids) || !is_array($sids)) redirect('global_op_unselect');
$this->db->from($this->table);
$this->db->where_in('sid', $sids);
$this->db->delete();
}
function getcount($where) {
$this->db->from($this->table,'s');
$this->db->where($where);
return $this->db->count();
}
/*
* 按指定要求统计
* 可支持多条件统计
*/
function get_deliverycat_total($conds) {
foreach ($conds as $key=>$value){
$this->db->where($key, $value);
}
$this->db->from($this->table);
return $this->db->count();
}
}
?><file_sep>/core/modules/modoer/mobile.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
$_G ['in_ajax'] = 1;
$op = trim ( $_GET ['op'] );
$allow_ops = array (
'ads',
'list',
'recommend',
'dishes',
'login',
'register',
'add'
);
$login_ops = array ();
$op = empty ( $op ) || ! in_array ( $op, $allow_ops ) ? '' : $op;
if (! $op) {
redirect ( 'global_op_unkown' );
} elseif (in_array ( $op, $login_ops ) && ! $user->isLogin) {
$_G ['forward'] = $_G ['web'] ['referer'] ? $_G ['web'] ['referer'] : $_G ['cfg'] ['siteurl'];
redirect ( 'member_not_login' );
}
$delivery = $_G ['loader']->model ( 'item:delivery' );
$json = & $_G ['loader']->lib ( 'json', NULL, TRUE );
switch ($op) {
// 主界面广告接口
case 'ads' :
$bcastr = $_G ['loader']->model ( 'bcastr' );
$sql = "select bcastr_id,itemtitle,item_url,link from ms_bcastr limit 0,4";
list ( , $list ) = $bcastr->getlist1 ( $sql );
if ($list) {
while ( $val = $list->fetch_array () ) {
$result [] = ads_to_array ( $val );
}
$list->free_result ();
$output = $json->encode ( array (
'msg' => '10001',
'data' => $result
) );
}
echo $output;
output ();
break;
// 主界面推荐商家接口
case 'recommend' :
$where = " where s.c_status = 1";
list ( , $list ) = $delivery->getlist2 ( $where, 4 );
if ($list) {
while ( $val = $list->fetch_array () ) {
$result [] = shops_to_array ( $val );
}
$list->free_result ();
$output = $json->encode ( array (
'msg' => '10001',
'data' => $result
) );
}
echo $output;
output ();
break;
// 商户检索接口
case 'list' :
$where = " where s.c_status=1 ";
$keyword = '川菜';
$keyword = trim ( $_GET ['keyword'] );
$lat = trim ( $_GET ['lat'] );
$lng = trim ( $_GET ['lng'] );
$dist = trim ( $_GET ['dist'] );
$limit = trim ( $_GET ['num'] );
if (! empty ( $keyword )) {
$where = $where . "And sj.fullname LIKE '%$keyword%' ";
}
if (! empty ( $lat ) && ! empty ( $lng )) {
$lat1 = $lat + $dist;
$lng1 = $lng + $dist;
$where = $where . "And sj.map_lng between $lng and $lng1 ";
$where = $where . "And sj.map_lat between $lat and $lat1 ";
}
if (empty ( $limit ))
$limit = 500;
list ( , $list ) = $delivery->getlist2 ( $where, $limit );
if ($list) {
while ( $val = $list->fetch_array () ) {
$result [] = shops_to_array ( $val );
}
$list->free_result ();
$output = $json->encode ( array (
'msg' => '10001',
'data' => $result
) );
}
echo $output;
output ();
break;
// 商家菜单查询接口
case 'dishes' :
$sid = trim ( $_GET ['sid'] );
$sid = 896;
/*
* // 检索餐厅基本信息 $where = " where sj.sid=$sid"; list ( , $list ) =
* $delivery->getlist2 ( $where, 1 ); if ($list) { while ( $val =
* $list->fetch_array () ) { $result [] = shops_to_array ( $val ); } }
*/
// 检索菜单所有分类
$sql = "select catid,name,listorder,num from ms_product_category where sid=$sid order by catid asc";
list ( , $list ) = $delivery->getlist1 ( $sql );
if ($list) {
while ( $val = $list->fetch_array () ) {
$catid = $val ['catid'];
$catname = $val ['name'];
// 检索分类下的菜名
$sql = "select pid,subject,price from ms_product where sid=$sid and catid=$catid";
list ( , $list1 ) = $delivery->getlist1 ( $sql );
if ($list1) {
while ( $val = $list1->fetch_array () ) {
$dishes [] = menu_to_array ( $val );
}
$list1->free_result ();
}
$result [] = array (
'catid' => $catid,
'catname' => $catname,
'dishes' => $dishes
);
$dishes = null;
}
$list->free_result ();
$output = $json->encode ( array (
'msg' => '10001',
'data' => $result
) );
}
echo $output;
output ();
break;
default :
redirect ( 'global_op_unkown' );
}
// 构造商家数组
function shops_to_array(&$val) {
return array (
// 商家编号
'id' => $val ['sid'],
// 商家名称
'name' => $val ['fullname'],
// 商家Logo
'zoom' => $val ['thumb'],
// 是否推荐
'recommend' => $val ['c_finer'],
// 商家星级
'stars' => $val ['c_stars'],
// 商家起送金额
'startprice' => $val ['c_minprice'],
// 商家人均消费
'average' => $val ['c_avgprice'],
// 商家地址
'address' => $val ['c_dizhi'],
// 商家电话
'tel' => $val ['c_dianhua'],
// 商家营业时间
'worktime' => $val ['c_yunye']
);
}
// 构造菜单数组
function menu_to_array(&$val) {
return array (
// 菜谱编号
'id' => $val ['sid'],
// 菜谱名称
'name' => $val ['fullname'],
// 菜谱所属分类
'catid' => $val ['catid'],
// 菜谱所属分类名称
'catname' => $val ['catname'],
// 是否推荐
'recommend' => $val ['c_tuijian'],
// 商家价格
'price' => $val ['price'],
// 计量单位
'unit' => $val ['c_unit'],
// 销售量
'salenum' => $val ['c_salenum']
);
}
// 构造菜单数组
function ads_to_array(&$val) {
return array (
// 广告编号
'id' => $val ['bcastr_id'],
// 广告标题
'title' => $val ['itemtitle'],
// 广告连接
'url' => $val ['item_url'],
// 广告图片
'picture' => $val ['link']
);
}
// 输出为XML文档
function search_to_xml($result) {
if (! $result)
return '';
$content = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
$content .= "<root>\n";
foreach ( $result as $val ) {
$content .= "<subject>\n";
foreach ( $val as $k => $v ) {
$htmlon = preg_match ( "/<[a-z]+\s+.+\\>/i", $v );
$content .= "\t<$k>" . ($htmlon ? '<![CDATA[' : '') . $v . ($htmlon ? ']]>' : '') . "</$k>\n";
}
$content .= "</subject>\n";
}
$content .= "</root>";
return $content;
}
?>
<file_sep>/core/modules/tuan/assistant/coupon.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
$C =& $_G['loader']->model('tuan:coupon');
$op = _input('op');
$status = _get('status', 'available', MF_TEXT);
switch($op) {
case 'detail':
$oid = _get('oid',0,'intval');
$offset = 20;
$start = get_start($_GET['page'], $offset);
list($total, $list) = $C->my_single($user->uid,$oid,$status,$start,$offset);
if($total) $multipage = multi($total, $offset, $_GET['page'], url("tuan/member/ac/coupon/op/detail/oid/$oid/status/$status"));
$O =& $_G['loader']->model('tuan:order');
$order = $O->read($oid);
$tplname = 'm_coupon_detail';
break;
default:
$offset = 10;
$start = get_start($_GET['page'], $offset);
list($total, $list) = $C->my_all($user->uid, $status, $start, $offset);
if($total) $multipage = multi($total, $offset, $_GET['page'], url("tuan/member/ac/coupon/status/$status"));
$tplname = 'm_coupon';
}
$active = array();
if($status) {
$acticve[$status] = ' class="current"';
}
?><file_sep>/core/modules/member/mobile/query.php
<?php
$json = & $_G ['loader']->lib ( 'json', NULL, TRUE );
$zd = $_G ['loader']->model ( 'zidian' );
// 查询条件
$keyword = trim ( $_GET ['q'] );
$vartype = trim ( $_GET ['vartype'] );
$keyword='1';
$vartype='work';
if ($_G ['charset'] != 'utf-8') {
$_G ['loader']->lib ( 'chinese', NULL, FALSE );
$CHS = new ms_chinese ( 'utf-8', $_G ['charset'] );
$keyword = $keyword ? $CHS->Convert ( $keyword ) : '';
}
$list = $zd->getlist ( $vartype, $keyword );
$result = array ();
foreach ( $list as $value ) {
$result [] = array (
'id' => $value [id],
'name' => $value [varname],
'vartype' => $value [vartype]
);
}
$total=count($list);
$output = $json->encode(array('results'=>$result,'total'=>$total));
//$output = $json->encode ( $result );
echo $output;
output ();
?>
<file_sep>/img/shop/other/tab.js
/**
* Tab切换类库
*/
TabClass = function (config)
{
this.tabName = config.tabName; //Tab的名称前缀
this.cntName = config.cntName; //Tab的内容前缀
this.number = config.number; //Tab的个数
this.tabShowCls = config.tabShowCls;//活动的Tab的Class
if (config.tabHiddenCls)
this.tabHiddenCls = config.tabHiddenCls;//非活动的Tab的Class
else
this.tabHiddenCls = '';
if (config.cntShowCss)
this.cntShowCss = config.cntShowCss;//非活动的Tab的内容的样式
else
this.cntShowCss = 'block';
this.show = function(index){
for (var i=0; i<this.number; i++) {
if (i!=index) {
$('#'+this.tabName+'_'+i).removeClass(this.tabShowCls);
if (this.tabHiddenCls)
$('#'+this.tabName+'_'+i).addClass(this.tabHiddenCls);
$('#'+this.cntName+'_'+i).css('display', 'none');
}
else {
if (this.tabHiddenCls)
$('#'+this.tabName+'_'+i).removeClass(this.tabHiddenCls);
$('#'+this.tabName+'_'+i).addClass(this.tabShowCls);
$('#'+this.cntName+'_'+i).css('display', this.cntShowCss);
}
}
}
}
// Special ver for Index Map hot point switch
TabClassMap = function (config)
{
this.tabName = config.tabName; //Tab的名称前缀
this.cntName = config.cntName; //Tab的内容前缀
this.number = config.number; //Tab的个数
this.tabShowCls = config.tabShowCls.split("@");//活动的Tab的Class,多个用@分割
if (config.tabHiddenCls)
this.tabHiddenCls = config.tabHiddenCls
else
this.tabHiddenCls = '';
if (config.cntShowCss)
this.cntShowCss = config.cntShowCss;//非活动的Tab的内容的样式
else
this.cntShowCss = 'block';
this.show = function(index){
for (var i=0; i<this.number; i++) {
if (i!=index) {
$('#'+this.tabName+'_'+i).removeClass(this.tabShowCls[0]);
$('#'+this.tabName+'_'+i).removeClass(this.tabShowCls[1]);
if (this.tabHiddenCls)
$('#'+this.tabName+'_'+i).addClass(this.tabHiddenCls);
$('#'+this.cntName+'_'+i).css('display', 'none');
}
else {
if (this.tabHiddenCls)
$('#'+this.tabName+'_'+i).removeClass(this.tabHiddenCls);
var tab_str = $('#'+this.tabName+'_'+i).text();
var tab_str_len = tab_str.length;
var templen = tab_str_len;
for(var j=0;j<tab_str_len;j++)
{
var rstr=escape(tab_str.substring(j,j+1));
if (rstr.substring(0,2)=="%u")
{
templen++;
}
}
if(templen > 6)
$('#'+this.tabName+'_'+i).addClass(this.tabShowCls[1]);
else
$('#'+this.tabName+'_'+i).addClass(this.tabShowCls[0]);
$('#'+this.cntName+'_'+i).css('display', this.cntShowCss);
}
}
}
}<file_sep>/core/modules/tuan/model/order_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_tuan_order extends ms_model {
var $table = 'dbpre_tuan_order';
var $key = 'oid';
var $model_flag = 'tuan';
function __construct() {
parent::__construct();
$this->model_flag = 'tuan';
$this->init_field();
$this->modcfg = $this->variable('config');
}
function msm_tuan_order() {
$this->__construct();
}
function init_field() {
$this->add_field('oid,tid,mobile,status,good_status,contact,express');
$this->add_field_fun('subject,mobile', '_T');
$this->add_field_fun('oid,tid', 'intval');
}
function find($select="*", $where=null, $orderby=null, $start=0, $offset=10, $total=FALSE) {
$this->db->join($this->table,'o.tid','dbpre_tuan','t.tid');
$where && $this->db->where($where);
$result = array(0,'');
if($total) {
if(!$result[0] = $this->db->count()) {
return $result;
}
$this->db->sql_roll_back('from,where');
}
$this->db->select($select?$select:'*');
if($orderby) $this->db->order_by($orderby);
if($start < 0) {
if(!$result[0]) {
$start = 0;
} else {
$start = (ceil($result[0]/$offset) - abs($start)) * $offset; //按 负数页数 换算读取位置
}
}
$this->db->limit($start, $offset);
$result[1] = $this->db->get();
return $result;
}
//我的订单
function myorders($status = null, $offset = 20) {
$this->db->join($this->table,'o.tid','dbpre_tuan','t.tid');
$this->db->where('o.uid',$this->global['user']->uid);
if($status) $this->db->where('o.status',$status);
$result = array(0,'','');
if($result[0] = $this->db->count()) {
$this->db->sql_roll_back('from,where');
$this->db->select('o.*,t.mode,t.subject,t.thumb,t.city_id');
$this->db->order_by('o.dateline','DESC');
$start = get_start($_GET['page'],$offset);
$this->db->limit($start,$offset);
$result[1] = $this->db->get();
}
return $result;
}
//订单
function save($oid = null) {
$edit = $oid != null;
if($edit) {
if(!$detail = $this->read($oid)) redirect('tuan_order_empty');
$tid = $detail['tid'];
} else {
if(!$tid = (int)_post('id')) redirect(lang('global_sql_keyid_invalid','id'));
}
$num = (int) _post('buynum');
if($num < 1) redirect('tuan_order_num_invalid');
$mobile = _post('mobile','',MF_TEXT);
$contact = _post('contact',null);
$tuan = $this->check_buy($tid, $num);
if($tuan['sendtype'] == 'express') {
$this->modcfg['need_mobile'] = 1;
$contact['linkman'] = _T($contact['linkman']);
$contact['address'] = _T($contact['address']);
$contact['postcode'] = _T($contact['postcode']);
if(!$contact['linkman']) redirect('tuan_order_linkman_empty');
if(!$contact['address']) redirect('tuan_order_address_empty');
}
$contact['des'] = _T($contact['des']);
if($this->modcfg['need_mobile'] && !$mobile) redirect('tuan_order_mobile_empty');
$mobile_preg = $this->modcfg['mobile_preg'] ? $this->modcfg['mobile_preg'] : "/^[0-9]{11}$/";
if($mobile && !preg_match($mobile_preg, $mobile)) redirect('tuan_order_mobile_format_invalid');
if($tuan['use_ex_point'] && $tuan['use_ex_price']>0) {
$ex_point = _post('ex_point',null,MF_INT);
$ex_pointtype = $this->modcfg['ex_pointtype'];
$mypoint = $this->global['user']->$ex_pointtype;
$pointname = display('member:point',"point/$ex_pointtype");
if($mypoint < $ex_point) redirect(lang('tuan_order_point_not_enough', $pointname));
$maxpoint = $tuan['use_ex_price'] * $this->modcfg['ex_rate'];
if($maxpoint < $ex_point) redirect(lang('tuan_order_point_max_exchange',array($maxpoint,$maxpoint)));
$ex_price = round($ex_point / $this->modcfg['ex_rate'],2);
}
//判断用户是否已经购买
if(!$edit && $this->check_bought($this->global['user']->uid, $tid)) redirect('tuan_buy_bought');
$post = array();
$post['num'] = $num;
$post['price'] = $num * $tuan['price'];
$post['pay_price'] = $post['price'];
$post['mobile'] = $mobile;
$post['contact'] = $contact ? serialize($contact) : '';
if(isset($ex_price) && $ex_price > 0) {
$post['ex_price'] = $ex_price;
$post['ex_point'] = $ex_point;
$post['ex_pointtype'] = $ex_pointtype;
$post['price'] = $post['price'] - $ex_price;
$post['pay_price'] = $post['pay_price'] - $ex_price;
}
if(!$edit) {
$post['tid'] = $tid;
$post['uid'] = $this->global['user']->uid;
$post['username'] = $this->global['user']->username;
$post['status'] = 'new';
$post['dateline'] = $this->global['timestamp'];
$post['endtime'] = $tuan['endtime'];
}
$oid = parent::save($post, $oid);
return $oid;
}
//订单物流更新
function update_good_status($oid, $post) {
if(!$detail = $this->read($oid)) redirect('tuan_order_empty');
$express = $post['express'] ? serialize($post['express']) : '';
$this->db->from($this->table);
$this->db->set('good_status',$post['good_status']);
$this->db->set('express',$express);
$this->db->where('oid',$oid);
$this->db->update();
}
//更新订单状态 //过期订单
function plan_overdue($uid = null) {
$endtime = strtotime(date('Y-m-d', $this->global['timestamp']))-1;
//团购结束的算过期
$this->db->from($this->table);
if($uid > 0) $this->db->where('uid', $uid);
$this->db->where('status','new');
$this->db->where_less('endtime', $endtime);
$this->db->set('status', 'overdue');
$this->db->update();
}
//计划检测更新过期订单
function update_overdue($tid, $endtime) {
$this->db->from($this->table);
$this->db->where('tid', $tid);
$this->db->where('status','new');
$this->db->set('endtime', $endtime);
$this->db->update();
}
//对已支付的订单进行退款
function refund($oid, $ratio = 1) {
if(!$order = $this->read($oid)) redirect('tuan_order_empty');
if($order['status'] != 'payed') redirecy('tuan_order_refund_des_payed');
$M =& $this->loader->model(':member');
if(!$member = $M->read($order['uid'])) redirect('member_empty');
//更新订单
$this->db->from($this->table);
$this->db->where('oid', $oid);
$this->db->set('status','refunded');
$this->db->update();
//给会员返回现金
//price 支付的价格 - return_balance_price 已经退了多少 = 需要退多少
$price = $order['price'] - $order['return_balance_price'];
if(is_numeric($price)) $this->_refundrmb($oid, $order['uid'], $price);
if($order['ex_point'] && $this->modcfg['refund_point']) $this->_refundpoint($order['oid'], $order['uid'], $order['ex_point'], $order['ex_pointtype']);
//更新团购表
$T =& $this->loader->model(':tuan');
$T->refund($order['tid'], 1, $order['num']);
}
//对整合团购项目所有购买用户退款
function refund_tuan($tid) {
$this->db->from($this->table);
$this->db->where('tid', $tid);
$this->db->where('status','payed');
if(!$q = $this->db->get()) return;
$oids = array();
while($v=$q->fetch_array()) {
//不符合要求
if(!$v['uid']||!$v['price']) continue;
$oids[] = $v['oid'];
//返回给会员现金
$price = $v['price'] - $v['return_balance_price'];
if(is_numeric($price)) $this->_refundrmb($v['oid'], $v['uid'], $price);
if($v['ex_point'] && $this->modcfg['refund_point']) $this->_refundpoint($v['oid'], $v['uid'], $v['ex_point'], $v['ex_pointtype']);
}
if($oids) {
//更新订单状态
$this->db->from($this->table);
$this->db->set('status','refunded');
$this->db->where('oid', $oids);
$this->db->update();
}
//还原团购表
$T =& $this->loader->model(':tuan');
$T->restore($tid);
}
//线下付款(不扣除积分,直接设为已支付)
function localpay($oid) {
if(!defined('IN_ADMIN')) return;
if(!$detail = $this->read($oid)) redirect('tuan_order_empty');
if($detail['status'] != 'new') redirect('tuan_order_' . $detail['status']);
$tuan = $this->check_buy($detail['tid']);
$this->db->from($this->table);
$this->db->set('exchangetime', $this->global['timestamp']);
$this->db->set('status', 'payed');
$this->db->where('oid', $oid);
$this->db->update();
//更新产品购买情况
$T =& $this->loader->model(':tuan');
$T->update_total($detail['tid'], 1, $detail['num']);
//发放团购券
if($T->check_succeed($detail['tid']) && $tuan['sendtype'] == 'coupon') {
$C =& $this->loader->model('tuan:coupon');
$C->create($tuan['tid']);
}
}
//取消一个订单支付
function cancel($oids) {
$ids = parent::get_keyids($oids);
$this->db->from($this->table);
$this->db->where_in('oid', $ids);
$this->db->set('status','canceled');
$this->db->update();
}
//当前会员购买数量
function member_buy_total($uid,$tid) {
}
//判断是否买过了
function check_bought($uid, $tid, $oid = null) {
$this->db->from($this->table);
$this->db->where('uid',$uid);
$this->db->where('tid',$tid);
$this->db->where_in('status', array('new','payed'));
if($oid > 0) $this->db->where_not_equal('oid',$oid);
return $this->db->count();
}
//检测是否可以进行购买
function check_buy($tid, $buynum = null, $show_error = TRUE) {
$start = strtotime(date('Y-m-d', $this->global['timestamp']));
$endtime = strtotime(date('Y-m-d', $this->global['timestamp']));
$T =& $this->loader->model(':tuan');
if(!$detail = $T->read($tid)) {
if($show_error) redirect('tuan_empty');
if(!$show_error) return FALSE;
}
//判断状态
if($detail['status'] != 'new') {
if($show_error) redirect('tuan_buy_status_invalid');
if(!$show_error) return FALSE;
}
//判断时间
if($detail['starttime'] > $start) {
if($show_error) redirect('tuan_buy_starttime_less');
if(!$show_error) return FALSE;
}
if($detail['endtime'] < $endtime) {
if($show_error) redirect('tuan_buy_endtime_more');
if(!$show_error) return FALSE;
}
//判断是否卖光了
if($detail['goods_sell'] >= $detail['goods_total']) {
if($show_error) redirect('tuan_buy_sellout');
if(!$show_error) return FALSE;
}
//if($detail['mode'] == 'wholesale')
//是否卖光了
//if(!$detail['goods_stock']) redirect('tuan_buy_sellout');
if($buynum > 0) {
$stock = $detail['goods_total'] - $detail['goods_sell']; //剩余
$limit = min($stock, $detail['people_buylimit']);
if($buynum > $limit) {
redirect(lang('tuan_buy_limitmun', $limit));
if(!$show_error) return FALSE;
}
}
return $detail;
}
//生成在线支付接口记录,进入支付页面
function pay_online($oid,$payment) {
if(!$detail = $this->read($oid)) redirect('tuan_order_empty');
if($detail['status'] != 'new') redirect('tuan_order_' . $detail['status'], url('tuan/member/ac/order'));
//判断单子是不是自己的
if($detail['uid'] != $this->global['user']->uid) redirect('tuan_order_dnot_myself', url('tuan/member/ac/order'));
$tuan = $this->check_buy($detail['tid']);
$P =& $this->loader->model(':pay');
$post = array(
//订单标识,用于区别moder内部各个模块的orderid
'order_flag' => 'tuan_order',
//订单号
'orderid' => $oid,
//订单的标题
'order_name' => trimmed_title($tuan['subject'],30,'...'),
//支付用户uid
'uid' => $this->global['user']->uid,
//接口标识
'payment_name' => $payment,
//价格单位元
'price' => $detail['price'],
//分润功能(仅支持支付宝)例如:<EMAIL>^0.01^分润备注一|<EMAIL>^0.01^分润备注二
'royalty' => '',
//此连接用于在支付成功后让关联订单代码执行订单支付后的逻辑(PHP函数get方式服务器端后台执行)
'notify_url' => url("tuan/pay_notify/oid/$oid",'',true,true),
//此连接用户支付完毕后跳转返回的连接地址(客户端浏览器打开)
'callback_url' => url("tuan/member/ac/pay/ac/order", '', true, true),
);
//生成支付接口记录,并跳转到支付页面
$P->create_pay($post);
}
//支付模块通知在线支付成功,进入下单提交流程
function pay_online_succeed($oid) {
$P = $this->loader->model(':pay');
//获取支付接口记录
$pay = $P->read_ex('tuan_order', $oid);
//判断支付接口记录是否存在和状态
if(!$pay) redirect("支付记录不存在。(OID:$oid)");
if(!$pay['pay_status']) redirect("等待支付状态,如果您已经完成支付,请稍后再查看。(OID:$oid)");
if($pay['my_status']) return; //已经处理过了
//先把钱充值到会员现金账户,避免下面提交时出现问题,现金丢失
$this->_pay_online_recharge($pay['uid'], $pay['price']);
//更新记录表自定义状态,避免重复充值
$P->update_mystatus($pay['payid'], 1);
//开始下单,扣现金
$succeed = $this->pay($oid, FALSE);
return $succeed;
}
//检测并支付
function pay($oid, $check_self=TRUE) {
if(!$detail = $this->read($oid)) redirect('tuan_order_empty');
if($detail['status'] != 'new') redirect('tuan_order_' . $detail['status'], url('tuan/member/ac/order'));
//判断单子是不是自己的
if($check_self) {
if($detail['uid'] != $this->global['user']->uid) {
redirect('tuan_order_dnot_myself', url('tuan/member/ac/order'));
}
}
$tuan = $this->check_buy($detail['tid']);
//扣除账户金额
if($detail['price']) {
$this->_payrmb($oid, $detail['uid'], $detail['price']);
}
//扣积分
if($detail['ex_point']) {
$this->_paypoint($oid, $detail['uid'], $detail['ex_point'], $detail['ex_pointtype']);
}
$this->db->from($this->table);
$this->db->set('exchangetime', $this->global['timestamp']);
$this->db->set('status', 'payed');
$this->db->where('oid', $oid);
$this->db->update();
//更新产品购买情况
$T =& $this->loader->model(':tuan');
$T->update_total($detail['tid'], 1, $detail['num']);
//发放团购券
if($T->check_succeed($tuan['tid']) && $tuan['sendtype'] == 'coupon') {
$C =& $this->loader->model('tuan:coupon');
$C->create($tuan['tid'], $oid);
}
return TRUE;
}
//支付
function _payrmb($oid, $uid, $price) {
//判断会员余额
$member = $this->loader->model(':member')->read($uid);
if($price > $member['rmb']) {
redirect('tuan_order_rmb_wantage');
}
$PT =& $this->loader->model('member:point');
$PT->update_point2($uid,'rmb',-$price,lang('tuan_update_point_payrmb_des', $oid));
/*
$this->db->from('dbpre_members');
$this->db->set_dec('rmb', $price);
$this->db->where('uid', $uid);
$this->db->update();
*/
}
//在线支付成功后,先把钱充值进会员账号,避免订单提交失败后,钱丢失
function _pay_online_recharge($uid, $price) {
if(!$uid) return;
//增加充值记录
$PT =& $this->loader->model('member:point');
$PT->update_point2($uid,'rmb',$price,lang('member_point_pay_des'));
}
//更新订单团购券发送
function update_sent($oid) {
if(!$oid) return;
$this->db->from($this->table);
$this->db->where('oid',$oid);
$this->db->set('is_sent', 1);
return $this->db->update();
}
//取得未发放团购券的订单
function get_sent_list($tid) {
$this->db->from($this->table);
$this->db->where('tid', $tid);
$this->db->where('status','payed');
$this->db->where('is_sent', 0);
return $this->db->get();
}
//更新最终支付价格,并计算出差价
function update_real_price($tid) {
// 取团购信息
$T =& $this->loader->model(':tuan');
if(!$tuan = $T->read($tid)) redirect('tuan_empty');
if($tuan['mode']== 'forestall') {
$prices = $T->forestall_parse_prices($tuan['prices']);
} else {
$real_price = $tuan['real_price'];
}
// 更新
$this->db->from($this->table);
$this->db->where('tid', $tid);
$this->db->order_by('exchangetime', 'ASC'); //名次排序,根据订单支付时间
$q = $this->db->get();
if(empty($q)) return;
$ranking = 1; //排名
while($v = $q->fetch_array()) {
if($tuan['mode']== 'forestall') {
$real_price = $this->get_forestall_price($tuan['price'], $prices, $ranking);
}
$total_real_price = $real_price * $v['num'];
$balance_price = $v['price'] - $total_real_price;
$this->db->from($this->table);
$this->db->set('pay_price', $total_real_price);
$this->db->set('balance_price', $balance_price);
$this->db->where('oid',$v['oid']);
$this->db->update();
$ranking++; //排名累计
}
}
//根据下单名次获得价格
function get_forestall_price($price, $prices, $ranking) {
$real_price = $price;
foreach($prices as $num => $price_x) {
if($ranking <=$num) {
$real_price = $price_x;
break;
}
}
return $real_price;
}
//退还差价
function return_balance($tid) {
$this->db->from($this->table);
$this->db->where('tid',$tid);
$this->db->where('status','payed');
$q = $this->db->get();
if(empty($q)) return;
while($v=$q->fetch_array()) {
if(empty($v['balance_price'])) continue;
if($v['balance_price']<=$v['return_balance_price']) continue;
$balance = $v['balance_price'] - $v['return_balance_price'];
if(empty($balance)) continue;
//退差价
$this->_refundrmb($v['oid'], $v['uid'], $balance);
//更新订单
$this->db->from($this->table);
$this->db->where('oid',$v['oid']);
$this->db->set('return_balance_price', $v['balance_price']);
$this->db->set('return_balance_time', $this->global['timestamp']);
$this->db->update();
}
}
//某个团购的订单状态统计
function status_total($tid) {
$this->db->from($this->table);
$this->db->where('tid',$tid);
$this->db->group_by('status');
$this->db->select('status');
$this->db->select('tid', 'count', 'COUNT(?)');
$this->db->select('price', 'price', 'SUM(?)');
$this->db->select('balance_price', 'balance_price', 'SUM(?)');
$this->db->select('return_balance_price', 'return_balance_price', 'SUM(?)');
$this->db->select('num', 'num', 'SUM(?)');
if(!$q = $this->db->get()) return array();
$result = array();
$result['total'] = 0;
while($v=$q->fetch_array()) {
$result['total'] += $v['count'];
foreach($v as $_k=>$_v) {
$result[$v['status']][$_k] = $_v;
}
}
$q->free_result();
return $result;
}
//获得用户在本次团购中下单位数(名次)
function get_ranking($tid, $oid) {
$this->db->from($this->table);
$this->db->where('tid',$tid);
$this->db->where_less('oid', $oid);
return $this->db->count();
}
//删除订单
function delete($oids) {
$ids = parent::get_keyids($oids);
$where = array('oid' => $ids);
$this->_delete($where);
}
//删除某个团购的所有订单
function delete_tids($tids) {
$ids = parent::get_keyids($tids);
$where = array('tid'=>$ids);
$this->_delete($where);
}
//统一删除
function _delete($where) {
if(!$where) return;
//获取订单号
$this->db->where($where);
$this->db->from($this->table);
if(!$q = $this->db->get()) return;
$oids = array();
while($v=$q->fetch_array()) {
$oids[] = $v['oid'];
}
$q->free_result();
//删除已发放的优惠券
$COUPON =& $this->loader->model('tuan:coupon');
$COUPON->delete_order($oids);
//删除订单
$this->db->where('oid',$oids);
$this->db->from($this->table);
$this->db->delete();
}
//支付积分
function _paypoint($oid, $uid, $point, $pointtype) {
if($price > $this->global['user']->$pointtype) {
redirect(lang('tuan_order_point_wantage', display('member:point',"point/$pointtype")));
}
$PT =& $this->loader->model('member:point');
$PT->update_point2($uid,$pointtype,-$point,lang('tuan_update_point_payrmb_des', $oid));
}
//返还积分
function _refundrmb($oid, $uid, $price) {
$PT =& $this->loader->model('member:point'); //update_point2
$PT->update_point2($uid,'rmb',$price,lang('tuan_update_point_refundrmb_des', $oid));
/*
$this->db->from('dbpre_members');
$this->db->set_add('rmb', $price);
$this->db->where('uid', $uid);
$this->db->update();
*/
}
//返还积分
function _refundpoint($oid, $uid, $point, $pointtype) {
$PT =& $this->loader->model('member:point'); //update_point2
$PT->update_point2($uid,$pointtype,$point,lang('tuan_update_point_refundrmb_des', $oid));
}
}
?><file_sep>/templates/mobile1/js/test_global.js
$(function() {
$('#sel-area').click(function() {
$('#list-cat').hide();
$('#list-top').hide();
$('#list-area').slideToggle();
})
$('#sel-cat').click(function() {
$('#list-area').hide();
$('#list-top').hide();
$('#list-cat').slideToggle();
})
$('#sel-top').click(function() {
$('#list-cat').hide();
$('#list-area').hide();
$('#list-top').slideToggle();
})
var appkey = "908026411";
var secret = "c2baf9fa0c904a6797a8406fbe13ef2d";
var param = {};
param["city"]="无锡";
param["category"]="美食";
param["region"]="新区";
param["limit"]="20";
param["offset_type"]="2";
param["has_coupon"]="1";
param["has_deal"]="1";
param["keyword"]="宝龙广场";
param["sort"]="7";
var ajax_loading = true;
if (window.navigator.geolocation) {
var options = {
enableHighAccuracy: true,
};
//document.getElementById('currentPosLng').innerHTML = 'GPSing';
window.navigator.geolocation.getCurrentPosition(successHandle,errorHandle,options);
} else {
alert("浏览器不支持html5来获取地理位置信息");
}
var totalheight = 0;
append_distance();
$(window).scroll( function() {
//append_distance();
loadData(0);
});
function successHandle(position){
var lng = position.coords.longitude;
var lat = position.coords.latitude;
$.cookie('lat',lat);
$.cookie('lng',lng);
append_distance();
loadData(1);//获取到当前坐标后加载第一组数据
}
function errorHandle(error){
loadData(0);
}
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
function append_distance() {
//alert(1111);
if ($.cookie('lat') && $.cookie('lng') && !$(this).find('.distance').text()) {
var local_lat = parseFloat($.cookie('lat'));
var local_lng = parseFloat($.cookie('lng'));
$('.des-dist').each(function(){
var item_lat = parseFloat($(this).find('.dist-lng').text());
var item_lng = parseFloat($(this).find('.dist-lat').text());
var dist = get_dist(item_lat,item_lng,local_lat,local_lng);
$(this).find('.distance').text(dist);
});
}
}
function get_dist(item_lat,item_lng,local_lat,local_lng) {
var rad_item_lat = Math.PI/180*item_lat;
var rad_local_lat = Math.PI/180*local_lat;
var rad_item_lng = Math.PI/180*item_lng;
var rad_local_lng = Math.PI/180*local_lng;
var a=rad_item_lat - rad_local_lat;//两纬度之差,纬度<90
var b=rad_item_lng - rad_local_lng;//两经度之差纬度<180
var dist = 2*Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2)+Math.cos(rad_item_lat)*Math.cos(rad_local_lat)*Math.pow(Math.sin(b/2),2)))*6378.137;
dist = Math.round(dist*1000);
if (dist>=1000) {
dist = dist/1000;
dist = Math.round(dist,2)+'Km';
}
else {
dist +='m';
}
return dist;
}
function common_ajax_next_page(boxid,pageid,isFirst) {
if(!ajax_loading) return;
ajax_loading = false;
var nexturl;
if (isFirst) {
// 对参数名进行字典排序
var array = new Array();
for(var key in param)
{
array.push(key);
}
array.sort();
// 拼接有序的参数名-值串
var paramArray = new Array();
paramArray.push(appkey);
for(var index in array)
{
var key = array[index];
paramArray.push(key + param[key]);
}
paramArray.push(secret);
// 字符串连接示例
// XXXXXXXXcategory美食city上海formatjsonhas_coupon1has_deal1keyword泰国菜latitude31.21524limit20longitude121.420033offset_type0radius2000region长宁区sort7XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// SHA-1编码,并转换成大写,即可获得签名
var shaSource = paramArray.join("");
var sign = new String(toSHA1(shaSource)).toUpperCase();
nexturl = 'http://api.dianping.com/v1/business/find_businesses'+'?city='+param["city"]+'&category='
+param["category"]+'®ion='+param["region"]+'&limit='+param["limit"]+'&offset_type='
+param["offset_type"]+'&has_coupon='+param["has_coupon"]+'&has_deal='+param["has_deal"]
+'&keyword='+param["keyword"]+'&sort='+param["sort"]+'&appkey='+appkey+'&sign='+sign;
alert(nexturl);
} else {
var array = new Array();
for(var key in param)
{
array.push(key);
}
array.sort();
// 拼接有序的参数名-值串
var paramArray = new Array();
paramArray.push(appkey);
for(var index in array)
{
var key = array[index];
paramArray.push(key + param[key]);
}
paramArray.push(secret);
// 字符串连接示例
// XXXXXXXXcategory美食city上海formatjsonhas_coupon1has_deal1keyword泰国菜latitude31.21524limit20longitude121.420033offset_type0radius2000region长宁区sort7XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// SHA-1编码,并转换成大写,即可获得签名
var shaSource = paramArray.join("");
var sign = new String(str_sha1(shaSource)).toUpperCase();
nexturl = 'http://api.dianping.com/v1/business/find_businesses'+'?city='+param["city"]+'&category='
+param["category"]+'®ion='+param["region"]+'&limit='+param["limit"]+'&offset_type='
+param["offset_type"]+'&has_coupon='+param["has_coupon"]+'&has_deal='+param["has_deal"]
+'&keyword='+param["keyword"]+'&sort='+param["sort"]+'&appkey='+appkey+'&sign='+sign;
nexturl="http://192.168.3.11/v1/business/find_businesses_by_region?appkey=908026411&sign=2BD5DF0D671E07A0768FC00E9AF681B3140722A8&category=%E6%B5%B7%E9%B2%9C&city=%E4%B8%8A%E6%B5%B7®ion=%E9%95%BF%E5%AE%81%E5%8C%BA&has_coupon=1&limit=20&format=json&platform=2";
}
$('#multipage').remove();
if(!nexturl) {
$('#'+pageid).hide();
return;
}
$('#'+pageid).show();
$.get(nexturl,
function(result) {
if(result == null) {
$('#'+pageid).show();
} else if(result != '') {
$('#'+boxid).append(result);
append_distance();
if($('#multipage').find('[nextpage="Y"]')[0]) {
ajax_loading = true;
} else {
$('#'+pageid).hide();
}
}
},json);
}
function loadData(isFirst){
totalheight = parseFloat($(window).height()) + parseFloat($(window).scrollTop());
if ($(document).height() <= totalheight) { // 说明滚动条已达底部
/*这里使用Ajax加载更多内容*/
common_ajax_next_page('list-box','loading',isFirst);
}
}
})<file_sep>/core/modules/modoer/item/mobile/list.php
<?php
$catid = isset ( $_GET ['catid'] ) ? ( int ) $_GET ['catid'] : ( int ) $MOD ['pid'];
! $catid and location ( url ( 'item/mobile/do/category' ) );
//获取用户当前经纬度
$lat = isset ( $_POST ['lat']) ? ( float ) $_POST ['lat'] : 0;
$lng = isset ( $_POST ['lng'] ) ? ( float ) $_POST ['lng'] : 0;
echo $lat;
echo $lng;
$op = _input('op');
// 实例化主题类
$S = & $_G ['loader']->model ( 'item:subject' );
$S->get_category ( $catid );
if (! $pid = $S->category ['catid']) {
location ( url ( 'item/mobile/do/category' ) );
}
//查询条件
$where = array ();
$where['city_id'] = array(8);
$where['finer'] = array(2);
//$where['status'] = array('where_not_equal',array('0'));
//区域信息
$sonaid='';
$aid = ( int ) $_GET ['aid'];
if($aid==0){
$sel_aid='全部商区';
}else{
//统一使用区域的子区域查询
$areas = $_G ['loader']->variable ( 'area_8', null, false );
$paid=$areas[$aid]['pid'];
$sel_aid=$areas[$aid]['name'];
//顶级区划
if($paid==8){
foreach($areas as $area){
if($area[pid]==$aid){
$sonaid=$sonaid.$area[aid].',';
}
}
}else{
$sonaid=$aid;
}
$where['aid'] = explode(',',$sonaid);
}
//统一使用子分类信息查询
$soncatid='';
if($catid==0){
$sel_catid='美食';
}else{
//顶级分类
$topcats=array(1,19,22,23,24);
if(in_array($catid, $topcats)){
$cats = $_G ['loader']->variable ( 'category','item');
$soncatid=$cats[$catid]['subcats'];
$sel_catid=$cats[$catid]['name'];
}else{
$soncatid=$catid;
$temp = & $_G ['loader']->model ( 'item:category' );
$aa=$temp->read($catid);
$sel_catid=$aa['name'];
}
$where['catid'] = explode(',',$soncatid);
}
//排序条件
$orderby = isset ( $_GET ['px'] ) ? $_GET ['px'] : 'finer';
$order_arr = array (
'finer' => array ('s.finer' => 'DESC','distance' => 'ASC'),
'listorder' => array ('s.c_listorder' => 'ASC','distance' => 'ASC'),
'addtime' => array ('addtime' => 'DESC','distance' => 'ASC'),
'pageviews' => array ('pageviews' => 'DESC','distance' => 'ASC')
);
//获取排序名称
if($orderby=='finer'){
$ordername='默认排序';
}elseif($orderby=='listorder'){
$ordername='按评分从高到底';
}elseif($orderby=='pageviews'){
$ordername='按评分从低到高';
}else{
$ordername='默认排序';
}
//查询数据
//$lat=120.358537;
//$lng=31.546392;
$num = 10;
$offset = $num;
$start = get_start($_GET['page'], $num);
$select="sf.sid,s.pid,s.catid,s.aid,s.name,s.subname,s.best,s.finer,s.map_lng,s.map_lat,s.fullname,s.status,s.pageviews,s.avgsort,s.avgprice,s.coupons,s.credits,s.tuans,round((6371*acos(cos(radians($lat))*cos(radians( map_lat))*cos(radians(map_lng)-radians($lng))+sin(radians($lat))*sin(radians(map_lat)))),3) AS distance";
list ( $total, $list ) = $S->getlist ( $pid, $select, $where, $order_arr [$orderby], $start, $num, true );
if($total) {
$multipage = mobile_page($total, $num, $_GET['page'], url("item/mobile/do/list/catid/$catid/aid/$aid/order/$order/type/$type/num/$num/total/$total/page/_PAGE_"));
}
//显示模版
if($_G['in_ajax'] && _input('waterfall')=='Y') {
$tplname = 'item_list_li_ajax';
//echo $lat;
//echo $lng;
} else {
$tplname = 'item_list';
}
include mobile_template($tplname);
// 解析Tags
function get_mytag($val) {
global $S;
return $S->get_mytag ( $val );
}
// 解析Att
function get_myatt($val) {
global $S;
return $S->get_myatt ( $val );
}
// 解析坐标
function get_mydist($lat2,$lng2) {
global $lat,$lng;
//echo $lat.' ';
//echo $lng;
if ($lat == 0) {
return 0;
}
else {
return get_distance($lng,$lat,$lng2,$lat2);
}
}
/*
* SELECT sid, fullname,round(( 6371 * acos( cos( radians(120.358537) ) * cos( radians( map_lat ) ) * cos( radians( map_lng ) - radians(31.546392) ) + sin( radians(120.358537) ) * sin( radians( map_lat ) ) ) ),3) AS distance FROM ms_subject HAVING distance < 2 ORDER BY distance LIMIT 0 , 500;
*
*/
?>
<file_sep>/core/modules/fenlei/model/field_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
$_G['loader']->model('field', FALSE);
class msm_fenlei_field extends msm_field {
function __construct() {
$this->fielddir = MOD_ROOT . 'model' . DS . 'fields';
parent::__construct();
$this->model_flag = 'fenlei';
}
function msm_fenlei_field() {
$this->__construct();
}
function & field_list($pid, $p_cfg = FALSE) {
return parent::field_list('fenlei', $pid, $p_cfg);
}
function validator($catid, &$data) {
if(!$category = $this->variable('category')) return false;
if(!$pid = $category[$catid]['pid']) return false;
$fieldids = $category[$catid]['fieldids'] ? explode(',', $category[$catid]['fieldids']) : '';
if(!$fieldids) return false;
$myfieldids = array();
if(!$fields = $this->variable('field_' . $pid)) return false;
foreach($fieldids as $id) {
$myfieldids[$id] = $fields[$id];
}
$FV =& $this->loader->model($this->class_fieldvalidator);
$result = array();
foreach($myfieldids as $val) {
$value = $FV->validator($val, $data[$val['fieldname']]);
if(!$FV->leave) $result[$val['fieldname']] = $value;
}
return $result;
}
function delete($fieldid) {
if(!$detail = $this->read($fieldid)) return;
if($pid = $detail['id']) {
$C =& $this->loader->model('fenlei:category');
if($list = $C->read_all($pid)) {
foreach($list as $val) {
if(!$val['fieldids']) continue;
if(!$fids = explode(',', $val['fieldids'])) continue;
$index = array_search($fieldid, $fids);
if($index === false) continue;
unset($fids[$index]);
$C->select($val['catid'], $fids);
}
}
}
parent::delete($fieldid);
}
function write_cache($pid = null) {
if($modelid > 0) {
$this->_write_cache('fenlei', $pid);
return;
}
$this->db->from('dbpre_fenlei_category');
$this->db->where('pid', 0);
if(!$row = $this->db->get()) return;
while($value = $row->fetch_array()) {
$this->_write_cache('fenlei', $value['catid'], $this->model_flag);
}
}
}
?><file_sep>/core/modules/tuan/admin/menus.inc.php
<?php
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$modmenus = array(
array(
'title' => '团购导航',
'tuan|团购网站|tgsite|list',
'tuan|导航数据|tuandh|list',
),
array(
'title' => '团购管理',
'tuan|模块配置|config',
'tuan|分类管理|category',
'tuan|团购管理|tuan',
'tuan|团购券|coupon',
'tuan|自助团购|wish',
'tuan|用户答疑|discuss',
'tuan|邮件订阅|subscibe',
),
);
?><file_sep>/templates/item/vip/coupon_detail.php
<?exit?>
<!--{eval
$_HEAD['title'] = (isset($catid)?$category[$catid][name]:'') . $MOD[name] . $_CFG['titlesplit'] . $detail[subject] . $subject[name] . $subject[subname] . $MOD[subtitle];
}-->
<!--{template 'header', 'item', $subject[templateid]}-->
<link href="{URLROOT}/img/vipfiles/css/shopEx_$subject[c_vipstyle].css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function coupon_effect(couponid) {
$.post(Url('coupon/detail/do/effect/id/'+couponid),
{ effect:'effect1',in_ajax:1 },
function(result) {
if(result == null) {
alert('信息读取失败,可能网络忙碌,请稍后尝试。');
} else if (result.match(/\{\s+caption:".*",message:".*".*\s*\}/)) {
myAlert(result);
} else if (result == 'OK') {
$('#btn_effect1').html('对我有用!');
}
});
}
</script>
<body>
<div class="wrap">
<div id="header">
<div id="crumb">
<p id="crumbL"><a href="{url modoer/index}">{lang global_index}</a> » {print implode(' » ', $urlpath)} » $subject[name] $subject[subname]
<p id="crumbR"><a href="javascript:post_log($subjectl[sid]);">补充信息</a> | <a href="{url item/member/ac/subject_add/subbranch_sid/$subject[sid]}">增加分店</a> | <a href="{url member/index}">管理本店</a></p>
</div>
<div id="shopBanner">
<h1>$subject[name] $subject[subname]</h1>
<p>
<!--{if $subject[c_add]}-->
<B>地址:</B></LABEL>$subject[c_add]
<!--{/if}-->
<!--{if $subject[c_tel]}-->
<B>电话:</B></LABEL>$subject[c_tel]</p>
<!--{/if}-->
<div class="headerPic">
<img src="{if $subject[c_vipbanner]}$subject[c_vipbanner]{else}{URLROOT}img/haibao/nonbanner.png{/if}" alt="$subject[name] $subject[subname]店铺海报" width="950" height="150"/>
</div>
</div>
<div id="nav">
<ul>
<!--
<li><a href="#"><span>Array</span></a></li>
<li><a href="#"><span></span></a></li>
<li class="special"><a href="#"><span>导航栏介绍</span></a></li>
-->
<li><a href="{url item/detail/id/$subject[sid]}"><span>首页</span></a></li>
<li><a href="{url article/list/sid/$subject[sid]}"><span>店铺资讯</span></a></li>
<li><a href="{url fenlei/list/sid/$subject[sid]}"><span>诚聘英才</span></a> </li>
<li><a href="{url product/list/sid/$subject[sid]}"><span>产品展厅</span></a></li>
<li class="current" ><a href="{url coupon/list/sid/$subject[sid]}"><span>优惠打折</span></a></li>
<li><a href="{url item/pic/sid/$subject[sid]}"><span>商家相册</span></a></li>
<li><a href="{url item/vipabout/id/$subject[sid]}"><span>关于我们</span></a></li>
<li><a href="{url item/vipreview/id/$subject[sid]}"><span>会员点评</span></a></li>
<li><a href="{url item/vipguestbook/id/$subject[sid]}"><span>留言板</span></a></li>
</ul>
</div>
</div>
<div id="smartAd"><img src="{if $subject[c_vipbanner2]}$subject[c_vipbanner2]{else}{URLROOT}img/haibao/non.png{/if}" alt="$subject[name] $subject[subname]店铺海报"/></a><br />
</div>
<div id="mainBody">
<div id="mainBodyL">
<div id="infoList" class="deafBox">
<div class="deafBoxTit">
<h2>【$subject[name] $subject[subname]】</h2>
<p class="deafBoxTitMore"><a href="{url item/vipabout/id/$subject[sid]}">更多</a></p>
</div>
<div class="deafBoxCon">
<dl>
<table cellpadding="0" cellspacing="0" border="0" width=100% >
<tr>
<td align="center" valign="middle">
<a href="{url item/pic/sid/$subject[sid]}"><img src="{URLROOT}/{if $subject[thumb]}$subject[thumb]{else}static/images/noimg.gif{/if}" alt="$subject[name]" width="270" height="200" /></a>
</td>
</tr>
</table>
<div class="leftnr">
<!--{if $subject[finer]}-->
店铺级别:<img src="{URLROOT}/img/vipfiles/img/vip$subject[finer].gif" align="absmiddle"/><br />
<!--{/if}-->
<div class="subject">
<h2><a href="{url item/detail/id/$sid}" src="$subject[thumb]" onMouseOver="tip_start(this,1);">$subject[name] $subject[subname]</a></h2>
<!--{eval $reviewcfg = $_G['loader']->variable('config','review');}-->
<p class="start start{print get_star($subject[avgsort],$reviewcfg[scoretype])}"></p>
<table class="subject_field_list" border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2"><span class="font_2">$subject[reviews]</span>点评,
<span class="font_2">$subject[guestbooks]</span>留言,
<span class="font_2">$subject[pageviews]</span>浏览</td>
</tr>
$subject_field_table_tr
</table>
<a class="abtn1" href="{url review/member/ac/add/type/item_subject/id/$subject[sid]}"><span>我要点评</span></a>
<a class="abtn2" href="javascript:add_favorite($sid);"><span>收藏</span></a>
<a class="abtn2" href="{url item/detail/id/$sid/view/guestbook}#guestbook"><span>留言</span></a>
<div class="clear"></div>
</dl>
</div>
</div>
<div id="position" class="deafBox">
<div class="deafBoxTit">
<h2>更多优惠券</h2>
</div>
<div class="deafBoxCon">
<div id="map_small">
<ul class="rail-list">
{get:coupon val=list_new(sid/$val[sid]/row/10)}
<li><a href="{url coupon/detail/id/$val[couponid]}" title="$val[subject]">{sublen $val[subject],20}</a></li>
{/get}
</ul>
</div>
</div>
</div>
<div id="position" class="deafBox">
<div class="deafBoxTit">
<h2>商户所在位置</h2>
</div>
<div class="deafBoxCon">
<!--{eval $model=$I->get_model($subject[catid],1);}-->
<!--{if $model[usearea]}-->
<div class="mainrail">
<!--{eval $mapparam = array(
'width' => '270',
'height' => '265',
'title' => $subject[name] . $subject[subname],
'p' => $subject[mappoint],
'show' => $subject[mappoint]?1:0,
);}-->
<iframe src="{URLROOT}/index.php?act=map&{print url_implode($mapparam)}" frameborder="0" scrolling="no" height="265" width="270"></iframe>
<div style="text-align:center;margin:5px 0;">
<!--{if !$subject['mappoint']}-->
<a href="javascript:post_map($subject[sid], $subject[pid]);">地图未标注,我来标注</a>
<!--{else}-->
<a href="javascript:show_bigmap();">查看大图</a>
<a href="javascript:post_map($subject[sid], $subject[pid]);">报错</a>
<!--{/if}-->
</div>
</div>
<script type="text/javascript">
function show_bigmap() {
<!--{eval $mapparam = array(
'width' => '600',
'height' => '400',
'title' => $subject[name] . $subject[subname],
'p' => $subject[mappoint],
'show' => $subject[mappoint]?1:0,
);}-->
var src = "{URLROOT}/index.php?act=map&{print url_implode($mapparam)}";
var html = '<iframe src="' + src + '" frameborder="0" scrolling="no" width="100%" height="400" id="ifupmap_map"></iframe>';
dlgOpen('查看大图', html, 600, 450);
}
</script>
<!--{/if}-->
</div>
</div>
</div>
<div id="chaBodyR">
<div id="chaBodyRTit">
<h2>优惠券信息</h2>
</div>
<div class="listCon">
<div id="coupon_left_vip">
<div class="detail">
<h1 class="subject">[{$category[$detail[catid]][name]}] $detail[subject]</h1>
<div class="info">发布时间:{date $detail[endtime],'Y-m-d'} 人气:$detail[pageview] 打印:$detail[prints] 评论:$detail[comments]</div>
<ul class="des">
<li>有效时间:{date $detail[starttime],'Y-m-d'} ~ {date $detail[endtime],'Y-m-d'}</li>
<li>优惠说明:$detail[des]</li>
</ul>
<div class="print">
<a class="abtn1" href="{url coupon/print/id/$couponid}"><span>打印此券</span></a>
<span id="btn_effect1"><a class="abtn2" href="javascript:coupon_effect($couponid);"><span>对我有用</span></a></span>
<div class="clear"></div>
</div>
<div class="content">
<p style="text-align:center;"><img src="{URLROOT}/$detail[picture]" alt="$detail[subject]" /></p>
<p>{print nl2br($detail[content])}</p>
</div>
<!--{if check_module('comment')}-->
<div class="comment_foo">
<style type="text/css">@import url("{URLROOT}/{$_G[tplurl]}css_comment.css");</style>
<script type="text/javascript" src="{URLROOT}/static/javascript/comment.js"></script>
<!--{eval $comment_modcfg = $_G['loader']->variable('config','comment');}-->
<!--{if $detail[comments]}-->
<!--{/if}-->
<a name="comment"></a>
{eval $_G['loader']->helper('form');}
<div id="comment_form">
<!--{if $user->check_access('comment_disable', $_G['loader']->model(':comment'), false)}-->
<!--{if $MOD[post_comment] && !$comment_modcfg['disable_comment'] && !$detail[closed_comment]}-->
<!--{eval $idtype = 'coupon'; $id = $couponid; $title = 'Re:' . $detail[subject];}-->
{template comment_post}
<!--{else}-->
<div class="messageborder">评论已关闭</div>
<!--{/if}-->
<!--{else}-->
<div class="messageborder">如果您要进行评论信息,请先 <a href="{url member/login}">登录</a> 或者 <a href="{url member/reg}">快速注册</a> 。</div>
<!--{/if}-->
</div>
<!--{if !$comment_modcfg['hidden_comment']}-->
<div class="mainrail rail-border-3">
<em>评论总数:<span class="font_2">$detail[comments]</span>条</em>
<h1 class="rail-h-3 rail-h-bg-3">网友评论</h1>
<div id="commentlist" style="margin-bottom:10px;"></div>
<script type="text/javascript">
$(document).ready(function() { get_comment('coupon',$couponid,1); });
</script>
</div>
<!--{/if}-->
</div>
<!--{/if}-->
</div>
</div>
</div>
<div class="pageRoll">
<div class=plist id=pageConDown> 以上优惠最终解释权归【$subject[name] $subject[subname]】所有 </div> </div>
</div>
<div class="clear"></div>
<!--{template 'footer', 'item', $subject[templateid]}--><file_sep>/core/modules/tuan/assistant/g_coupon.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
$T =& $_G['loader']->model(':tuan');
$TC =& $_G['loader']->model('tuan:coupon');
$op = _input('op');
$_G['loader']->helper('form','item');
$_G['loader']->helper('form','tuan');
$status = _get('status', 'available', MF_TEXT);
$status_lang = lang('tuan_coupon_status');
switch($op) {
case 'use':
$TC->use_coupon(_post('serial'), _post('passward'));
redirect('global_op_succeed', url("tuan/member/ac/$ac/op/query/serial/"._post('serial')));
break;
case 'query':
$next_op = $op;
if(_input('serial')) {
$next_op = 'use';
if(!$detail = $TC->read(_input('serial'),'*',true)) redirect('tuan_coupon_empty');
$tuan = $T->read($detail['tid']);
}
break;
default:
$sid = abs ((int) $_GET['sid']);
$tid = abs ((int) $_GET['tid']);
$S =& $_G['loader']->model('item:subject');
if(!$subjects = $S->mysubject($user->uid)) redirect('product_mysubject_empty');
if($sid && !in_array($sid, $subjects)) redirect('product_mysubject_nonentity');
$where = array();
if($tid) {
$where['tid'] = $tid;
} else {
$where['tid'] = $T->mylist($subjects, true, true);
}
$offset = 20;
$start = get_start($_GET['page'], $offset);
list($total, $list) = $TC->getlist($where, $start, $offset);
if($total) {
$multipage = multi($total, $offset, $_GET['page'], url("tuan/member/ac/g_coupon/sid/$sid/tid/$tid/page/_PAGE_"));
}
}
?><file_sep>/core/modules/about/admin/templates/list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="post" action="<?=cpurl($module,$act)?>&" name="myform">
<div class="space">
<div class="subtitle">单页面管理</div>
<ul class="cptab">
<li<?=$_GET['enabled']=='Y'?' class="selected"':''?>><a href="<?=cpurl($module,$act,'',array('sign' => $_GET['sign'],'enabled'=>'Y'))?>">启用</a></li>
<li<?=$_GET['enabled']=='N'?' class="selected"':''?>><a href="<?=cpurl($module,$act,'',array('sign' => $_GET['sign'],'enabled'=>'N'))?>">停用</a></li>
</ul>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr class="altbg1">
<td width="50"><button type="button" onclick="checkbox_checked('apids[]');" class="btn2">全选</button></td>
<td width="100">地区</td>
<td width="*">页面名称</td>
<td width="100">页面标识</td>
<td width="100">所属页面组</td>
<td width="100">模版名称</td>
<td width="100">SEO(Title)</td>
<td width="150">SEO(Keywords)</td>
<td width="150">SEO(Description)</td>
<td width="50">操作</td>
</tr>
<?if($total):?>
<?while($val=$list->fetch_array()) {?>
<tr>
<td><input type="checkbox" name="apids[]" value="<?=$val['apid']?>" /></td>
<td><?=display('modoer:area',"aid/$val[city_id]")?></td>
<td><?=$val['pname']?></td>
<td><?=$val['mark']?></td>
<td><?=$val['mark']?></td>
<td><?=$val['templates']?></td>
<td><?=$val['title']?></td>
<td><?=$val['keywords']?></td>
<td><?=$val['description']?></td>
<td><a href="<?=url("about/page/info/$val[mark]")?>" target="_blank">预览</a> <a href="<?=cpurl($module,$act,'edit',array('apid'=>$val['apid'],'sign' => $_GET['sign']))?>">编辑</a></td>
</tr>
<?}?>
<?else:?>
<tr><td colspan="10">暂无信息</td></tr>
<?endif;?>
</table>
</div>
<div><?=$multipage?></div>
<center>
<input type="hidden" name="op" value="delete" />
<input type="hidden" name="dosubmit" value="yes" />
<button type="button" class="btn" onclick="document.location='<?=cpurl($module,$act,'add')?>'" />增加单页面</button>
<?if($total):?>
<button type="button" class="btn" onclick="easy_submit('myform','delete','apids[]');">删除所选</button>
<?endif;?>
<button type="button" onclick="document.location='<?=cpurl($module,$act)?>';" class="btn">返回</button>
</center>
</form>
</div><file_sep>/core/modules/fenlei/admin/templates/field_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="post" action="<?=cpurl($module,$act)?>">
<div class="space">
<div class="subtitle">字段管理</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y">
<tr class="altbg1">
<?if($op=='select'):?>
<td width="60">使用</td>
<?else:?>
<td width="60">排序</td>
<?endif;?>
<td width="*">字段标题</td>
<td width="150">字段名</td>
<td width="100">所属表</td>
<td width="100">字段类型</td>
<?if($op!='select'):?>
<td width="40"><center>核心</center></td>
<td width="40"><center>列表页</center></td>
<td width="40"><center>内容页</center></td>
<td width="40"><center>后台</center></td>
<td width="120">操作</td>
<?endif;?>
</tr>
<?if($list) { foreach($list as $val) {?>
<tr>
<?if($op=='select'):?>
<td><input type="checkbox" name="fieldids[]" value="<?=$val['fieldid']?>"<?=in_array($val['fieldid'], $select)?' checked="checked"':''?> /></td>
<?else:?>
<td><input type="text" name="neworder[<?=$val['fieldid']?>]" value="<?=$val['listorder']?>" class="txtbox5" /></td>
<?endif;?>
<td><?=$val['title']?></td>
<td><?=$val['fieldname']?></td>
<td><?=$val['tablename']?></td>
<td><?=$F->fieldtypes[$val['type']]?></td>
<?if($op!='select'):?>
<td><center><?=$val['iscore']?'√':'×'?></center></td>
<td><center><?=$val['show_list']?'√':'×'?></center></td>
<td><center><?=$val['show_detail']?'√':'×'?></center></td>
<td><center><?=$val['isadminfield']?'√':'×'?></center></td>
<td>
<a href="<?=cpurl($module,$act,'edit',array('fieldid'=>$val['fieldid']))?>">编辑</a>
<?if(!$val['iscore']) { $disable = $val['disable'] ? 'enable' : 'disable'; ?>
<a href="<?=cpurl($module,$act,$disable,array('modelid'=>$_GET['modelid'],'fieldid'=>$val['fieldid']))?>"><?=$val['disable']?'启用':'禁用'?></a>
<a href="<?=cpurl($module,$act,'delete',array('modelid'=>$_GET['modelid'],'fieldid'=>$val['fieldid']))?>" onclick="return confirm('您确定要进行删除操作吗?');">删除</a>
<?}?>
</td>
<?endif;?>
</tr>
<?}?>
<?} else {?>
<tr><td colspan="9">暂无信息。</td></tr>
<?}?>
</table>
<center>
<input type="hidden" name="pid" value="<?=$pid?>" />
<?if($op=='select'):?>
<input type="hidden" name="op" value="select" />
<input type="hidden" name="catid" value="<?=$catid?>" />
<button type="submit" class="btn" name="dosubmit" value="yes">提交</button>
<button type="button" class="btn" onclick="location.href='<?=cpurl($module,'category','',array('pid'=>$pid))?>'" /><?=lang('global_return')?></button>
<?else:?>
<input type="hidden" name="op" value="listorder" />
<?if($list) {?>
<button type="submit" class="btn" name="dosubmit" value="yes">更新排序</button>
<?}?>
<button type="button" class="btn" onclick="document.location.href='<?=cpurl($module,'field','add',array('pid'=>$pid))?>'">新增字段</button>
<button type="button" class="btn" onclick="location.href='<?=cpurl($module,'category')?>'" /><?=lang('global_return')?></button>
<?endif;?>
</center>
</div>
</form>
</div><file_sep>/core/modules/mobile/member.php
<?php
!defined('IN_MUDDER') && exit('Access Denied');
$allowacs = array('index','review','subject');
$guestacs = array('review');
if(!$_GET['ac']) $_GET['ac'] = 'index';
$ac = !in_array($_GET['ac'], $allowacs) ? header("Location:" . url("mobile/member/ac/index")) : $_GET['ac'];
if(!$user->isLogin && !in_array($ac, $guestacs)) {
$forward = $_G['web']['reuri'] ? ($_G['web']['url'] . $_G['web']['reuri']) : url('mobile/index');
location(url('mobile/login/forward/'.base64_encode($forward)));
}
require_once MOD_ROOT . 'assistant' . DS . $ac . '.php';
?><file_sep>/core/modules/fenlei/helper/form.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
function form_fenlei_category($pid=0,$select='',$out='',$type='option') {
$loader =& _G('loader');
$category = $loader->variable('category', 'fenlei', FALSE);
if(!$category) return '';
if($select && !$pid) {
if($category[$select] && $category[$select]['pid']) {
$select = $category[$select]['pid'];
}
} elseif($pid && !$select) {
if($category[$pid] && $category[$pid]['pid']) {
$select = $pid;
$pid = $category[$select]['pid'];
}
}
$list = array();
foreach($category as $catid => $val) {
if($pid>0 && !$val['pid']) continue;
if($val['pid']!=$pid) continue;
if(is_array($out) && in_array($catid,$out)) continue;
$list[$catid] = $val['name'];
}
$loader->helper('form');
return form_option($list,$select);
}
function form_fenlei_colors($select = '') {
$loader =& _G('loader');
$cfg = $loader->variable('config','fenlei');
if(!$cfg['colors']) return '';
$list = explode(',',$cfg['colors']);
$content = '';
foreach($list as $key) {
$selected = $key == $select ? ' selected' : '';
$content .= "\t<option value=\"$key\" style=\"background:$key;color:$key;\"$selected>$key</option>\r\n";
}
return $content;
}
function form_fenlei_days($vkey, $select = '') {
$loader =& _G('loader');
$cfg = $loader->variable('config','fenlei');
if(!$cfg[$vkey]) return '';
$list = explode("\r\n",$cfg[$vkey]);
$content = '';
foreach($list as $key) {
list($d,$p) = explode('|',$key);
$selected = $d == $select ? ' selected' : '';
$content .= "\t<option value=\"$key\" point=\"$p\">$d".lang('fenlei_days')."</option>\r\n";
}
return $content;
$loader->helper('form');
return form_option($list,$select);
}
function form_fenlei_tops($select='') {
$loader =& _G('loader');
$cfg = $loader->variable('config','fenlei');
if(!$cfg['top_level']) return '';
$list = explode(',',$cfg['top_level']);
if(count($list)!=3) return '';
$content = '';
$types = lang('fenlei_tops');
foreach($list as $i=>$key) {
if(!is_numeric($key)) return '';
$v = $i + 1;
$selected = $key == $select ? ' selected' : '';
$content .= "\t<option value=\"$v\" basenum=\"$key\" $selected>".$types[$v]."</option>\r\n";
}
return $content;
}
?><file_sep>/core/modules/item/admin/delivery.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(! defined ( 'IN_ADMIN' ) || ! defined ( 'IN_MUDDER' )) && exit ( 'Access Denied' );
$D = & $_G ['loader']->model ( MOD_FLAG . ':delivery' );
$op = isset ( $_POST ['op'] ) ? $_POST ['op'] : $_GET ['op'];
switch ($op) {
case 'update' :
if (! $_POST ['dosubmit']) {
$detail = $D->read ( $_GET ['sid'] );
$detail ['c_payment'] = explode ( ',', $detail ['c_payment'] );
$detail ['c_deliver'] = explode ( ',', $detail ['c_deliver'] );
$detail ['c_book'] = explode ( ',', $detail ['c_book'] );
$_G ['loader']->helper ( 'form', 'item' );
$admin->tplname = cptpl ( 'delivery_save', MOD_FLAG );
} else {
$post ['sid'] = $_POST ['sid'];
$post ['c_book'] = $_POST ['book'];
$post ['c_payment'] = $_POST ['payment'];
$post ['c_deliver'] = $_POST ['deliver'];
$post ['c_types'] = $_POST ['c_types'];
$post ['c_minprice'] = $_POST ['c_minprice'];
$post ['c_freight'] = $_POST ['c_freight'];
$post ['c_pack'] = $_POST ['c_pack'];
$post ['c_range'] = $_POST ['c_range'];
$post ['c_content'] = $_POST ['c_content'];
$post['c_status']='1';
//保存操作
$D->update($post, $_POST ['sid']);
// 更新外卖类型属性
$AD = & $_G ['loader']->model ( 'item:att_data' );
$AD->add ( 3, $_POST ['sid'], $post ['c_types'] );
redirect ( 'global_op_succeed', get_forward ( cpurl ( $module, $act, 'list' ) ) );
}
break;
case 'delete' :
$D->delete ( _post ( 'ids' ) );
redirect ( 'global_op_succeed_delete', get_forward ( cpurl ( $module, $act, 'list' ) ) );
break;
default :
$op = 'list';
$status=$_GET ['f'];
$D->db->join ( $D->table, 'a.sid', 'dbpre_subject', 's.sid', MF_DB_LJ );
if (! $admin->is_founder)
$D->db->where ( 'a.city_id', $_CITY ['aid'] );
if (is_numeric ( $_GET ['city_id'] ) && $_GET ['city_id'] >= 0)
$D->db->where ( 'a.city_id', $_GET ['city_id'] );
if($status=='0'){
$D->db->where ( 'a.c_status','0');
}
else {
$D->db->where_more ('a.c_status',$status);
}
if ($_GET ['sid'])
$D->db->where ( 'a.sid', $_GET ['sid'] );
if ($_GET ['name'])
$D->db->where_like ( 'a.name', '%' . $_GET ['name'] . '%' );
if ($_GET ['starttime'])
$D->db->where_more ( 'a.lastupdate', strtotime ( $_GET ['starttime'] ) );
if ($_GET ['endtime'])
$D->db->where_less ( 'a.lastupdate', strtotime ( $_GET ['endtime'] ) );
if ($total = $D->db->count ()) {
$D->db->sql_roll_back ( 'from,where' );
! $_GET ['orderby'] && $_GET ['orderby'] = 'sid';
! $_GET ['ordersc'] && $_GET ['ordersc'] = 'DESC';
$D->db->order_by ( 'a.' . $_GET ['orderby'], $_GET ['ordersc'] );
$D->db->limit ( get_start ( $_GET ['page'], $_GET ['offset'] ), $_GET ['offset'] );
$D->db->select ( 'a.*,s.name as subjectname,s.subname,s.fullname' );
$list = $D->db->get ();
$multipage = multi ( $total, $_GET ['offset'], $_GET ['page'], cpurl ( $module, $act, 'list', $_GET ) );
}
$admin->tplname = cptpl ( 'delivery_list', MOD_FLAG );
}<file_sep>/core/modules/fenlei/admin/menus.inc.php
<?php
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$modmenus = array(
'fenlei|模块配置|config',
'fenlei|分类管理|category',
'fenlei|信息管理|fenlei',
'fenlei|信息审核|fenlei|checklist',
);
?><file_sep>/core/modules/tuan/admin/templates/coupon_list.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<div id="body">
<form method="get" action="<?=SELF?>">
<input type="hidden" name="module" value="<?=$module?>" />
<input type="hidden" name="act" value="<?=$act?>" />
<input type="hidden" name="op" value="<?=$op?>" />
<div class="space">
<div class="subtitle">团购券筛选</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100" class="altbg1">团购ID</td>
<td width="*"><input type="text" name="tid" class="txtbox4" value="<?=$_GET['tid']?>" /></td>
</tr>
<tr>
<td class="altbg1">团购券<br />一行一个</td>
<td colspan="3"><textarea name="serial" style="width:300px;height:50px;"><?=$_GET['serial']?></textarea></td>
</tr>
<tr>
<td class="altbg1">筛选</td>
<td colspan="3">
<button type="submit" value="yes" name="dosubmit" class="btn2">筛选</button>
</td>
</tr>
</table>
</div>
</form>
<form method="post" action="<?=cpurl($module,$act)?>" name="myform">
<div class="space">
<div class="subtitle">团购券管理</div>
<ul class="cptab">
<?foreach(lang('tuan_coupon_status') as $k => $v):?>
<li<?=$_GET['status']==$k?' class="selected"':''?>><a href="<?=cpurl($module,$act,'list',array('status'=>$k))?>"><?=$v?>(<?=(int)$lsit_total[$k]['count']?>)</a></li>
<?endforeach;?>
</ul>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" trmouse="Y">
<tr class="altbg1">
<?if($_GET['status']=='new'):?>
<td width="30">选</td>
<?endif;?>
<td width="150">券号</td>
<?if($admin->is_founder=='Y'):?>
<td width="150">密码</td>
<?endif;?>
<td width="*">项目</td>
<td width="100">用户</td>
<td width="110">有效期</td>
<?if($_GET['status']=='used'):?>
<td width="110">使用时间</td>
<td width="120">操作员</td>
<?endif;?>
</tr>
<?if($total):?>
<?while($val=$list->fetch_array()) {?>
<tr>
<?if($_GET['status']=='new'):?>
<td><input type="checkbox" name="serials[]" value="<?=$val['serial']?>" /></td>
<?endif;?>
<td><?=$val['serial']?></td>
<?if($admin->is_founder=='Y'):?>
<td><?=$val['passward']?></td>
<?endif;?>
<td><a href="<?=url("tuan/detail/id/$val[tid]")?>" target="_blank"><?=$val['subject']?></a></td>
<td><a href="<?=url("space/index/uid/$val[uid]")?>" target="_blank"><?=$val['username']?></a></td>
<td><?=date('Y-m-d', $val['expiretime'])?></td>
<?if($_GET['status']=='used'):?>
<td><?=date('Y-m-d H:i', $val['usetime'])?></td>
<td>
<?if($val['op_uid']):?>
<a href="<?=url("space/index/uid/$val[op_uid]")?>"><?=$val['op_username']?></a>
<?else:?>
<?=$val['op_username']?><span class="font_2">(后台)</span>
<?endif;?>
</td>
<?endif;?>
</tr>
<?}?>
<?else:?>
<tr>
<td colspan="8">暂无信息</td>
</tr>
<?endif;?>
</table>
</div>
<div><?=$multipage?></div>
<center>
<input type="hidden" name="op" value="update" />
<input type="hidden" name="dosubmit" value="yes" />
<?if($total):?>
<button type="button" class="btn" onclick="if(confirm('您确定要设置所选团购券为已使用状态吗?')) easy_submit('myform','used','serials[]');">设置团购券已使用</button>
<?endif;?>
</center>
</form>
</div><file_sep>/core/modules/party/model/party_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
class msm_party extends ms_model {
var $table = 'dbpre_party';
var $key = 'partyid';
var $model_flag = 'party';
var $category_table = 'dbpre_party_category';
var $flag = array(1,2,3);
var $status = array(0,1,2);
var $category = null;
function __construct() {
parent::__construct();
$this->model_flag = 'party';
$this->init_field();
$this->modcfg = $this->variable('config');
$this->category = $this->variable('category');
}
function msm_party() {
$this->__construct();
}
function init_field() {
$this->add_field('subject,catid,city_id,aid,sid,uid,username,status,joinendtime,begintime,endtime,plannum,sex,age,price,thumb,linkman,contact,address,des');
$this->add_field_fun('catid,city_id,sid,aid,uid,status,joinendtime,begintime,endtime,plannum,sex', 'intval');
$this->add_field_fun('subject,des,age,price,thumb,linkman,contact,address,', '_T');
$this->add_field_fun('des', '_HTML');
}
function read($partyid) {
if(!$result = parent::read($partyid)) return;
if($result['map_lng'] != 0 && $result['map_lat'] != 0) {
$result['mappoint'] = $result['map_lng'].','.$result['map_lat'];
}
$this->_plan_check_flag($result);
return $result;
}
function calendar($select,$where) {
$this->db->from($this->table);
$this->db->select($select?$select:'*');
$this->db->where($where);
if(!$q = $this->db->get()) return;
$list = array();
while($v = $q->fetch_array()) {
$list[] = $v;
}
$q->free_result();
return $list;
}
//获取未审核内容
function checklist($where = array()) {
$result = array(0,null,null);
$this->db->from($this->table);
if($where) $this->db->where($where);
$this->db->where('status',0);
if($result[0] = $this->db->count()) {
$this->db->sql_roll_back('from,where');
$this->db->select('partyid,aid,catid,thumb,subject,uid,username,address,num,flag,joinendtime,begintime,endtime');
$this->db->order_by('dateline', 'DESC');
$offset = 20;
$this->db->limit(get_start($_GET['page'], $offset), $offset);
$result[1] = $this->db->get();
$result[2] = multi($total, $_GET['offset'], $_GET['page'], cpurl($module, $act, 'checklist'));
}
return $result;
}
//保存活动
function save($post, $partyid = null, $role = 'member') {
$edit = $partyid > 0;
if($edit) {
if(!$detail = $this->read($partyid)) redirect('party_empty');
if(!$this->in_admin) {
if(isset($post['status'])) unset($post['status']);
$this->check_post_access('edit', $role, $detail['sid'], $detail['uid']); //权限判断
}
} else {
if($this->in_admin) {
$post['username'] = $this->global['admin']->adminname;
} else {
$post['uid'] = $this->global['user']->uid;
$post['username'] = $this->global['user']->username;
$post['status'] = $this->modcfg['party_check'] ? 0 : 1;
$this->check_post_access('add', $role, $post['sid'], $this->global['user']->uid);
}
$post['dateline'] = $this->global['timestamp'];
}
//设置城市ID
$AREA =& $this->loader->model('area');
$city_id = $AREA->get_parent_aid($post['aid']);
$post['city_id'] = $city_id;
foreach(array('joinendtime','begintime','endtime') as $k) {
if(!preg_match("/^[0-9]{4}\-[0-9]{1,2}\-[0-9]{1,2}\s[0-9]{1,2}:[0-9]{1,2}$/", $post[$k])) redirect('global_time_invalid');
$post[$k] = strtotime($post[$k]);
}
if(isset($post['mappoint'])) {
list($post['map_lng'], $post['map_lat']) = $this->_pares_map($post['mappoint']);
unset($post['mappoint']);
}
if($_FILES['picture']['name']) {
$this->loader->lib('upload_image', NULL, FALSE);
$img = new ms_upload_image('picture', $this->global['cfg']['picture_ext']);
$this->upload_thumb($img);
$post['thumb'] = str_replace(DS, '/', $img->path . '/' . $img->thumb_filenames['thumb']['filename']);
}
if($edit && $detail['thumb'] && $post['thumb']) {
$this->_delete_thumb($detail['thumb']);
}
//设置活动状态
$post['flag'] = $this->_check_flag($post['joinendtime'], $post['begintime'], $post['endtime']);
$partyid = parent::save($post, $detail ? $detail : $partyid);
if($edit) {
if($detail['catid'] != $post['catid']) { //是否更换了分类
if($detail['status']) $this->category_num($detail['catid'],-1); //原分类通过审核的数量-1
if($post['status']) $this->category_num($post['catid'],1); //新分类数量+1
} else {
if(!$detail['status'] && $post['status']) {
$this->category_num($post['catid'],1); //通过审核+1
} elseif($detail['status'] && isset($post['status']) && $post['status']==0 ) {
$this->category_num($post['catid'],-1); //更改审核状态-1
}
}
if(!$detail['status'] && $post['status']) {
$this->user_point_add($detail['uid']); //用户积分
$detail['uid']>0 && $this->_feed($fid); //feed
}
} elseif($post['status']) {
define('RETURN_EVENT_ID', 'global_op_succeed');
$this->category_num($post['catid'],1); //新入不需要审核+1
$this->user_point_add($post['uid']); //用户积分
$post['uid'] && $this->_feed($fid); //feed
} else {
define('RETURN_EVENT_ID', 'global_op_succeed_check');
}
return $party;
}
//提交检测和判断
function check_post(&$post, $edit = false) {
if(!$post['subject']) redirect('party_post_subject_empty');
if(!$post['aid'] || !is_numeric($post['aid'])) redirect('party_post_aid_empty');
if(!$post['catid'] || !is_numeric($post['catid'])) redirect('party_post_catid_empty');
if(!$post['joinendtime']) redirect('party_post_joinendtime_empty');
if(!$post['begintime']) redirect($this->errmsg = 'party_post_begintime_empty');
if(!$post['endtime']) redirect('party_post_endtime_empty');
//if(!$post['address']) redirect('party_post_address_empty');
//if(!$post['plannum']) redirect('party_post_plannum_empty');
if(!$post['linkman']) redirect('party_post_linkman_empty');
if(!$post['contact']) redirect('party_post_contact_empty');
if(!$post['des']) redirect('party_post_des_empty');
}
//上传图片
function upload_thumb(& $img) {
$thumb_w = $this->modcfg['party_thumb_w'] ? $this->modcfg['party_thumb_w'] : 200;
$thumb_h = $this->modcfg['party_thumb_h'] ? $this->modcfg['party_thumb_h'] : 150;
$img->set_max_size($this->global['cfg']['picture_upload_size']);
$img->userWatermark = $this->global['cfg']['watermark'];
$img->watermark_postion = $this->global['cfg']['watermark_postion'];
$img->thumb_mod = $this->global['cfg']['picture_createthumb_mod'];
//$img->limit_ext = array('jpg','png','gif');
$img->set_ext($this->global['cfg']['picture_ext']);
$img->set_thumb_level($this->global['cfg']['picture_createthumb_level']);
$img->add_thumb('thumb', 'thumb_', $thumb_w, $thumb_h);
$img->upload('party');
}
//审核
function checkup($ids,$uppoint=true) {
$ids = parent::get_keyids($ids);
$this->db->from($this->table);
$this->db->where_in('partyid', $ids);
$this->db->where('status', 0);
$this->db->select('partyid,uid,status,catid,thumb');
if(!$q=$this->db->get()) return;
$keyids = $catids = $uids = array();
while($v=$q->fetch_array()) {
$keyids[] = $v['partyid'];
if(isset($catids[$v['catid']])) {
$catids[$v['catid']]++;
} else {
$catids[$v['catid']] = 1;
}
if(!$uppoint||!$v['uid']) continue;
if(isset($uids[$v['uid']])) {
$uids[$v['uid']]++;
} else {
$uids[$v['uid']] = 1;
}
$v['uid'] > 0 && $this->_feed($v['fid']); //feed
}
$q->fetch_array();
if($catids) {
foreach($catids as $catid => $num) {
$this->category_num($catid, $num);
}
}
if($uids) {
foreach($uids as $uid => $num) {
$this->user_point_add($uid, $num);
}
}
if($keyids) {
$this->db->from($this->table);
$this->db->set('status', 1);
$this->db->where_in('partyid', $keyids);
$this->db->update();
}
}
//更新操作
function update($post) {
if(!$post || !is_array($post)) redirect('global_op_unselect');
foreach($post as $partyid => $val) {
if(!$partyid) continue;
$this->db->from($this->table);
$this->db->set('finer', (int)$val['finer']);
$this->db->where('partyid', $partyid);
$this->db->update();
}
}
//我的活动,返回id数组
function mypartys($uid) {
$result = array();
$this->db->from($this->table);
$this->db->where('uid',$uid);
$this->db->select('partyid');
if(!$q=$this->db->get()) return $result;
while($v=$q->fetch_array()) {
$result[] = $v['partyid'];
}
$q->free_result();
return $result;
}
//判断是否是我的活动
function is_myparty($partyid, $uid) {
$this->db->from($this->table);
$this->db->where('partyid',$partyid);
$this->db->where('uid',$uid);
return $this->db->count() > 0;
}
//删除
function delete($ids,$up_point=false) {
$ids = parent::get_keyids($ids);
$this->_delete(array('partyid'=>$ids), TRUE, $up_point);
}
//删除某些分类的
function delete_catids($catids) {
if(!$catids) return;
$this->_delete(array('catid'=>$catids), FALSE, FALSE);
}
//删除某些主题的
function delete_sids($sids) {
if(empty($sids)) return;
$where = array('sid'=>$sids);
$this->_delete($where);
}
//会员组权限判断
function check_access($key, $value, $jump) {
if($this->in_admin) return TRUE;
if($key=='party_post') {
$value = (int) $value;
if(!$value) {
if(!$jump) return FALSE;
if(!$this->global['user']->isLogin) redirect('member_not_login');
redirect('fenlei_access_disable');
}
}
return TRUE;
}
//判断2种角色的提交权限
function check_post_access($op='add', $role='member', $sid, $uid) {
if($this->in_admin) return TRUE;
if($op == 'add') {
return $this->global['user']->check_access('party_post', $this, 0);
} else {
if($this->global['user']->uid == $uid) {
return TRUE;
}
}
return FALSE;
}
//判断删除权限
function check_delete_access($uid, $sid, &$mysubjects) {
if($this->in_admin) return TRUE;
if(is_array($mysubjects) && $sid > 0 && in_array($sid, $mysubjects)) return TRUE;
if($uid > 0 && $uid == $this->global['user']->uid && $this->global['user']->check_access('party_delete', $this, 0)) return TRUE;
return false;
}
//更新分类统计
function category_num($catid, $num=1) {
if(!$num) return;
$this->db->from($this->category_table);
if($num > 0) {
$this->db->set_add('num',$num);
} else {
$this->db->set_dec('num',abs($num));
}
$this->db->where('catid',$catid);
$this->db->update();
}
// 增加积分
function user_point_add($uid, $num = 1) {
if(!$uid) return;
$P =& $this->loader->model('member:point');
$BOOL = $P->update_point($uid, 'add_party', FALSE, $num);
/*
if(!$BOOL) return;
$this->db->set_add('fenleis', $num);
$this->db->update();
*/
}
// 减少积分
function user_point_dec($uid, $num = 1) {
if(!$uid) return;
$P =& $this->loader->model('member:point');
$BOOL = $P->update_point($uid, 'add_party', TRUE, $num);
/*
if(!$BOOL) return;
$this->db->set_dec('fenleis', $num);
$this->db->update();
*/
}
//增加浏览量
function pageview($partyid, $num=1) {
$this->db->from($this->table);
$this->db->set_add('pageview', $num);
$this->db->where('partyid',$partyid);
$this->db->update();
}
//报名
function join($partyid, $num=1, $act='add') {
$this->db->from($this->table);
$this->db->where('partyid',$partyid);
if($act == 'add')
$this->db->set_add('num', $num);
else
$this->db->set_dec('num', $num);
$this->db->update();
}
//更新活动状态
function update_flag() {
$this->db->from($this->table);
$this->db->where_less('flag',2);
$this->db->where('status',1);
$this->db->select('partyid,flag,joinendtime,begintime,endtime');
if(!$q = $this->db->get()) return;
$update = array();
while($v=$q->fetch_array()) {
if($v['flag'] != $this->_check_flag($v['joinendtime'],$v['begintime'],$v['endtime'])) {
$update[$v['flag']][] = $v['partyid'];
}
}
$q->fetch_array();
if(!$update) return;
foreach($update as $flag => $ids) {
$this->db->from($this->table);
$this->db->where_in('partyid',$ids);
$this->db->set('flag', $flag);
$this->db->update();
}
}
/******************************* private ********************************/
function _check_flag($join, $begin, $end) {
$flag = 1;
if($this->global['timestamp'] < $join) {
$flag = 1;
} elseif($this->global['timestamp'] > $join && $this->global['timestamp'] < $end) {
$flag = 2;
} elseif($this->global['timestamp'] > $end) {
$flag = 3;
}
return $flag;
}
function _plan_check_flag(& $party) {
$nowflag = $this->_check_flag($party['joinendtime'], $party['begintime'], $party['endtime']);
if($party['flag'] <= 3 && $party['flag'] != $nowflag) {
$party['flag'] = $nowflag;
$this->db->from($this->table);
$this->db->set('flag', $nowflag);
$this->db->where('partyid', $party['partyid']);
$this->db->update();
}
}
//删除分类信息
function _delete($where, $up_total = TRUE, $up_point = FALSE) {
$this->db->from($this->table);
$this->db->where($where);
$this->db->select('partyid,sid,uid,status,catid,thumb');
if(!$q=$this->db->get()) return;
if(!$this->in_admin) {
$S =& $this->loader->model('item:subject');
$mysubjects = $S->mysubject($this->global['user']->uid);
}
$keyids = $catids = $uids = array();
while($v=$q->fetch_array()) {
//权限判断
$access = $this->in_admin || $this->check_delete_access($v['uid'], $v['sid'], $mysubjects);
if(!$access) redirect('global_op_access');
$keyids[] = $v['partyid'];
if($v['thumb']) $this->_delete_thumb($v['thumb']);
if($v['status']=='1') {
if($up_total) {
if(isset($catids[$v['catid']])) {
$catids[$v['catid']]++;
} else {
$catids[$v['catid']] = 1;
}
}
if(!$up_point||!$v['uid']) continue;
if(isset($uids[$v['uid']])) {
$uids[$v['uid']]++;
} else {
$uids[$v['uid']] = 1;
}
}
}
if($up_total && $catids) {
foreach($catids as $catid => $num) {
$this->category_num($catid, -$num);
}
}
if($uids) {
foreach($uids as $uid => $num) {
$this->user_point_dec($uid, $num);
}
}
if($keyids) {
$this->_delete_linktable($keyids);
parent::delete($keyids);
}
}
//删除管理表单(图片,报名,content)
function _delete_linktable($keyids) {
//报名信息
$APPLY =& $this->loader->model('party:apply');
$APPLY->delete_partyids($keyids);
unset($APPLY);
//留言信息
$COMMENT =& $this->loader->model('party:comment');
$COMMENT->delete_partyids($keyids);
unset($COMMENT);
//精彩回顾
$CONTENT =& $this->loader->model('party:content');
$CONTENT->delete($keyids);
unset($CONTENT);
//活动照片
$PIC =& $this->loader->model('party:picture');
$PIC->delete_partyids($keyids);
unset($PIC);
}
//解析地图坐标
function _pares_map($point) {
$result = array(0,0);
list($lng,$lat) = explode(',', trim($point));
if(!$lng || !$lat) return $result;
if(!preg_match("/[0-9\-\.]+/", $lng) || !preg_match("/[0-9\-\.]+/", $lat)) return $result;
return array($lng,$lat);
}
//删除图片
function _delete_thumb($thumb) {
@unlink(MUDDER_ROOT . $thumb);
@unlink(MUDDER_ROOT . str_replace("/thumb_", "/", $thumb));
}
//feed
function _feed($fid) {
if(!$fid) return;
$FEED =& $this->loader->model('member:feed');
if(!$FEED->enabled()) return;
$this->global['fullalways'] = TRUE;
if(!$detail = $this->read($fid, false)) return;
if(!$detail['uid']) return;
$feed = array();
$feed['icon'] = lang('party_feed_icon');
$feed['title_template'] = lang('party_feed_title_template');
$feed['title_data'] = array (
'username' => '<a href="'.url("space/index/uid/$detail[uid]").'">' . $detail['username'] . '</a>',
);
$feed['body_template'] = lang('party_feed_body_template');
$feed['body_data'] = array (
'subject' => '<a href="'.url("party/detail/id/$detail[fid]").'">' . $detail['subject'] . '</a>',
);
$feed['body_general'] = trimmed_title(strip_tags(preg_replace("/\[.+?\]/is", '', $detail['des'])), 150);
$FEED->save($this->model_flag, $detail['city_id'], $feed['icon'], $detail['uid'], $detail['username'], $feed);
//$FEED->add($feed['icon'], $detail['uid'], $detail['username'], $feed['title_template'], $feed['title_data'], $feed['body_template'], $feed['body_data'], $feed['body_general']);
}
}
?><file_sep>/core/modules/tuan/model/wish_class.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
class msm_tuan_wish extends ms_model {
var $table = 'dbpre_tuan_wish';
var $key = 'twid';
var $model_flag = 'tuan';
function __construct() {
parent::__construct();
$this->model_flag = 'tuan';
$this->init_field();
$this->modcfg = $this->variable('config');
}
function init_field() {
$this->add_field('city_id,uid,username,title,thumb,price,content,status');
$this->add_field_fun('title,username', '_T');
$this->add_field_fun('city_id,uid,status', 'intval');
$this->add_field_fun('content', '_TA');
}
//保存
function save($post, $twid=null) {
$edit = $twid != null;
if($edit) {
if(!$detail = $this->read($twid)) redirect('tuan_wish_empty');
} else {
$post['status'] = '0';
if(!$this->in_admin) {
$post['uid'] = $this->global['user']->uid;
$post['username'] = $this->global['user']->username;
$post['city_id'] = $this->global['city']['aid'];
}
$post['dateline'] = $this->global['timestamp'];
}
//上传图片部分
if($_FILES['picture']['name']) {
$this->loader->lib('upload_image', NULL, FALSE);
$img = new ms_upload_image('picture', $this->global['cfg']['picture_ext']);
$this->upload_thumb($img);
$post['picture'] = str_replace(DS, '/', $img->path . '/' . $img->filename);
$post['thumb'] = str_replace(DS, '/', $img->path . '/' . $img->thumb_filenames['thumb']['filename']);
unset($img);
}
$twid = parent::save($post, $edit?$detail:$twid);
define('RETURN_EVENT_ID', $this->in_admin ? 'global_op_succeed' : 'global_op_succeed_check');
return $twid;
}
//审核
function checkup($twids) {
$ids = parent::get_keyids($twids);
$this->db->from($this->table);
$this->db->where('twid',$twids);
$this->db->set('status',1);
$this->db->update();
foreach($ids as $id) {
$this->_feed($id);
}
}
//前台列表
function get_list($city_id,$succeed,$orderby,$start,$offset) {
$this->db->from($this->table);
if($succeed == '0') {
$this->db->where('tid',0);
} elseif($succeed) {
$this->db->where_not_equal('tid',0);
}
$this->db->where('status ',1);
$this->db->where('city_id',$city_id);
if(!$result[0] = $this->db->count()) {
return $result;
}
$this->db->sql_roll_back('from,where');
$this->db->select('*');
if($orderby) $this->db->order_by($orderby);
$this->db->limit($start, $offset);
$q = $this->db->get();
while($v=$q->fetch_array()) {
$users = explode("\n", $v['interest_users']);
$list = false;
if(!empty($users)) {
foreach($users as $val) {
list($uid, $uname) = explode("\t", $val);
$list[$uid] = $uname;
}
}
$v['interest_users'] = $list;
$result[1][] = $v;
}
return $result;
}
//上传图片
function upload_thumb(& $img) {
$thumb_w = $this->modcfg['thumb_width'] ? $this->modcfg['thumb_width'] : 200;
$thumb_h = $this->modcfg['thumb_height'] ? $this->modcfg['thumb_height'] : 121;
$img->set_max_size($this->global['cfg']['picture_upload_size']);
$img->userWatermark = $this->modcfg['watermark'];
$img->watermark_postion = $this->global['cfg']['watermark_postion'];
$img->thumb_mod = $this->global['cfg']['picture_createthumb_mod'];
$img->set_ext($this->global['cfg']['picture_ext']);
$img->set_thumb_level($this->global['cfg']['picture_createthumb_level']);
$img->add_thumb('thumb', 's_', $thumb_w, $thumb_h);
$img->upload('tuan');
}
//提交检测
function check_post(& $post, $edit = false) {
$this->loader->helper('validate');
if(!is_numeric($post['city_id'])) redirect('tuan_post_city_empty');
if(!$post['title']) redirect('tuan_wish_title_empty');
if(!validate::is_numeric($post['price'])) redirect('tuan_wish_price_empty');
if(!$post['content']) redirect('tuan_wish_content_empty');
}
//已成功发起团购
function succeed($twid,$tid) {
$this->db->from($this->table);
$this->db->where('twid',$twid);
$this->db->set('tid',$tid);
$this->db->update();
}
//感兴趣
function interest($twid) {
if(!$this->global['user']->uid) redirect('member_op_not_login');
$detail = $this->read($twid);
if(empty($detail)) redirect('tuan_wish_empty');
$users = explode("\n", $detail['interest_users']);
$exists = false;
if(!empty($users)) {
foreach($users as $val) {
list($uid, $uname) = explode("\t", $val);
if($uid == $this->global['user']->uid) {
redirect('tuan_wish_interest_exists');
}
}
}
$txt = $this->global['user']->uid . "\t" . $this->global['user']->username;
$detail['interest_users'] = $txt . ( $detail['interest_users'] ? ("\n".$detail['interest_users']):'');
$this->db->from($this->table);
$this->db->where('twid',$twid);
$this->db->set_add('interest',1);
$this->db->set('interest_users',$detail['interest_users']);
$this->db->update();
}
//承接申请
function undertake($twid,$num=1) {
$this->db->from($this->table);
$this->db->where('twid', $twid);
$fun = $num > 0 ? 'set_add' : 'set_dec';
$this->db->$fun('undertakers', abs($num));
$this->db->update();
}
//设置某个用户为承接用户
function set_undertaker($tuid) {
$tu = $this->loader->model('tuan:undertake');
$undertake = $tu->read($tuid);
if(!$undertake) redirect('tuan_undertask_empty');
$wish = $this->read($undertake['twid']);
if(!$wish) redirect('tuan_wish_empty');
$this->db->from($this->table);
$this->db->where('twid', $undertake['twid']);
$this->db->set('undertaker', $undertake['uid']."\t".$undertake['username']);
$this->db->update();
}
//会员组权限判断
function check_access($key, $value, $jump) {
if($this->in_admin) return TRUE;
if($key=='tuan_post_wish') {
$value = (int) $value;
if(!$value) {
if(!$jump) return FALSE;
if(!$this->global['user']->isLogin) redirect('member_not_login');
redirect('tuan_post_wish_access_disable');
}
}
return TRUE;
}
function _feed($twid) {
if(!$twid) return;
$FEED =& $this->loader->model('member:feed');
if(!$FEED->enabled()) return;
$this->global['fullalways'] = TRUE;
$detail = $this->read($twid);
if(!$detail['uid']) return;
$city_id = (int) $detail['city_id'];
$feed = array();
$feed['icon'] = lang('tuan_post_wish_feed_icon');
$feed['title_template'] = lang('tuan_post_wish_title_template');
$feed['title_data'] = array (
'username' => '<a href="'.url("space/index/uid/$detail[uid]").'">' . $detail['username'] . '</a>',
);
$feed['body_template'] = lang('tuan_post_wish_feed_body_template');
$feed['body_data'] = array (
'title' => '<a href="'.url("tuan/wish/twid/$detail[twid]").'">' . $detail['title'] . '</a>',
);
$feed['body_general'] = '';
$FEED->save($this->model_flag, $city_id, $feed['icon'], $detail['uid'], $detail['username'], $feed);
}
}
?><file_sep>/core/modules/tuan/admin/templates/tuan_detail.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript">
var current_id = 0;
function tuan_sms_start() {
var content = $('<div></div>').attr('id','taoke_store_save');
var textarea = $('<textarea></textarea>').attr('id','sms_status_content').
css({width:'100%', height:'200px', 'overflow-x':'visible'});
dlgOpen('团购券短信息发送',content, 500, 300);
var bttton1 = $('<button id="btn_start_save" type="button" class="btn">开始发送</button>').click(function() {
tuan_sms_sending();
});
var bttton2 = $('<button type="button" class="btn">关闭</button>').click(function() {
dlgClose();
});
content.append(textarea).append($('<center style="margin-top:10px;"></center>').
append(bttton1).append(' ').append(bttton2));
current_id = 0;
textarea.val("请点击开始发送...\r\n");
}
function tuan_sms_sending() {
$('#btn_start_save').hide();
current_id++;
$.post("<?=cpurl($module,'coupon','send_sms')?>", { in_ajax:1, tid:'<?=$tid?>', page:current_id }, function(data){
var s = tuan_sms_parse(data);
if(s.succeed) {
tuan_add_status(s.message, true);
tuan_sms_sending(s.succeed);
} else if(!s.succeed){
tuan_add_status(s.message, false);
tuan_sms_stop();
current_id = 0;
} else {
tuan_sms_stop(s.succeed,true);
current_id = 0;
}
});
}
function tuan_sms_stop(succeed) {
tuan_add_status('本次短信发送完毕.',succeed);
}
function tuan_add_status(msg,status,title) {
var textarea = $('#sms_status_content');
var message = (status?'√ ':'× ') + msg + (title?('('+title+')'):'');
textarea.val(textarea.val() + message + "\r\n");
document.getElementById('sms_status_content').scrollTop = document.getElementById('sms_status_content').scrollHeight;
}
function tuan_sms_parse(result) {
var s = { succeed:false, message:'未知错误', end:true }
data = result.match(/(\{\s+caption:".*",message:".*".*\s*\})/);
if (data) {
var mymsg = eval('('+data[0]+')');
result = mymsg.message;
} else {
return s;
}
alert(result);
if(result == 'ERROR:END') {
s.end = true;
s.message = '短信发送完毕.';
} else if(result.indexOf('ERROR:') > -1) {
s.succeed = false;
s.message = result.replace('ERROR:','');
} else if(result) {
s.end = false;
s.succeed = true;
s.message = result.replace('SUCCEED:','');
} else {
s.succeed = false;
s.message = result;
}
return s;
}
</script>
<div id="body">
<form method="post" name="myform" action="<?=cpurl($module,$act,'manage')?>">
<div class="space">
<div class="subtitle">团购详情</div>
<ul class="cptab">
<li class="selected"><a href="<?=cpurl($module,'tuan','detail',array('tid'=>$tid))?>">团购详情</a></li>
<li><a href="<?=cpurl($module,'order','list',array('tid'=>$tid))?>">订单管理</a></li>
</ul>
<table class="maintable" border="0" cellspacing="0" cellpadding="0" id="config1">
<tr>
<td class="altbg1" width="120">项目:</td>
<td width="*"><a href="<?=url("tuan/detail/id/$detail[tid]")?>" target="_blank"><?=$detail['subject']?></a></td>
</tr>
<tr>
<td class="altbg1">关联商家:</td>
<td><a href="<?=url("item/detail/id/detail[sid]")?>" target="_blank"><?=trim($subject['name'].($subject['subname']?"($subject[subname])":''))?></a></td>
</tr>
<tr>
<td class="altbg1">团购时间:</td>
<td>
<?=$detail['starttime']?> ~ <?=$detail['endtime']?>
</td>
</tr>
<tr>
<td class="altbg1">成团时间:</td>
<td>
<?=$detail['succeedtime']?$detail['succeedtime']:'尚未成团'?>
</td>
</tr>
<tr><td class="altbg2" colspan="2"><b>产品销售详情</b></td></tr>
<tr>
<td class="altbg1">团购模式:</td>
<td><?=lang('tuan_mode_'.$detail['mode'])?></td>
</tr>
<tr>
<td class="altbg1">产品总量:</td>
<td><?=$detail['goods_total']?> 件</td>
</tr>
<tr>
<?if($detail['mode'] == 'normal'):?>
<td class="altbg1">团购价格:</td>
<?else:?>
<td class="altbg1">团购临时价:</td>
<?endif;?>
<td class="font_1">¥<?=$detail['price']?></td>
</tr>
<?if($detail['mode'] == 'wholesale'):?>
<tr>
<td class="altbg1">批发价格策略:</td>
<td>
<?php
$prices = $T->parse_prices($detail[prices]);
foreach($prices as $num=>$price) {
echo '销售数量大于<span class="font_1">'.$num.'</span>件产品时,单价为<span class="font_1">'.$price.'</span>元/件<br />';
}
?>
</td>
</tr>
<tr>
<td class="altbg1">最低成团数量:</td>
<td><?=$detail['goods_min']?> 件</td>
</tr>
<?else:?>
<tr>
<td class="altbg1">最低成团人数:</td>
<td><?=$detail['peoples_min']?> 人</td>
</tr>
<?endif;?>
<tr>
<td class="altbg1">已购销售数量:</td>
<td><?=$detail['goods_sell']?> 件</td>
</tr>
<tr>
<td class="altbg1">已购买人数:</td>
<td><?=$detail['peoples_sell']?> 人</td>
</tr>
<tr>
<td class="altbg1">每人限购数量:</td>
<td><?=$detail['people_buylimit']?> 件</td>
</tr>
<tr><td class="altbg2" colspan="2"><b>销售订单统计</b></td></tr>
<tr>
<td class="altbg1">购买量:</td>
<td>
订单总量:<?=(int)$order_total['total']?>
已支付订单:<?=(int)$order_total['payed']['count']?>
未支付订单:<?=(int)$order_total['new']['count']?>
已取消订单:<?=(int)$order_total['cancel']['count']?>
已过期订单:<?=(int)$order_total['overdue']['count']?>
已退款订单:<?=(int)$order_total['refunded']['count']?>
</td>
</tr>
<tr>
<td class="altbg1">销售量:</td>
<td><?=(int)$order_total['payed']['num']?></td>
</tr>
<tr>
<td class="altbg1">销售额:</td>
<td class="font_1">¥<?=(float)$order_total['payed']['price']?></td>
</tr>
<?if($detail['sendtype']=='coupon'):?>
<tr>
<td class="altbg2" colspan="2"><b>团购券</b></td>
</tr>
<tr>
<td class="altbg1">发放统计:</td>
<td>
已发送优惠券:<?=(int)$coupon_total['total']?>
未使用数量:<?=(int)$coupon_total['new']['count']?>
已使用数量:<?=(int)$coupon_total['used']['count']?>
已过期数量:<?=(int)$coupon_total['expired']['count']?>
</td>
</tr>
<?if($detail['succeedtime']):?>
<tr>
<td class="altbg1">发放团购券:</td>
<td><button type="button" class="btn2" onclick="document.location='<?=cpurl($module,'coupon','send',array('tid'=>$detail['tid']))?>';">发放全部已付款订单团购券</button></td>
</tr>
<?if($MOD['send_sms']):?>
<tr>
<td class="altbg1">短信息统计:</td>
<td>
已发送:<?=$sms_total[1]?>
未发送:<?=$sms_total[2]?>
发送失败:<?=$sms_total[3]?>
</td>
</tr>
<tr>
<td class="altbg1">发送短信息:</td>
<td><button type="button" class="btn2" onclick="tuan_sms_start();">发送短信息</button></td>
</tr>
<?endif;?>
<?endif;?>
<?endif;?>
<?if($detail['mode']!='normal'):?>
<tr><td class="altbg2" colspan="2"><b>退还差价</b></td></tr>
<tr>
<td class="altbg1">最终价格:</td>
<td>
<?if($detail['mode']=='forestall'):?>
<div class="font_1">抢鲜团无统一价格,根据购买次序定价,请先更新差价再退款</div>
<?else:?>
<span class="font_1">¥<?=$detail['real_price']?></span>
(每件产品需退还差价<span class="font_1">¥<?=$detail['price']-$detail['real_price']?></span>)
<?endif;?>
</td>
</tr>
<tr>
<td class="altbg1">退款信息:</td>
<td>
需退款总金额:<span class="font_1">¥<?=(int)$order_total['payed']['balance_price']?></span>
已完成退款金额:<span class="font_1">¥<?=(int)$order_total['payed']['return_balance_price']?></span>
</td>
</tr>
<?if($detail['succeedtime'] && $detail['status']=='succeeded'):?>
<tr>
<td class="altbg1">退还差价:</td>
<td>
<button type="button" class="btn2" onclick="document.location='<?=cpurl($module,'order','update_real_price',array('tid'=>$detail['tid']))?>';">更新订单差价</button>
<button type="button" class="btn2" onclick="return href_submit_form('退还差价,请先点击“更新订单差价”按钮。\n您确定要将差价退还给所有已支付用户吗?','<?=cpurl($module,'order','return_balance')?>',<?=$detail['tid']?>);">向全部用户退还差价</button>
</td>
</tr>
<?endif;?>
<?endif;?>
</tr>
<?if($order_total['total'] > 0):?>
<tr>
<td class="altbg2" colspan="2"><b>退款信息</b></td>
</tr>
<tr>
<td class="altbg1">已退款量:</td>
<td><?=(int)$order_total['refunded']['count']?></td>
</tr>
<tr>
<td class="altbg1">全部退款:</td>
<td><button type="button" class="btn2" onclick="return href_submit_form('慎重!仅建议团购失败后使用!您确定要对本次团购的全部已支付订单进行退款?','<?=cpurl($module,'order','refund_tuan')?>',<?=$detail['tid']?>);">向所有已支付用户进行退款(慎重)</button></td>
</tr>
<?endif;?>
</table>
</div>
<center>
<input type="button" class="btn" value="返回" onclick="document.location='<?=cpurl($module,'tuan')?>';" />
</center>
<?=form_end()?>
</div>
<script type="text/javascript">
function href_submit_form (msg, $url, $tid) {
if(!confirm(msg)) return false;
var frm = $('#sfhjkshfd');
if(frm[0]) frm.remove();
frm = $("<form method=\"post\" action=\""+$url+"\"></form>");
var hie = $("<input type=\"hidden\" name=\"tid\">").val($tid);
frm.append(hie);
$(document.body).append(frm);
frm[0].submit();
}
</script><file_sep>/core/modules/coupon/mobile/match.php
<?php
! defined ( 'IN_MUDDER' ) && exit ( 'Access Denied' );
define ( 'SCRIPTNAV', 'coupon' );
$C = $_G ['loader']->model ( 'coupon:card' );
$M = $_G ['loader']->model ( 'coupon:match' );
//$card = $_GET ['card'];
$card='1001,1001';
if (empty ( $card )) {
}
$temp = explode ( ',', $card );
$cid = $temp [0];
$cpwd = $temp [1];
$r = $C->valide ( $cid, $cpwd );
if ($r == '1') {
redirect ( '卡号错误!' );
}
if ($r == '2') {
redirect ( '该券已被绑定过!' );
}
if ($r == '3') {
redirect ( '验证密码错误!' );
}
// 验证成功
if ($r == '4') {
$wxid='123';
$uid='5';
$post ['uid'] = $uid;
$post ['wxid'] = $wxid;
$post ['cid'] = $cid;
$post ['dateline'] = date ('Y-m-d h:m:s');
print_r($post);
$M->save ( $post,null );
//redirect ( '绑定成功!' );
}
?>
<file_sep>/core/modules/tuan/assistant/buy.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');
$O =& $_G['loader']->model('tuan:order');
if(check_submit('dosubmit')) {
if($oid = (int)_post('oid')) {
$O->save($oid);
} else {
$oid = $O->save();
}
location(url('tuan/member/ac/pay/id/'.$oid));
} else {
if($tid = (int)_get('id')) {
if($order = $O->check_bought($user->uid, $tid)) {
if($order['status']=='new') {
location(url('tuan/member/ac/buy/oid/'.$order['oid']));
} else {
redirect('tuan_buy_bought', url('tuan/member/ac/order'));
}
} else {
$order = array();
}
$detail = $O->check_buy($tid);
} elseif($oid = (int)_get('oid')) {
$order = $O->read($oid);
if(!$order = $O->read($oid)) redirect('tuan_order_empty');
if($order['status']!='new') location(url('tuan/member/ac/order/op/detail/oid/'.$oid));
$order['contact'] = $order['contact'] ? unserialize($order['contact']) : array();
$detail = $O->check_buy($order['tid']);
} else {
redirect('global_op_unkown');
}
$stock = $detail['goods_total'] - $detail['goods_sell'];
$buy_limit_num = min($stock, $detail['people_buylimit']);
$tplname = 'buy';
$_G['loader']->helper('form','member');
$address =& _G('loader')->model('member:address')->get_list();
}
?><file_sep>/core/modules/member/mobile/reg.php
<?php
$wxid = $_GET ['wxid'];
$wxid = '123';
$M = $_G ['loader']->model ( 'member:member' );
$MP = $_G ['loader']->model ( 'member:profile' );
$zd = $_G ['loader']->model ( 'zidian' );
//保存信息
if ($_POST ['dosubmit']) {
//保存会员基本信息
$uid=$_POST['uid'];
$home=$_POST['home'];
$work=$_POST['work'];
$postmem['uid']=$uid;
$postmem['password']=$postmem['password2']='321';
$postmem['wxid']=$wxid;
$postmem['username']='ag'.$uid;
$postmem['email']='<EMAIL>';
$id=$M->save($postmem,$uid);
//保存会员详细信息
$myprofile['uid']=$_POST['uid'];
$myprofile['tel']=$_POST['tel'];
$myprofile['qq']=$_POST['qq'];
$myprofile['work']=$work;
$myprofile['home']=$home;
$MP->save($myprofile,$uid);
//redirect('Ok');
//是否是新增加的字典数据
$ohome=$_POST['ohome'];
$owork=$_POST['owork'];
if($ohome!=$home){
$p['varname']=$home;
$p['vartype']='home';
$zd->save($p);
$zd->write_cache_home();
}
if($owork!=$work){
$p['varname']=$work;
$p['vartype']='work';
$zd->save($p);
$zd->write_cache_work();
}
}
// 加载会员基本信息
$profile = $M->read1 ( $wxid );
include mobile_template ( 'member_reg' );
?>
<file_sep>/core/modules/item/app/wmlist.php
<?php
/*
* 安卓应用:外卖列表代码
* 调用方法:http://127.0.0.7/item.php?act=app&do=wmlist&kwyword=无锡&total=15&page=0
* 关键词:keyword 坐标点:lat,lnt 总数目:total 当前页:page
*/
// 实例化主题类
$D = & $_G ['loader']->model ( 'item:takeout' );
$json = & $_G ['loader']->lib ( 'json', NULL, TRUE );
// 查询条件
$where = array ();
$where ['s.city_id'] = array (8 );
$where ['s.status'] = array ('where_not_equal',array ('0' ) );
// 关键词方式检索
$keyword = $_GET ['keyword'];
$keyword = '无锡科技职业学院';
if (! empty ( $keyword )) {
$where ['td.tagname'] = $keyword;
}
// 查询数据
$num = 10;
$offset = $num;
$start = get_start ( $_GET ['page'], $num );
$select="sf.sid,sf.c_dianhua,sf.c_dizhi,sf.c_yunye,sf.content,sf.c_minprice,sf.c_sendprice,sf.c_range,sf.c_jianjie,s.aid,s.pid,s.catid,s.name,s.subname,s.best,s.finer,s.map_lng,s.map_lat,s.fullname,s.status,s.pageviews";
list ( $total, $list ) = $D->find ($select, $where, $start, $num);
if ($total) {
while ( $val = $list->fetch_array () ) {
$result [] = seatch_to_waimai_array ( $val );
}
$list->free_result ();
$output = $json->encode ( array (
'msg' => '10001',
'data' => $result
) );
echo $output;
output ();
}
// 构造外卖商家数组
function seatch_to_waimai_array(&$val) {
return array (
'sid' => $val ['sid'],
'name' => $val ['fullname'],
'dianhua' => $val ['c_dianhua'],
'dizhi' => $val ['c_dizhi'],
'yunye' => $val ['c_yunye'],
'minprice' => $val ['c_minprice'],
'sendprice' => $val ['c_sendprice'],
'lat' => $val ['map_lat'],
'lng' => $val ['map_lng'],
'best' => $val ['best'],
'finer' => $val ['finer']
);
}
<file_sep>/core/admin/templates/cphome.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<script type="text/javascript" src="./static/javascript/mdialog.js"></script>
<div id="body">
<div class="space">
<div class="subtitle">后台在线用户</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<tr class="altbg1">
<td width="30%">用户名称</td>
<td width="40%">IP地址</td>
<td width="30%">最后活动时间</td>
</tr>
<?php if($sessions) while($val = $sessions->fetch_array()) { ?>
<?php if($val['adminname']==$admin->adminname){?><tr style="font-weight:bold;"><?}else{?><tr><?}?>
<td><?=$val['adminname']?></td>
<td><?=$val['ip']?></td>
<td><?=date('Y-m-d H:i:s', $val['dateline'])?></td>
</tr>
<? } ?>
</table>
</div>
<?if($_G['cfg']['console_total']):?>
<div class="space">
<div class="subtitle">数据统计</div>
<table class="maintable" border="0" cellspacing="0" cellpadding="0">
<?if($system):foreach($system as $key => $val):?>
<?if($key%3==0):?><tr><?endif;?>
<td width="100" class="altbg1"><?=$val['name']?></td>
<td width="200"><?=$val['content']?></td>
<?if($key%3==2):?></tr><?endif;?>
<?endforeach;?>
<?php
$ix=ceil(($key+1)/3) * 3 - ($key+1);
for($i=0;$i<$ix;$i++) {
echo '<td width="100" class="altbg1"> </td>';
echo '<td width="200"> </td>';
}
echo '</tr>';
?>
<?else:?>
<tr><td>没有统计信息。</td></tr>
<?endif;?>
</table>
</div>
<?endif;?>
</div>
<file_sep>/core/modules/fenlei/admin/templates/hook_usergroup_save.tpl.php
<?php (!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied'); ?>
<tr>
<td class="altbg1"><strong>禁止本组会员发布分类信息:</strong>开启本功能后,本组会员便可以在前台发布的分类信息</td>
<td><?=form_bool('access[fenlei_post]', $access['fenlei_post'])?></td>
</tr>
<tr>
<td class="altbg1"><strong>禁止本组会员删除自己的分类信息:</strong>开启本功能后,本组会员便可以在前台删除自己发布的分类信息</td>
<td><?=form_bool('access[fenlei_delete]', $access['fenlei_delete'])?></td>
</tr><file_sep>/core/modules/party/admin/party.inc.php
<?php
/**
* @author moufer<<EMAIL>>
* @copyright www.modoer.com
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');
$PARTY =& $_G['loader']->model(':party');
$_G['loader']->helper('form','party');
$op = _input('op');
switch($op) {
case 'add':
$_G['loader']->lib('editor',null,false);
$editor = new ms_editor('des');
$editor->item = 'admin';
$edit_html = $editor->create_html();
$admin->tplname = cptpl('party_save', MOD_FLAG);
break;
case 'edit':
if(!$partyid = _get('partyid',null,'intval')) redirect(lang('global_sql_keyid_invalid','partyid'));
if(!$detail = $PARTY->read($partyid)) redirect('party_empty');
if($detail['sid']>0) {
$S =& $_G['loader']->model('item:subject');
$subject = $S->read($detail['sid'],'*',false);
}
$_G['loader']->lib('editor',null,false);
$editor = new ms_editor('des');
$editor->item = 'admin';
$editor->content = $detail['des'];
$edit_html = $editor->create_html();
$admin->tplname = cptpl('party_save', MOD_FLAG);
break;
case 'save':
if(_post('do')=='edit') {
if(!$partyid = _post('partyid',null,'intval')) redirect(lang('global_sql_keyid_invalid','partyid'));
} else {
$partyid = null;
}
$post = $PARTY->get_post($_POST);
$partyid = $PARTY->save($post, $partyid);
redirect('global_op_succeed',get_forward(cpurl($module,$act),1));
break;
case 'delete':
$PARTY->delete($_POST['partyids']);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'update':
$PARTY->update($_POST['partys']);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'content':
if(!$partyid = _input('partyid', null, 'intval')) redirect(lang('global_sql_keyid_invalid','partyid'));
if(!$party = $PARTY->read($partyid)) redirect('party_empty');
$CON =& $_G['loader']->model('party:content');
if(check_submit('dosubmit')) {
$CON->save(_post('content'), $partyid);
redirect('global_op_succeed', get_forward(cpurl($module,$act),1));
} else {
$content = $CON->read($partyid);
$_G['loader']->lib('editor',null,false);
$editor = new ms_editor('content');
$editor->upimage = TRUE;
$editor->height = '400px';
$editor->content = $content['content'];
$edit_html = $editor->create_html();
$tplname = 'party_content';
$admin->tplname = cptpl('party_content', MOD_FLAG);
}
break;
case 'checkup':
$PARTY->checkup($_POST['partyids']);
redirect('global_op_succeed', get_forward(cpurl($module,$act)));
break;
case 'checklist':
$where = array();
if(!$admin->is_founder) $where['city_id'] = $_CITY['aid'];
list($total,$list,$multipage) = $PARTY->checklist($where);
$admin->tplname = cptpl('party_check', MOD_FLAG);
break;
default:
$op = 'list';
$admin->tplname = cptpl('party_list', MOD_FLAG);
if(isset($_GET['dosubmit'])) {
if(isset($_GET['aid']) && is_numeric($_GET['aid'])) {
$AREA =& $_G['loader']->model('area');
$aids = $AREA->get_sub_aids($_GET['aid']);
unset($AREA);
}
$PARTY->db->from($PARTY->table);
if(!$admin->is_founder) {
$_GET['city_id'] = '';
$PARTY->db->where('city_id',$_CITY['aid']);
} elseif($_GET['city_id']) {
$PARTY->db->where('city_id',$_GET['city_id']);
}
if($_GET['catid']) {
$PARTY->db->where('catid', $_GET['catid']);
}
if(isset($aids)) $PARTY->db->where('aid', $aids);
if($_GET['sid']) $PARTY->db->where('sid', $_GET['sid']);
if($_GET['subject']) $PARTY->db->where_like('subject', '%'.$_GET['subject'].'%');
if($_GET['username']) $PARTY->db->where('username', $_GET['username']);
if($_GET['starttime']) $PARTY->db->where_more('dateline', strtotime($_GET['starttime']));
if($_GET['endtime']) $PARTY->db->where_less('dateline', strtotime($_GET['endtime']));
if($total = $PARTY->db->count()) {
$PARTY->db->sql_roll_back('from,where');
!$_GET['orderby'] && $_GET['orderby'] = 'partyid';
!$_GET['ordersc'] && $_GET['ordersc'] = 'ASC';
$PARTY->db->order_by($_GET['orderby'], $_GET['ordersc']);
$PARTY->db->limit(get_start($_GET['page'], $_GET['offset']), $_GET['offset']);
$PARTY->db->select('partyid,city_id,aid,catid,finer,thumb,subject,uid,username,address,num,flag,joinendtime,begintime,endtime');
$list = $PARTY->db->get();
$multipage = multi($total, $_GET['offset'], $_GET['page'], cpurl($module,$act,'list',$_GET));
}
}
}
/*
load_class('mod_party', MOD_FLAG);
$modp = new mod_party();
switch($op) {
case 'delete':
if($dosubmit) {
$partyids = $partyids;
$modp->delete($partyids);
cpmsg('操作完毕!', "admincp.php?action=$action&file=$file&op=view");
} else {
cpmsg('未知的提交行为。');
}
break;
case 'checkup':
if(empty($partyids)) cpmsg('未选择操作项,请返回选择。');
$modp->checkup($partyids, 1);
cpmsg('操作完成!',"admincp.php?action=$action&file=$file&op=view");
break;
case 'edit':
if($dosubmit) {
$post = array();
foreach($modp->field as $key) {
if(isset($_POST[$key])) {
$post[$key] = $_POST[$key];
}
}
unset($post['uid'], $post['username']);
if(!$modp->edit($partyid, $post)) {
cpmsg($modp->errmsg);
} else {
$forward = empty($forward) ? "admincp.php?action=$action&file=$file&op=view" : $forward;
cpmsg('操作完成!', $forward);
}
} else {
$party = $modp->read($partyid);
include cptpl('list_edit', MOD_ROOT.'./admin/templates/');
}
break;
default:
$op = 'view';
$where = array();
if($status==='') unset($status);
isset($status) && $where['status'] = (int)$status;
$flag && $where['flag'] = $flag;
$cat && $where['cat'] = $cat;
$offset = 20;
$start = get_start($page, $offset);
list($total, $list) = $modp->find($where, 'dateline DESC', $start, $offset);
if($total) {
$param = create_http_query($where);
$multipage = multi($total, $offset, $page, "admincp.php?action=$action&file=$file&op=$op&".$param);
}
include cptpl('list_view', MOD_ROOT.'./admin/templates/');
}
*/
?>
|
dae8138833c003b2d7dacbbb670f5a7da15435f1
|
[
"JavaScript",
"SQL",
"HTML",
"PHP"
] | 278
|
PHP
|
AaguoTeam/aaguo
|
2efae9e601fdca0e9772816580f3f95dbbd91e54
|
76ccecea75b66c909f6a916c7835e9badfdc479f
|
refs/heads/master
|
<file_sep>from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
import logging
logger = logging.getLogger()
logger.setLevel(logging.CRITICAL)
# create a chatbot
chatbot = ChatBot('N4ruto')
trainer = ChatterBotCorpusTrainer(chatbot)
trainer.train("chatterbot.corpus.english")
while True:
query = str(input(">> "))
print(chatbot.get_response(query))
if "exit" in query:
break
|
f2d4912f97e9fe45fa7bc709ce71e60c66f5f41a
|
[
"Python"
] | 1
|
Python
|
JeevanNaikOP/simple_Chatbot
|
1d7a8ea3a5aeb14f325d4a88654a2f807bdfc556
|
a4cf022b456a9c80606b1d25c5859bbe6fa09821
|
refs/heads/main
|
<repo_name>SaulFernand0/GenerarReporteXML<file_sep>/index.php
<?php
function call($f_i, $f_f, $cliente){
require "conexion.php";
$resp = mysqli_query($conex, "select * from cliente c join venta v on (c.idcliente = v.idcliente) join detalle d on (d.idventa = v.idventa) join producto p on (p.idproducto = d.idproducto) where c.idcliente = 1 and v.fecha between '$f_i' and '$f_f' and c.idcliente = '$cliente'");
if($resp){
$xml = new DOMDocument("1.0");
$xml->formatOutput = true;
$fitness = $xml->createElement("clientes");
$xml-> appendChild($fitness);
while($row = mysqli_fetch_array($resp)){
$cliente=$xml->createElement("cliente");
$fitness->appendChild($cliente);
$idcliente = $xml->createElement("idcliente", $row['idcliente']);
$cliente->appendChild($idcliente);
$nombres = $xml->createElement("nombres", $row['nombres']);
$cliente->appendChild($nombres);
$apellidos = $xml->createElement("apellidos", $row['apellidos']);
$cliente->appendChild($apellidos);
$dni = $xml->createElement("dni", $row['dni']);
$cliente->appendChild($dni);
$direccion = $xml->createElement("direccion", $row['direccion']);
$cliente->appendChild($direccion);
}
echo "<xmp>".$xml->saveXML()."</xmp>";
$xml->save("report.xml");
}else{
echo "error..!";
}
}
?><file_sep>/home.php
<?php
require "index.php";
if(isset($_GET['submit'])){
$fecha_inicio = $_GET['f_i'];
$fecha_final = $_GET['f_f'];
$client = $_GET['cliente'];
call($fecha_inicio, $fecha_final, $client);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ventas</title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top: 50px">
<form>
<div class="row row-cols-4">
<div class="col col-lg-2">
<input class="form-control" type="date" name="f_i">
</div>
<div class="col col-lg-2">
<input class="form-control" type="date" name="f_f">
</div>
<div class="col">
<select class="form-select" aria-label="Default select example" name="cliente">
<option selected>Clientes</option>
<?php
require "conexion.php";
$respuesta = mysqli_query($conex, "select * from cliente");
while($row=$respuesta->fetch_assoc()){
echo "<option value='{$row['idcliente']}'>{$row['nombres']}</option>";
}
?>
</select>
</div>
</div>
<div class="row" style="margin-top: 10px;">
<div class="col">
<button type="submit" name="submit" class="btn btn-primary" style="width: 745px;">Generar Reporte</button>
</div>
</div>
</form>
</div>
</div>
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
</body>
</html>
|
8f0e9e0383b56b41b202f7c34f807eb929ac400d
|
[
"PHP"
] | 2
|
PHP
|
SaulFernand0/GenerarReporteXML
|
c9b6d2ccb93d8ef26a391c175f45d237660e9949
|
dc53f3e6bfd7af13f59c8677d5319ac0e87e9d71
|
refs/heads/master
|
<file_sep><?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
class LearningController extends AbstractController
{
private $name;
/**
* @Route("/", name="learning")
*/
public function aboutMe()
{
return $this->render('learning/index.html.twig', [
'controller_name' => 'LearningController',
]);
}
public function showMyName(){
if (!isset($_POST['name'])){
$_POST ['name'] = 'there! Angel of my nightmare 😇';
}
return $this->render('learning/showMyName.html.twig', [
'controller_name' => 'LearningController', "name" => $_POST ['name']
]);
}
private function name() {
return $this->name;
}
public function changeMyName() {
if (!isset($_POST['name'])) {
$_POST['name']= "undefined";
}
$this->name = $_POST['name'];
return $this->render('learning/changeMyName.html.twig', [
'controller_name' => 'LearningController',
'name' => $this->name()
]);
}
}
|
aa1a98e2b1f6d447505af8b997d07abf1c49db6b
|
[
"PHP"
] | 1
|
PHP
|
grgdhiraj/symfony-mvc-routing
|
412a3beec8b0a0a37e85ce63a6e30f09f806323d
|
43f508f8ef5b6a2722b2e2b51ae4a7228b1f64db
|
refs/heads/master
|
<repo_name>etsangsplk/drone-gc<file_sep>/gc/cache/listener_test.go
// Copyright 2019 Drone.IO Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file.
package cache
|
d2080745563dfeb1018c0e015375ac0e8d7e12cd
|
[
"Go"
] | 1
|
Go
|
etsangsplk/drone-gc
|
93752ce7050469a0d0334c06382b7dbbfb8c198c
|
fed20359d4968ed357e8fc74dcff2a9a1785ac00
|
refs/heads/master
|
<file_sep>import React from 'react';
import truncate from '../util/truncate';
/* Props:
* @albumInfo: object
*/
export default (props) => {
// get AlbumOverlay data
const itunesUrl = 'https://www.apple.com/itunes/download/';
const {
artistName,
collectionName,
collectionPrice,
artistViewUrl,
collectionViewUrl
} = props.albumInfo;
return (
<div className={ props.show ? "overlay overlay--active" : "overlay" }>
<div className="overlay__stub">
<a className="overlay__title"
href={ collectionViewUrl } target="_blank">
<h3>{ truncate(collectionName, 30) }</h3>
</a>
<a className="overlay__artist"
href={ artistViewUrl } target="_blank">
<h3>{ truncate(artistName, 18) }</h3>
</a>
</div>
<ul>
<li className="overlay__list-item">
<i className="fa fa-music"></i>
<a className="overlay__link" href={ collectionViewUrl } target="_blank">
View Album
</a>
</li>
<li className="overlay__list-item">
<i className="fa fa-user"></i>
<a className="overlay__link" href={ artistViewUrl } target="_blank">
Artist Page
</a>
</li>
<li className="overlay__list-item">
<i className="fa fa-download"></i>
<a className="overlay__link" href={ itunesUrl } target="_blank">
Get iTunes
</a>
</li>
<li className="overlay__price">
<span>${ collectionPrice }</span>
</li>
</ul>
</div>
);
}
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import Promise from 'core-js/es6/promise';
import assign from 'core-js/fn/object/assign';
import fetch from 'whatwg-fetch';
import './styles/main.scss';
// render app
ReactDOM.render(
<App />,
document.getElementById('app')
);<file_sep>import React from 'react';
import Album from './Album';
/* Props:
* @query: string
* @albums: array
* @count: number
*/
export default (props) => {
// build Album components
const albumsList = props.albums.map((album, index) =>
<Album key={ index } albumInfo={ album } />
);
// build message
const getMessage = () => {
let message;
if (props.query === '')
message = 'Please enter an artist name to search.';
else if (props.count === 0)
message = `No results found for ${ props.query }`;
else
message = `Results 1 - ${ props.count } for "${ props.query }"`;
return message;
}
return (
<div id="albums-container" className="catalog">
<h2 className="catalog__message">{ getMessage() }</h2>
<div className="l-row">
{ (props.albums.length) ? albumsList : null }
</div>
</div>
);
}<file_sep># ArtistSearch
Code Challenge: React iTunes API album search catalog.
## Requirements
1. Create a github Repo or Click 'Fork' from the top menu and generate your own link.
2. Create a Search Component for entering an Artist.
3. On Search, make an API call to iTunes API to fetch information about the artist.
`API URL: https://itunes.apple.com/search?term=${ARTIST_NAME}`
4. When the Search button is clicked, make a call to the API and display the list of albums, including the album name and album cover inside #albums-container in a grid. Use any CSS technique you are comfortable with (Note: The API will return a list of albums based on the search result. Use your skills to find out what the iTunes API data structure looks like and extract the relevant data from it).
5. Style the page to the best of your ability to make the UI look clean and presentable.
6. Check-in your example.
## Installation
In project root run
`$ npm install`
## Development
`npm run start`
## Production
`npm run build`
<file_sep>import React from 'react';
import truncate from '../util/truncate';
import AlbumOverlay from './AlbumOverlay';
/* Props:
* @albumInfo: object
*/
export default class Album extends React.Component {
constructor() {
super();
this.state = { isHover: false };
this.handleHover = this.handleHover.bind(this);
}
handleHover(mouseEvent) {
this.setState(prevState => ({
isHover: !prevState.isHover
}));
}
render() {
// create Album data variables
const {
artistName,
collectionName,
artworkUrl100
} = this.props.albumInfo;
return (
<div className="l-column">
<div className="album"
onMouseEnter={ this.handleHover }
onMouseLeave={ this.handleHover }
onTouchStart={ this.handleHover }>
<img className="album__img" src={ artworkUrl100 } alt={ collectionName }/>
<div className="album__stub">
<p className="album__title">{ truncate(collectionName, 21) }</p>
<p className="album__artist">{ truncate(artistName, 44) }</p>
</div>
<AlbumOverlay albumInfo={ this.props.albumInfo }
show={ this.state.isHover } />
</div>
</div>
);
}
}
<file_sep>/*
* Function for truncating a string
* arguments: string, number
*/
export default (s, n) => {
// if string is less than number, return string
if (s.length <= n)
return s;
// truncate string at last space and add ellipsis
const subString = s.substr(0, n-1);
return subString.substr(0, subString.lastIndexOf(' ')) + '...';
};<file_sep>import React from 'react';
import Search from './Search';
/* Props:
* @submitSearch: function
*/
export default (props) => {
return (
<div className="header">
<h1 className="header__title">
Search for albums by your favorite artists
</h1>
<Search submitSearch={ props.submitSearch } />
</div>
);
}
|
e85655d44db5d212287fa3947ec895ce69fd9fd1
|
[
"JavaScript",
"Markdown"
] | 7
|
JavaScript
|
m-hatch/ArtistSearch
|
6f6b2942ba2de086124a7d93484aaa0ef67f4492
|
3c14f8ac6adc5ae552a0b7eb0e03781632ee4c88
|
refs/heads/master
|
<repo_name>IanMoonee/JavaDesignPatterns<file_sep>/src/patterns/Adapter/CelsiusTemperature.java
package patterns.Adapter;
public class CelsiusTemperature implements Temperature
{
@Override
public void printTemperatureMessage()
{
System.out.println("Temperature in Celsius");
}
}
<file_sep>/src/patterns/Main.java
package patterns;
import patterns.Composite.Department;
import patterns.Composite.FinancialDepartment;
import patterns.Composite.HeadDepartment;
import patterns.Composite.SalesDepartment;
import patterns.Iterator.DistributionBox;
import patterns.Iterator.DistroCollection;
import patterns.factory.TCPConnection;
import patterns.factory.TCPConnectionFactory;
import patterns.proxy.Node;
import patterns.proxy.ProxyNode;
import patterns.singleton.HwConnection;
import patterns.singleton.SingletonEnum;
public class Main {
public static void main(String[] args)
{
// Factory Pattern
TCPConnection tcp_connection = TCPConnectionFactory.getInstance("Unix");
tcp_connection.connect();
// Singleton Pattern
HwConnection hw_connection = HwConnection.getInstance();
// the object below cannot be created because we already have one open connection!
HwConnection hw_connection2 = HwConnection.getInstance();
//Singleton with Enum
SingletonEnum singletonEnum = SingletonEnum.INSTANCE;
// set two values and then print the value(only 1 value is stored at the instance)
singletonEnum.setValue(1);
singletonEnum.setValue(5);
System.out.println(singletonEnum.getValue());
//Proxy pattern
Node node = new ProxyNode(("192.168.1.1"));
node.displayNodeIp();
node.displayNodeIp();
node.displayNodeIp();
//Composite Pattern
Department salesDep = new SalesDepartment(1, "Sales Department");
Department financialDep = new FinancialDepartment(2, "Financial Department");
HeadDepartment headDep = new HeadDepartment(3, "Head Department");
headDep.addDepartment(salesDep);
headDep.addDepartment(financialDep);
headDep.printDepartmentName();
// Iterator pattern
DistroCollection distroCollection = new DistroCollection();
DistributionBox distributionBox = new DistributionBox(distroCollection);
distributionBox.printAllDistros();
}
}
<file_sep>/src/patterns/factory/TCPWindows.java
package patterns.factory;
public class TCPWindows implements TCPConnection
{
// We should override each method of TCPConnection as TCPConnection is the interface!!
@Override
public void connect()
{
System.out.println("Windows tcp connection established.");
}
}
<file_sep>/src/patterns/Iterator/LinuxDistros.java
package patterns.Iterator;
public class LinuxDistros
{
String distroName;
public LinuxDistros(String distroName)
{
this.distroName = distroName;
}
public String getDistroName()
{
return distroName;
}
}
<file_sep>/src/patterns/Iterator/DistroIterator.java
package patterns.Iterator;
public class DistroIterator implements CustomIterator {
LinuxDistros[] linuxDistroList;
int position = 0 ;
public DistroIterator(LinuxDistros[] linuxDistroList)
{
this.linuxDistroList = linuxDistroList;
}
@Override
public boolean hasNext() {
if (position >= linuxDistroList.length || linuxDistroList[position] == null)
{
return false;
}
else
return true;
}
@Override
public Object next()
{
LinuxDistros linuxDistros = linuxDistroList[position];
position += 1;
return linuxDistros;
}
}
|
2e14cf377dac4444fc975c5d95d504b66c69d446
|
[
"Java"
] | 5
|
Java
|
IanMoonee/JavaDesignPatterns
|
1b765538af280c6f932a0da018111ceb8e2d2c9a
|
0f0417b4b51550b9420075ea33fd55fcfdfeccf3
|
refs/heads/master
|
<repo_name>KMenz/Mars-Web-Scraping<file_sep>/README.md
# Mars-Web-Scraping<file_sep>/scrape_mars.py
#import dependencies
from bs4 import BeautifulSoup as bs
from splinter import Browser
import os
import pandas as pd
import time
from selenium import webdriver
def scrape():
executable_path = {"executable_path":"chromedriver.exe"}
browser = Browser("chrome", **executable_path, headless = False)
mars_facts_data = {}
url = "https://mars.nasa.gov/news/"
browser.visit(url)
html = browser.html
soup = bs(html, "html.parser")
#scrapping latest news about mars from nasa
news_title = soup.find("div", class_="content_title").text
news_description = soup.find("div", class_="article_teaser_body").text
mars_facts_data['news_title'] = news_title
mars_facts_data['news_paragraph'] = news_description
#Mars Featured Image
image_url = "https://www.jpl.nasa.gov/spaceimages/?search=&category=featured#submit"
browser.visit(image_url)
#get image url using BeautifulSoup
html_image = browser.html
soup = bs(html_image, "html.parser")
image_url = soup.find('a', class_ = "button fancybox")['data-fancybox-href']
base_url = 'https://www.jpl.nasa.gov/'
full_img_url = base_url + image_url
mars_facts_data["featured_image"] = full_img_url
# #### Mars Weather
#get mars weather's latest tweet from the website
weather_url = "https://twitter.com/marswxreport?lang=en"
browser.visit(weather_url)
html_weather = browser.html
soup = bs(html_weather, "html.parser")
mars_weather = soup.find(
'div', class_='js-tweet-text-container').text.strip()
mars_facts_data["mars_weather"] = mars_weather
# #### Mars Facts
url_facts = "https://space-facts.com/mars/"
table = pd.read_html(url_facts)
table[0]
facts_df = table[0]
facts_df.columns = ["Parameter", "Values"]
clean_table = facts_df.set_index(["Parameter"])
mars_html_table = clean_table.to_html()
mars_html_table = mars_html_table.replace("\n", "")
mars_facts_data["mars_facts_table"] = mars_html_table
# #### <NAME>
hemi_url = "https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars"
browser.visit(hemi_url)
#Getting the base url
hemi_base_url = 'https://astrogeology.usgs.gov/'
hemisphere_img_urls = []
hemisphere_img_urls
# #### Cerberus-Hemisphere-image-url
hemisphere_img_urls = []
results = browser.find_by_xpath(
"//*[@id='product-section']/div[2]/div[1]/a/img").first.click()
cerberus_open = browser.find_by_xpath("//*[@id='wide-image-toggle']").first.click()
cerberus_image = browser.html
soup = bs(cerberus_image, "html.parser")
cerberus_url = soup.find("img", class_="wide-image")["src"]
complete_cerberus = hemi_base_url + cerberus_url
cerberus_title = soup.find("h2", class_="title").text
cerberus = {'url': complete_cerberus, 'title': cerberus_title}
hemisphere_img_urls.append(cerberus)
#Go Back To Homescreen
back = browser.find_by_xpath(
"//*[@id='splashy']/div[1]/div[1]/div[3]/section/a").first.click()
# #### Schiaparelli-Hemisphere-image-url
results = browser.find_by_xpath(
"//*[@id='product-section']/div[2]/div[2]/a/img").first.click()
schiaparelli_open = browser.find_by_xpath("//*[@id='wide-image-toggle']").first.click()
schiaparelli_image = browser.html
soup = bs(schiaparelli_image, 'html.parser')
schiaparelli_url = soup.find('img', class_='wide-image')['src']
complete_schiaparelli = hemi_base_url + schiaparelli_url
schiaparelli_title = soup.find('h2', class_='title').text
schiaparelli = {'url': complete_schiaparelli, 'title': schiaparelli_title}
hemisphere_img_urls.append(schiaparelli)
#Go Back To Homescreen
back = browser.find_by_xpath(
"//*[@id='splashy']/div[1]/div[1]/div[3]/section/a").first.click()
# #### Syrtis Major Hemisphere
results = browser.find_by_xpath(
"//*[@id='product-section']/div[2]/div[3]/a/img").first.click()
syrtis_open = browser.find_by_xpath("//*[@id='wide-image-toggle']").first.click()
syrtis_image = browser.html
soup = bs(syrtis_image, 'html.parser')
syrtis_url = soup.find('img', class_='wide-image')['src']
complete_syrtis = hemi_base_url + syrtis_url
syrtis_title = soup.find('h2', class_='title').text
syrtis = {'url': complete_syrtis, 'title': syrtis_title}
hemisphere_img_urls.append(syrtis)
#Go Back To Homescreen
back = browser.find_by_xpath(
"//*[@id='splashy']/div[1]/div[1]/div[3]/section/a").first.click()
# #### Valles Marineris Hemisphere
results = browser.find_by_xpath(
"//*[@id='product-section']/div[2]/div[4]/a/img").first.click()
valles_open = browser.find_by_xpath("//*[@id='wide-image-toggle']").first.click()
valles_image = browser.html
soup = bs(valles_image, 'html.parser')
valles_url = soup.find('img', class_='wide-image')['src']
complete_valles = hemi_base_url + valles_url
valles_title = soup.find('h2', class_='title').text
valles = {'url': complete_valles, 'title': valles_title}
hemisphere_img_urls.append(valles)
#Go Back To Homescreen
back = browser.find_by_xpath(
"//*[@id='splashy']/div[1]/div[1]/div[3]/section/a").first.click()
mars_facts_data["hemisphere_img_url"] = hemisphere_img_urls
|
b348e0c27eb326f27552da1f35084c4f4b5ad030
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
KMenz/Mars-Web-Scraping
|
6df33da0509bd4c1ff8bbe55e7df8a8859c40ff2
|
98eb572418d8dd07a89b0bb94f9d4a5ba18a76dd
|
refs/heads/master
|
<repo_name>chaiyuan04/Get-Clean-Data-Project<file_sep>/run_analysis.R
#Course Project
setwd("C:/Users/chaix026/Dropbox/R/Getting Data and Data Clearning/quiz/Get-Clean-Data-Project")
ProjectUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
download.file(ProjectUrl, destfile="./data/ProjectData.zip")
unzip("./data/Get-Clean-Data-Project/ProjectData.zip", exdir="./data")
features <- read.table("./data/UCI HAR Dataset/features.txt")
head(features)
tail(features)
activity_labels <- read.table("./data/UCI HAR Dataset/activity_labels.txt")
activity_labels
#Training Data
X_train <- read.table("./data/UCI HAR Dataset/train/X_train.txt")
colnames(X_train) <- features[,2]
head(X_train)
Y_train <- read.table("./data/UCI HAR Dataset/train/Y_train.txt")
colnames(Y_train) <- "ActivityLabel"
summary(Y_train)
subject_train <- read.table("./data/UCI HAR Dataset/train/subject_train.txt")
colnames(subject_train) <- "VolunteerID"
head(subject_train)
table(subject_train)
trainData <- cbind(subject_train, Y_train, X_train)
head(trainData)
#Test
X_test <- read.table("./data/UCI HAR Dataset/test/X_test.txt")
colnames(X_test) <- features[,2]
head(X_test)
Y_test <- read.table("./data/UCI HAR Dataset/test/Y_test.txt")
colnames(Y_test) <- "ActivityLabel"
summary(Y_test)
subject_test <- read.table("./data/UCI HAR Dataset/test/subject_test.txt")
colnames(subject_test) <- "VolunteerID"
head(subject_test)
table(subject_test)
testData <- cbind(subject_test, Y_test, X_test)
head(testData)
#MergeData
MergeData <- rbind(trainData, testData)
head(MergeData)
#Extrats only the mean and std
library(stringr)
#Colnames having "mean" or "std"
MeanStdCol <- grepl("mean|std", colnames(MergeData))
#Selction: include the first two columns "ID" and "Activitiy", as well as only "mean" and "std" cols
SelCol <- MeanStdCol
SelCol[c(1,2)] <- c(TRUE, TRUE)
MergeDataSel <- MergeData[, SelCol]
#Rename Activity Labels
MergeDataSel[,2] <- as.factor(MergeDataSel[,2])
levels(MergeDataSel[,2]) <- activity_labels[,2]
#New data set of average
library(data.table)
DT <- as.data.table(MergeDataSel)
DT <- DT[order(VolunteerID, ActivityLabel)]
DT <- DT[, lapply(.SD, mean), by=list(VolunteerID, ActivityLabel)]
#Write the tidy data set as txt file
write.table(DT, file="./data/TidyData.txt", row.names=FALSE)
|
d9f33eff673b3cbe7f39991deadb317273b4e0aa
|
[
"R"
] | 1
|
R
|
chaiyuan04/Get-Clean-Data-Project
|
7a0dcbf90b02405534f2a340cdd3c6adf4237202
|
f84f7048a0bb5f18c39da4dffc3e8e453e42b3e1
|
refs/heads/main
|
<file_sep>def square_footage(length,width):
print(f"length: {length}, width: {width}")
length = int(length)
width = int(width)
area = length * width
print(f"Your square footage of your house is: ", area)
def circumference(diameter):
print(f"diameter: {diameter}")
diameter = int(diameter)
circumference = diameter | 3.14
print(f"Your circumference of your circle is: ", circumference)
|
c9a718d04f660608313eafdc64a1270e5fd56c60
|
[
"Python"
] | 1
|
Python
|
nbnulton/Week2Day3Homework
|
61e39d25b58a0826c25e446e0f3136010d719599
|
8fa24d54322b03b808f3df831c6c71908e5d36a1
|
refs/heads/master
|
<repo_name>alparf/ITAcademyJEE<file_sep>/app/src/main/java/by/academy/service/impl/SalaryService.java
package by.academy.service.impl;
import by.academy.model.bean.Salary;
import by.academy.repository.IRepository;
import by.academy.repository.impl.SalaryRepositoryDB;
import by.academy.service.ISalaryService;
import by.academy.specification.impl.SalaryByCoachIdSpecification;
import java.util.List;
public class SalaryService implements ISalaryService {
@Override
public boolean addSalary(Salary salary) {
return new SalaryRepositoryDB().add(salary);
}
@Override
public List<Salary> getAllByCoachId(long coachId) {
IRepository<Salary> repository = new SalaryRepositoryDB();
List<Salary> salaries = repository.query(new SalaryByCoachIdSpecification(coachId));
return salaries;
}
}
<file_sep>/app/src/main/java/by/academy/connection/ConnectionManager.java
package by.academy.connection;
import by.academy.exception.AppException;
import org.postgresql.ds.PGConnectionPoolDataSource;
import javax.sql.PooledConnection;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;
public final class ConnectionManager {
private static final int DEFAULT_TIME_OUT = 60_000;
private static final String URL = "url";
private static final String USER = "user";
private static final String PASSWORD = "<PASSWORD>";
private static final String CONNECTION_TIME_OUT = "connection.time.out";
private static final String PROPERTIES_FILE_NAME = "connection.prop";
private static volatile PooledConnection pooledConnection;
public static PooledConnection getConnectionPool() {
PooledConnection connection = pooledConnection;
if (null == connection) {
synchronized (ConnectionManager.class) {
connection = pooledConnection;
if (null == connection) {
Properties properties = loadProps(PROPERTIES_FILE_NAME);
PGConnectionPoolDataSource dataSource = new PGConnectionPoolDataSource();
dataSource.setURL(properties.getProperty(URL));
dataSource.setUser(properties.getProperty(USER));
dataSource.setPassword(properties.getProperty(PASSWORD));
try {
dataSource.setConnectTimeout(
Integer.parseInt(properties.getProperty(CONNECTION_TIME_OUT)));
} catch (NumberFormatException e) {
dataSource.setConnectTimeout(DEFAULT_TIME_OUT);
}
try {
pooledConnection = dataSource.getPooledConnection();
} catch (SQLException e) {
throw new AppException(e.getMessage());
}
}
}
}
return pooledConnection;
}
private static Properties loadProps(String fileName) {
Properties properties = new Properties();
try {
properties.load(Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
}
return properties;
}
private ConnectionManager () {
}
}
<file_sep>/app/src/main/webapp/resources/js/average.js
window.onload = function() {
document.getElementById("average-btn").addEventListener("click", function() {
console.log(document.getElementById('month-count').value)
let url = "AverageSalaries?monthCount=" + document.getElementById('month-count').value;
fetch(url)
.then((response) => {
return response.json();
})
.then((data) => {
build(data);
});
});
}
function build(data) {
let container = document.getElementById("salaries-container");
let averageSalaryList = "";
for (const [key, value] of Object.entries(data)) {
averageSalaryList += getSalaryInner(key, value);
}
removeAllChildNodes(container);
container.innerHTML = averageSalaryList;
}
function getSalaryInner(name, salary) {
return `
<div class="salary_inner">
<span>${name}</span>
<span>${salary / 100.0} BYN</span>
</div>`
}
function removeAllChildNodes(parent) {
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}<file_sep>/app/src/main/java/by/academy/repository/impl/UserRepositoryDB.java
package by.academy.repository.impl;
import by.academy.connection.ConnectionManager;
import by.academy.constant.SqlQuery;
import by.academy.exception.AppException;
import by.academy.model.bean.User;
import by.academy.model.bean.UserType;
import by.academy.repository.IRepository;
import by.academy.specification.ISpecification;
import by.academy.specification.SqlSpecification;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
public class UserRepositoryDB implements IRepository<User> {
@Override
public boolean add(User user) {
final int FIO = 1;
final int AGE = 2;
final int USER_NAME = 3;
final int PASSWORD = 4;
final int USER_TYPE = 5;
int update = 0;
try {
Connection connection = ConnectionManager.getConnectionPool().getConnection();
try (PreparedStatement statement = connection.prepareStatement(SqlQuery.INSERT_USER)){
if (null != user) {
statement.setString(FIO, user.getFio());
statement.setInt(AGE, user.getAge());
statement.setString(USER_NAME, user.getUserName());
statement.setString(PASSWORD, user.getPassword());
statement.setString(USER_TYPE, user.getUserType().getName());
update = statement.executeUpdate();
}
}
} catch (SQLException e) {
throw new AppException(e);
}
return update > 0;
}
@Override
public boolean remove(User user) {
final int ID = 1;
int update = 0;
try {
Connection connection = ConnectionManager.getConnectionPool().getConnection();
try (PreparedStatement statement = connection.prepareStatement(SqlQuery.DELETE_USER_BY_ID)) {
if (null != user) {
statement.setLong(ID, user.getId());
update = statement.executeUpdate();
}
}
} catch (SQLException e) {
throw new AppException(e);
}
return update > 0;
}
@Override
public boolean set(User user) {
return false;
}
@Override
public List<User> query(ISpecification<User> specification) {
List<User> users = new LinkedList<>();
final int ID = 1;
final int FIO = 2;
final int AGE = 3;
final int USER_NAME = 4;
final int PASSWORD = 5;
final int USER_TYPE = 6;
if (specification instanceof SqlSpecification) {
SqlSpecification sqlSpecification = (SqlSpecification) specification;
try {
Connection connection = ConnectionManager.getConnectionPool().getConnection();
try (PreparedStatement statement = sqlSpecification.getPreparedStatement(connection);
ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
users.add(User.newBuilder()
.withId(resultSet.getLong(ID))
.withFio(resultSet.getString(FIO))
.withAge(resultSet.getInt(AGE))
.withUserName(resultSet.getString(USER_NAME))
.withPassword(resultSet.getString(PASSWORD))
.withUserType(UserType.valueOf(resultSet.getString(USER_TYPE)))
.build());
}
}
} catch (SQLException e) {
throw new AppException(e);
}
}
users.removeIf(specification::isSpecific);
return users;
}
}
<file_sep>/app/src/main/java/by/academy/controller/JsonController.java
package by.academy.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public abstract class JsonController extends HttpServlet {
@SuppressWarnings("unchecked")
protected Map<String, String> getRequestParameters(HttpServletRequest req) {
Map<String, String> props = null;
try (BufferedReader br = req.getReader()) {
StringBuilder body = new StringBuilder();
while (br.ready()) {
body.append(br.readLine());
}
ObjectMapper mapper = new ObjectMapper();
props = mapper.readValue(body.toString(), HashMap.class);
} catch (IOException e) {
e.printStackTrace();
}
return props;
}
}
<file_sep>/app/src/main/java/by/academy/controller/user/admin/AddSalary.java
package by.academy.controller.user.admin;
import by.academy.constant.ExceptionMessage;
import by.academy.constant.PageName;
import by.academy.constant.ServletProperties;
import by.academy.controller.JsonController;
import by.academy.facade.UserFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
@WebServlet("/AddSalary")
public class AddSalary extends JsonController {
private static final Logger log = LoggerFactory.getLogger(AddSalary.class);
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
Map<String, String> props = getRequestParameters(req);
if (null != props) {
long coachId = Long.parseLong(props.get(ServletProperties.COACH_ID), 10);
double salary = Double.parseDouble(props.get(ServletProperties.SALARY));
UserFacade.addSalary(coachId, salaryFormat(salary));
log.info("Add salary = {} to Coach(" + coachId + ")", salary);
}
} catch (NumberFormatException e) {
log.error(e.getMessage(), e);
req.getSession().setAttribute(
ServletProperties.EXCEPTION_MESSAGE,
ExceptionMessage.VALUE_HAVE_TO_BE_NUMBER);
}
resp.sendRedirect(PageName.HOME);
}
private int salaryFormat(Double salary) {
return (int) (salary * 100);
}
}
<file_sep>/app/src/main/java/by/academy/controller/user/Login.java
package by.academy.controller.user;
import by.academy.constant.ExceptionMessage;
import by.academy.constant.PageName;
import by.academy.constant.ServletProperties;
import by.academy.facade.UserFacade;
import by.academy.model.bean.User;
import by.academy.model.bean.UserType;
import by.academy.exception.UserServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;
public class Login extends HttpServlet {
private static final Logger log = LoggerFactory.getLogger(Login.class);
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
String userName = req.getParameter(ServletProperties.USER_NAME);
String password = req.getParameter(ServletProperties.PASSWORD);
HttpSession session = req.getSession();
session.setAttribute(ServletProperties.EXCEPTION_MESSAGE, null);
Optional<User> user = UserFacade.login(userName, password);
if (user.isPresent()) {
session.setAttribute(ServletProperties.USER, user.get());
log.info("User = {} signed in", userName);
} else {
log.info("User = {} not found!", userName);
session.setAttribute(
ServletProperties.EXCEPTION_MESSAGE,
ExceptionMessage.INVALID_USER_NAME_OR_PASSWORD);
}
res.sendRedirect(PageName.HOME);
}
@Override
public void init() {
final String ADMIN_NAME = "adminName";
final String ADMIN_PASSWORD = "<PASSWORD>";
String adminName = getServletConfig().getInitParameter(ADMIN_NAME);
String adminPassword = getServletConfig().getInitParameter(ADMIN_PASSWORD);
User admin = User.newBuilder()
.withFio("<NAME>")
.withAge(34)
.withUserName(adminName)
.withPassword(<PASSWORD>)
.withUserType(UserType.ADMIN)
.build();
try {
UserFacade.addUser(admin);
} catch (UserServiceException e) {
e.printStackTrace();
}
}
}
<file_sep>/model/src/main/java/by/academy/model/constant/ExceptionMessage.java
package by.academy.model.constant;
public class ExceptionMessage {
public static final String INVALID_AGE_VALUE = "Invalid age value!";
public static final String USER_HAVE_TO_BE_COACH = "User have to be coach!";
public static final String INVALID_MONTH_COUNT = "Invalid month count!";
}
<file_sep>/model/src/test/java/by/academy/model/bean/UserTest.java
package by.academy.model.bean;
import by.academy.model.constant.ExceptionMessage;
import junit.framework.TestCase;
import org.junit.Assert;
import org.junit.Test;
public class UserTest extends TestCase {
@Test
public void testSetAge() throws IllegalArgumentException {
User user = User.newBuilder().build();
int age = -1;
try {
user.setAge(age);
Assert.fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException exception) {
assertEquals(exception.getMessage(), ExceptionMessage.INVALID_AGE_VALUE);
}
}
}<file_sep>/app/src/main/java/by/academy/filter/JsonFilter.java
package by.academy.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(urlPatterns = {"/AverageSalaries", "/UserList", "/CoachList"})
public class JsonFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
servletRequest.setCharacterEncoding("UTF-8");
servletResponse.setContentType("text/json");
chain.doFilter(servletRequest, servletResponse);
}
}
<file_sep>/app/src/main/java/by/academy/specification/impl/UserByIdSpecification.java
package by.academy.specification.impl;
import by.academy.constant.SqlQuery;
import by.academy.model.bean.User;
import by.academy.specification.ISpecification;
import by.academy.specification.SqlSpecification;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class UserByIdSpecification implements ISpecification<User>, SqlSpecification {
private final long userId;
public UserByIdSpecification(long userId) {
this.userId = userId;
}
@Override
public PreparedStatement getPreparedStatement(Connection connection) throws SQLException {
final int USER_ID = 1;
PreparedStatement preparedStatement;
preparedStatement = connection.prepareStatement(SqlQuery.SELECT_USER_BY_ID);
preparedStatement.setLong(USER_ID, this.userId);
return preparedStatement;
}
@Override
public boolean isSpecific(User user) {
return false;
}
}
<file_sep>/app/src/main/java/by/academy/repository/impl/SalaryRepositoryDB.java
package by.academy.repository.impl;
import by.academy.constant.SqlQuery;
import by.academy.exception.AppException;
import by.academy.model.bean.Salary;
import by.academy.connection.ConnectionManager;
import by.academy.repository.IRepository;
import by.academy.specification.ISpecification;
import by.academy.specification.SqlSpecification;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
public class SalaryRepositoryDB implements IRepository<Salary> {
@Override
public boolean add(Salary salary) {
int update = 0;
final int COACH = 1;
final int VALUE = 2;
try {
Connection connection = ConnectionManager.getConnectionPool().getConnection();
try (PreparedStatement statement = connection.prepareStatement(SqlQuery.INSERT_SALARY)) {
if ((null != salary) && (null != salary.getCoach())) {
statement.setLong(COACH, salary.getCoach().getId());
statement.setInt(VALUE, salary.getValue());
update = statement.executeUpdate();
}
}
} catch (SQLException e) {
throw new AppException(e);
}
return update > 0;
}
@Override
public boolean remove(Salary salary) {
return false;
}
@Override
public boolean set(Salary salary) {
return false;
}
@Override
public List<Salary> query(ISpecification<Salary> specification) {
final int ID = 1;
final int VALUE = 2;
List<Salary> salaries = new LinkedList<>();
if (specification instanceof SqlSpecification) {
SqlSpecification sqlSpecification = (SqlSpecification) specification;
try {
Connection connection = ConnectionManager.getConnectionPool().getConnection();
try (PreparedStatement statement = sqlSpecification.getPreparedStatement(connection);
ResultSet resultSet = statement.executeQuery()) {
while (resultSet.next()) {
salaries.add(Salary.newBuilder()
.withId(resultSet.getLong(ID))
.withValue(resultSet.getInt(VALUE))
.build());
}
}
} catch (SQLException e) {
throw new AppException(e);
}
}
salaries.removeIf(specification::isSpecific);
return salaries;
}
}
<file_sep>/app/src/main/java/by/academy/filter/AdminFilter.java
package by.academy.filter;
import by.academy.constant.PageName;
import by.academy.constant.ServletProperties;
import by.academy.model.bean.User;
import by.academy.model.bean.UserType;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;
@WebFilter(urlPatterns = {"/UserController", "/AddSalary" , "/UserList", "/CoachList"})
public class AdminFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpSession session = ((HttpServletRequest) request).getSession();
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
User user;
if ((null != session) && (Objects.nonNull(user = (User) session.getAttribute(ServletProperties.USER)))) {
if (user.getUserType() == UserType.ADMIN) {
chain.doFilter(request, response);
} else {
httpServletResponse.sendRedirect(PageName.HOME);
}
} else {
httpServletResponse.sendRedirect(PageName.LOGIN);
}
}
}
<file_sep>/app/src/main/java/by/academy/specification/impl/UserLoginSpecification.java
package by.academy.specification.impl;
import by.academy.constant.SqlQuery;
import by.academy.model.bean.User;
import by.academy.specification.ISpecification;
import by.academy.specification.SqlSpecification;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class UserLoginSpecification implements ISpecification<User>, SqlSpecification {
private final String userName;
private final String password;
public UserLoginSpecification(String userName, String password) {
this.userName = userName;
this.password = password;
}
@Override
public PreparedStatement getPreparedStatement(Connection connection) throws SQLException {
final int USER_NAME = 1;
PreparedStatement preparedStatement = connection.prepareStatement(SqlQuery.SELECT_USER_BY_USER_NAME);
preparedStatement.setString(USER_NAME, this.userName);
return preparedStatement;
}
@Override
public boolean isSpecific(User user) {
if ((null != user) && (null != this.password)) {
return !((user.getUserName().equals(this.userName)) && (this.password.equals(user.getPassword())));
}
return true;
}
}
<file_sep>/app/src/main/java/by/academy/constant/SqlQuery.java
package by.academy.constant;
public final class SqlQuery {
public static final String INSERT_USER = "INSERT INTO users (\"fio\", \"age\", \"userName\", \"password\", \"userType\") " +
"VALUES (?, ?, ?, ?, ?);";
public static final String SELECT_USER_BY_USER_NAME = "SELECT * FROM users " +
"WHERE \"userName\" = ?;";
public static final String SELECT_USER_BY_ID = "SELECT * FROM users " +
"WHERE \"id\" = ?;";
public static final String DELETE_USER_BY_ID = "DELETE FROM users " +
"WHERE \"id\" = ?;";
public static final String SELECT_USERS = "SELECT * FROM users;";
public static final String INSERT_SALARY = "INSERT INTO salaries (\"userId\", \"salary\") " +
"VALUES (?, ?)";
public static final String SELECT_SALARY = "SELECT \"id\", \"salary\" FROM salaries " +
"WHERE \"userId\" = ?;";
private SqlQuery() {
}
}
<file_sep>/app/src/main/java/by/academy/specification/impl/SalaryByCoachIdSpecification.java
package by.academy.specification.impl;
import by.academy.constant.SqlQuery;
import by.academy.model.bean.Salary;
import by.academy.specification.ISpecification;
import by.academy.specification.SqlSpecification;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class SalaryByCoachIdSpecification implements ISpecification<Salary>, SqlSpecification {
private final long coachId;
public SalaryByCoachIdSpecification(long coachId) {
this.coachId = coachId;
}
@Override
public PreparedStatement getPreparedStatement(Connection connection) throws SQLException {
final int COACH_ID = 1;
PreparedStatement preparedStatement = connection.prepareStatement(SqlQuery.SELECT_SALARY);
preparedStatement.setLong(COACH_ID, coachId);
return preparedStatement;
}
@Override
public boolean isSpecific(Salary salary) {
return false;
}
}
|
a9eaa157b40d3b34c65d6a930cab63f30d10d5e5
|
[
"JavaScript",
"Java"
] | 16
|
Java
|
alparf/ITAcademyJEE
|
e5ffe37d08e7812ab69292ba6fbb6a3d32c7dfdf
|
df1a1c62cbe2c54b51acbe5fa2f8d47514ee66f3
|
refs/heads/main
|
<repo_name>Perry5216/Ticketing-System<file_sep>/user.h
#ifndef UNTITLED_USER_H
#define UNTITLED_USER_H
#endif //UNTITLED_USER_H
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class user
{
public:
user();
~user();
void getLogin();
void getProfileInfo(string &fName, string &sName, string &address);
protected:
string fName;
string sName;
string address;
};
user::user()
{
fName = "";
sName = "";
address = "";
}
user::~user() {}
void user::getLogin()
{
string username;
string password;
std::cout
<< "\n---------- Welcome to the Bucks Centre for the Performing Arts Ticket Purchasing System! ----------\n"
<< std::endl;
std::cout << " Please log in. \n"
<< std::endl;
std::cout << "Enter username: ";
getline(cin, username);
while (username.length() > 10)
{
std::cout << "Your username should be no more than 10 characters long." << std::endl;
std::cout << "Please re-enter your usename: ";
getline(cin, username);
}
std::cout << "Enter password: ";
getline(cin, password);
while (password.length() > 10)
{
std::cout << "Your password should be no more than 10 characters long." << std::endl;
std::cout << "Please re-enter your password: ";
getline(cin, password);
}
}
void user::getProfileInfo(string &fName, string &sName, string &address)
{
std::cout << "\n---------- CREATE USER ACCOUNT ----------" << std::endl;
std::cout << "\n You are a new user. Please enter your details to create a new account." << std::endl;
std::cout << "\nPlease enter your first name: ";
getline(cin, fName);
std::cout << "Please enter your surname: ";
getline(cin, sName);
std::cout << "Please enter your address: ";
getline(cin, address);
std::cout << "\nHello " + fName + " " + sName + " from " + address + ".\n";
};<file_sep>/customer.h
#ifndef UNTITLED_CUSTOMER_H
#define UNTITLED_CUSTOMER_H
#endif //UNTITLED_CUSTOMER_H
#include <iostream>
#include <iomanip>
#include <string>
#include "user.h"
using namespace std;
class customer : public user
{
public:
void getPaymentInfo();
protected:
string fName;
string sName;
string address;
};
void customer::getPaymentInfo()
{
string cardNumber;
std::cout << "\n---------- PLEASE ENTER YOUR PAYMENT DETAILS ----------\n"
<< std::endl;
std::cin.clear();
std::cin.ignore(100, '\n');
std::cout << "\nPlease enter your card number: ";
getline(cin, cardNumber);
while (cardNumber.length() != 16)
{
std::cout << "Your card number should be 16 digits long." << std::endl;
std::cout << "Please re-enter your card number: ";
getline(cin, cardNumber);
}
std::cout << "\nThank you for your payment! ";
}<file_sep>/README.md
# Ticketing-System
Year two - OOP project, a console ticketing system
<file_sep>/main.cpp
#include <iostream>
#include <string>
#include "ticket.h"
#include "show.h"
#include "customer.h"
#include "showSeat.h"
using namespace std;
int main()
{
std::string a, b, c, f, g, h;
int d;
int e;
double i;
char ch,
terminator;
showSeat seat;
customer customer;
show show;
ticket *tick;
customer.getLogin();
customer.getProfileInfo(f, g, h);
std::cout << "\n---------- MAIN MENU ----------\n"
<< std::endl;
std::cout << "1. Buy tickets for upcoming shows" << std::endl;
std::cout << "2. Log out\n"
<< std::endl;
std::cout << "Please enter a menu choice number: ";
std::cin.get(ch);
while (ch != '1' && ch != '2')
{
std::cin.clear();
std::cin.ignore(100, '\n');
std::cout << "Please select a valid menu choice number: ";
std::cin.get(ch);
}
if (ch == '2')
{
cout << "Thank you for using the BCPA Ticketing System" << endl;
return EXIT_SUCCESS;
}
do
{
show.selectShow(a, b);
show.selectTime(c);
do
{
std::cin.clear();
std::cout << "\nAre you happy with your choice (Y = Yes, N = No)?: ";
std::cin.get(ch);
} while (ch != 'Y' && ch != 'y' && ch != 'N' && ch != 'n');
} while (ch == 'N' || ch == 'n');
d = seat.getNumSeats();
e = seat.getSeatSelection();
seat.calculatePrice(d);
customer.getPaymentInfo();
}<file_sep>/showSeat.h
#ifndef UNTITLED_SHOWSEAT_H
#define UNTITLED_SHOWSEAT_H
#endif //UNTITLED_SHOWSEAT_H
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
using namespace std;
class showSeat
{
public:
showSeat();
~showSeat();
int getNumSeats();
int getSeatSelection();
char col;
void calculatePrice(int rNum);
protected:
char floorPlan[7][6];
int numSeats;
int rNum;
float price;
};
showSeat::showSeat()
{
for (int r = 0; r < 7; r++)
for (int c = 0; c < 6; c++)
floorPlan[r][c] = '0';
numSeats = 0;
rNum = 0;
price = 1.99;
};
showSeat::~showSeat()
{
}
int showSeat::getNumSeats()
{
std::cout << "\n---------- SELECT SEATS INTERACTIVELY ----------\n";
do
{
std::cin.clear();
std::cin.ignore(100, '\n');
std::cout << "\nHow many tickets would you like to purchase (max. 8)?: ";
std::cin >> numSeats;
} while (numSeats != 1 && numSeats != 2 && numSeats != 3 && numSeats != 4 & numSeats != 5 &&
numSeats != 6 & numSeats != 7 && numSeats != 8);
return numSeats;
}
int showSeat::getSeatSelection()
{
std::string rNumber;
do
{
std::cout << "\nPlease select a row number (1 - 7): ";
std::cin >> rNum;
rNumber = std::to_string(rNum);
} while (rNum < 1 && rNum > 7);
do
{
std::cout << "Please select a column letter (A - F): ";
std::cin.get(col);
} while (col != 'A' && col != 'B' && col != 'C' && col != 'D' && col != 'E' && col != 'F');
std::cout << "\nYou have selected seat: " + rNumber + col << std::endl;
return rNum;
}
void showSeat::calculatePrice(int rNum)
{
if (rNum > 0 && rNum <= 4)
{
price += 20;
}
else if (rNum >= 5)
{
price += 30;
}
price = (price >= 0.0) ? floorf(price + 0.5) : ceilf(price - 0.5);
std::string nPrice;
nPrice = std::to_string(price);
std::cout << fixed << setprecision(2) << "\nYour tickets will cost £" << std::round(price) << ".\n";
}<file_sep>/show.h
#ifndef UNTITLED_SHOW_H
#define UNTITLED_SHOW_H
#endif //UNTITLED_SHOW_H
#include <iostream>
#include <iomanip>
#include <string>
class show
{
public:
show();
~show();
void selectShow(string &showName, string &showDate);
void selectTime(string &showTime);
protected:
string showName;
string showDate;
string showTime;
};
show::show()
{
showName = "";
showDate = "";
showTime = "";
}
show::~show() {}
void show::selectShow(string &showName, string &showDate)
{
char ch;
char terminator;
std::cout << "\n---------- SELECT AN UPCOMING SHOW ----------\n"
<< std::endl;
std::cout << "1. Star Wars: The Musical (20/05/2020)" << std::endl;
std::cout << "2. Les Miserables (21/05/2020)" << std::endl;
std::cout << "3. The Phantom of the Opera (22/05/2020)" << std::endl;
std::cin.clear();
std::cin.ignore(100, '\n');
std::cout << "\nPlease select a show number: ";
std::cin.get(ch);
while (ch != '1' && ch != '2' && ch != '3')
{
std::cin.clear();
std::cin.ignore(100, '\n');
std::cout << "Please select a valid show number: ";
std::cin.get(ch);
std::cin.get(terminator);
}
switch (ch)
{
case '1':
showName = "Star Wars: The Musical", showDate = "20/05/2020";
break;
case '2':
showName = "Les Miserables", showDate = "21/05/2020";
break;
case '3':
showName = "The Phantom of the Opera", showDate = "22/05/2020";
break;
}
this->showName = showName;
this->showDate = showDate;
}
void show::selectTime(string &showTime)
{
char ch;
std::cin.clear();
std::cin.ignore(100, '\n');
std::cout << "\n---------- SELECT A SHOWING -----------" << endl;
std::cout << "1: 2pm" << endl;
std::cout << "2: 5pm" << endl;
std::cout << "\nPlease select a showing number: ";
std::cin.get(ch);
switch (ch)
{
case '1':
showTime = "2pm";
break;
case '2':
showTime = "5pm";
break;
}
cout << "\n~~~~~~~~~~ You have selected " + showName + " on " + showDate + " at " + showTime + " ~~~~~~~~~~" << endl
<< endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Enjoy the show! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl
<< endl;
};<file_sep>/ticket.h
#ifndef UNTITLED_TICKET_H
#define UNTITLED_TICKET_H
#endif //UNTITLED_TICKET_H
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class ticket
{
public:
ticket();
~ticket();
void setPrice(double price);
void printTicket(string showName, string showDate, string showTime, int numSeats, string fName, string sName,
string address);
virtual double cost() = 0;
protected:
double totalCost;
};
ticket::ticket()
{
totalCost = 0;
}
void ticket::setPrice(double price)
{
totalCost = price;
std::cout << "\nThe total price of your tickets (including any applicable discount) is " << (char)156
<< this->cost() << ".\n"
<< std::endl;
system("PAUSE");
}
void ticket::printTicket(string showName, string showDate, string showTime, int numSeats, string fName, string sName,
string address)
{
std::cout << "\n---------- YOUR TICKETS ----------\n"
<< std::endl;
std::cout << "\n--------------------\n"
<< std::endl;
std::cout
<< "\n---------- Welcome to the Bucks Centre for the Performing Arts Ticket Purchasing System! ----------\n"
<< std::endl;
std::cout << "\n---------- Enjoy the show ----------\n"
<< std::endl;
std::cout << "Show: " << showName << std::endl;
std::cout << "Date: " << showDate << std::endl;
std::cout << "Time: " << showTime << std::endl;
std::cout << "\n--------------------\n"
<< std::endl;
std::cout << "Number of seats: " << numSeats << std::endl;
std::cout << "Total cost: " << (char)156 << this->cost() << std::endl;
std::cout << "Ticket purchaser: " << fName << " " << sName << std::endl;
std::cout << "Postal address: " << address << std::endl;
std::cout << "\n--------------------\n"
<< std::endl;
std::cout << "\n--------------------\n"
<< std::endl;
}
|
3100d7c07cb91d0cf29eda179bc3b7af8b943bd6
|
[
"Markdown",
"C++"
] | 7
|
C++
|
Perry5216/Ticketing-System
|
9bbf35e5f3ac9ee84baaf196a03764b02aa2910b
|
0e0a3f2cca92e4901d0f61cdcae78fe8fb48f75d
|
refs/heads/master
|
<file_sep>class PhpBuild < Formula
desc "Builds PHP so that multiple versions can be used side by side"
homepage "https://github.com/php-build/php-build"
# url "https://github.com/madumlao/php-build/archive/osx-zlib.zip"
# sha256 "2a903f4e066299334abbf8e4dad6e50bcd0ce9dc557d4097fd5b651d5b2813d9"
head "https://github.com/madumlao/php-build.git", branch: 'osx-zlib'
bottle :unneeded
depends_on "autoconf"
depends_on "pkg-config"
depends_on "bison"
depends_on "openssl"
depends_on "libxml2"
# optional dependencies - same as php formula
depends_on "curl" => :recommended
depends_on "freetype" => :recommended
depends_on "gettext" => :recommended
depends_on "gmp" => :recommended
depends_on "icu4c" => :recommended
depends_on "jpeg" => :recommended
depends_on "libpng" => :recommended
depends_on "libpq" => :recommended
depends_on "libtool" => :recommended
depends_on "libzip" => :recommended
depends_on "mhash" => :recommended
depends_on "pcre" => :recommended
depends_on "unixodbc" => :recommended
depends_on "webp" => :recommended
def install
ENV["PREFIX"] = prefix
system "./install.sh"
end
test do
assert_match "5.6.38", shell_output("#{bin}/php-build --definitions")
assert_match "7.2.10", shell_output("#{bin}/php-build --definitions")
end
end
<file_sep># phpenv-tap
Homebrew tap for installing [phpenv](https://github.com/phpenv/phpenv), [php-build](https://github.com/php-build/php-build), and related projects.
This tap is under active development, with formulae in beta status.
## How do I install these formulae?
### Installing the tap first
To install the tap without installing any formula, run:
~~~ sh
$ brew tap madumlao/phpenv-tap https://github.com/madumlao/phpenv-tap
~~~
Afterwards, homebrew will be able to install and run related formula:
~~~ sh
$ brew install --HEAD php-build
$ brew install --HEAD phpenv
~~~
<file_sep>class Phpenv < Formula
desc "Simple PHP version management"
homepage "https://github.com/phpenv/phpenv#readme"
head "https://github.com/phpenv/phpenv.git"
depends_on "php-build" => :recommended
def install
if build.head?
# Record exact git revision for `phpenv --version` output
git_revision = `git rev-parse --short HEAD`.chomp
inreplace "libexec/phpenv---version", /^(version=)"([^"]+)"/,
%Q(\\1"\\2-g#{git_revision}")
end
prefix.install ["bin", "completions", "libexec"]
end
test do
shell_output("eval \"$(#{bin}/phpenv init -)\" && phpenv versions")
end
end
|
c5986a9cc60ef3e4150b4c654d3e10d5d0358981
|
[
"Markdown",
"Ruby"
] | 3
|
Ruby
|
madumlao/phpenv-tap
|
260d6c1713634ecaf56a107b1c411094b5e99010
|
cfebf7ba9b6fbd12fe5bbbfb31f4d58575e58df9
|
refs/heads/master
|
<repo_name>FRC-6420/Fire-Island-PowerUp<file_sep>/powerupcode/src/org/usfirst/frc6420/powerupcode/src/org/usfirst/frc6420/powerupcode/Constants.java
package org.usfirst.frc6420.powerupcode;
public class Constants {
/*************************************************
* constants for Autonomous
*************************************************/
public static final double autoForwardTime = 5.0; //sec
public static final double autoForwardSpeed = .25;
public static final double autoForwardSpeed2 = -.25;
public static String gameData = " ";
public static char ourSwitch = ' ';
public static char scale = ' ';
/*************************************************
* constants for drive train and lift/motors
*************************************************/
// drive train motors
//ramp constant changes how fast it speeds up and down, smaller numbers make the ramp up slower.
public static final double rampConstant = .0095;
// zero band changes the size of the zero area on the controller
public static final double zeroBand = 0.3;
// tuning factor changes how fast the robot can go
public static final double tuningFactor = 1;
// arms/grabber motors
public static final double grabberOutSpeed = .7;
public static final double grabberInSpeed = -1;
public static final double grabberNetural = 0;
public static final double timedGabberOutDuration = 2.0;
public static final double timedGabberInDuration = 2.0;
// lift motors
public static final double liftUpSpeed = .75;
public static final double liftdownSpeed = -.15;
}
<file_sep>/README.md
# Fire-Island-PowerUp
|
fa3fd074e6e03922018bf9775e4ec43b45b42653
|
[
"Markdown",
"Java"
] | 2
|
Java
|
FRC-6420/Fire-Island-PowerUp
|
215b319cd1ba073ec5a9bd4a9e2cc2c7b8ada6c8
|
4cc93a3f914a7a880beef55dd3bd9173446facb9
|
refs/heads/master
|
<repo_name>testwangchao/learn-java<file_sep>/src/com/example/annotations/example/TableCreator.java
package com.example.annotations.example;
import com.example.annotations.example.anns.Constraints;
import com.example.annotations.example.anns.DBTable;
import com.example.annotations.example.anns.SQLInteger;
import com.example.annotations.example.anns.SQLString;
import com.example.annotations.example.pojo.Member;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TableCreator {
public static String getConstraints(Constraints constraints){
String constraintsProp = "";
if (!constraints.allowNull()) {
constraintsProp += " NOT NULL";
}
if (constraints.primaryKey()) {
constraintsProp += " PRIMARY KEY";
}
if (constraints.unique()){
constraintsProp += " UNIQUE";
}
return constraintsProp;
}
public static String createTable(String className) throws ClassNotFoundException {
Class<?> clazz = Class.forName(className);
// 获取DBTable注解
DBTable dbTable = clazz.getAnnotation(DBTable.class);
if (dbTable == null) {
System.out.println("No DBTable annotations in class " + className);
return null;
}
// 获取注解dbTable的name属性
String tableName = dbTable.name();
System.out.println(tableName);
if (tableName.equals("")) {
tableName = clazz.getName();
}
List<String> columns = new ArrayList<String>();
// 获取Member所有的成员字段
for(Field field:clazz.getDeclaredFields()){
// 获取所有成员字段的字段注解
Annotation[] fieldAnnotaion = field.getDeclaredAnnotations();
for (Annotation annotation:fieldAnnotaion) {
String columnName;
if (annotation instanceof SQLInteger) {
// 如果获取到的字段的SQLInteger注解的name为"",则取字段的名称
if (((SQLInteger) annotation).name().equals("")){
columnName = field.getName();
} else {
columnName = ((SQLInteger) annotation).name();
}
columns.add(columnName + " INT " + getConstraints(((SQLInteger) annotation).constraint()));
}
if (annotation instanceof SQLString) {
if (((SQLString) annotation).name().equals("")){
columnName = field.getName();
} else {
columnName = ((SQLString) annotation).name();
}
columns.add(columnName + " VARCHAR(" + ((SQLString) annotation).value() + ")" + getConstraints(((SQLString) annotation).constraint()));
}
}
}
System.out.println(columns);
return "123";
}
public static void main(String[] args) throws ClassNotFoundException {
TableCreator.createTable("com.example.annotations.example.pojo.Member");
}
}
<file_sep>/src/com/example/annotations/AnnotationType1.java
package com.example.annotations;
import java.lang.annotation.*;
/**
* ElementType.TYPE:标明该注解可以用于类、接口(包括注解类型)或enum声明
*/
@Inherited // 可以让注解被继承,但这并不是真的继承,只是通过使用@Inherited,可以让子类Class对象使用getAnnotations()获取父类被@Inherited修饰的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationType1 {
String name() default "";
}
|
3aebcc6f67e2a864ec2ceb4d93ba48b10a49fbbc
|
[
"Java"
] | 2
|
Java
|
testwangchao/learn-java
|
f9235bfa618ecc9ce7fabb944ac28a559df73892
|
088373cf01d414f224b8979fca9ad7e86898c34d
|
refs/heads/master
|
<repo_name>humanytek-team/contact_delivery_days<file_sep>/res_partner.py
# -*- coding: utf-8 -*-
from odoo import api, fields, models, _
from openerp import api
class res_partner(models.Model):
_inherit = 'res.partner'
custom_delivery_days = fields.Integer('Dias de trayecto')
|
8abb3b94e165509824e24ea940b955ebd4d64db9
|
[
"Python"
] | 1
|
Python
|
humanytek-team/contact_delivery_days
|
e1d673e3130bd09201d0b584eb3021ce696b71ea
|
cc401ca55fd5492a26d0768dbaf7fae15a728e27
|
refs/heads/master
|
<repo_name>Qcloud1223/exe-loading<file_sep>/src/build-generic.sh
#!/usr/bin/env bash
set -eux
gcc \
-L/home/hypermoon/Qcloud/glibc/build/install/lib \
-I/home/hypermoon/Qcloud/glibc/build/install/include \
-o "$1.exe" \
-g \
-rdynamic \
"$1.c" \
-Wl,-rpath=/home/hypermoon/Qcloud/glibc/build/install/lib \
-Wl,--dynamic-linker=/home/hypermoon/Qcloud/glibc/build/install/lib/ld-linux-x86-64.so.2 \
<file_sep>/src/Libnids.c
// Libnids used as main, a version where non-ascii chars got rid of
#define _GNU_SOURCE
#include <libnet.h>
#include <malloc.h>
#include <nids.h>
#include <pcap.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
char ascii_string[10000];
int state[7] = {0}; // a simple statistics on libnids
char *char_to_ascii(char ch)
{
memset(ascii_string, 0x00, 10000);
ascii_string[0] = 0;
char *string = ascii_string;
if (isgraph(ch))
{
*string++ = ch;
}
else if (ch == ' ')
{
*string++ = ch;
}
else if (ch == '\n' || ch == '\r')
{
*string++ = ch;
}
else
{
*string++ = '.';
}
*string = 0;
return ascii_string;
}
void tcp_protocol_callback(struct tcp_stream *tcp_connection, void **arg)
{
// printf("tcp_protocol_callback\n");
int i;
char address_string[1024];
static char content[65535];
// char content_urgent[65535];
struct tuple4 ip_and_port = tcp_connection->addr;
strcpy(address_string, inet_ntoa(*((struct in_addr *)&(ip_and_port.saddr))));
sprintf(address_string + strlen(address_string), " : %i", ip_and_port.source);
strcat(address_string, " <---> ");
strcat(address_string, inet_ntoa(*((struct in_addr *)&(ip_and_port.daddr))));
sprintf(address_string + strlen(address_string), " : %i", ip_and_port.dest);
strcat(address_string, "\n");
switch (tcp_connection->nids_state)
{
case NIDS_JUST_EST:
tcp_connection->client.collect++;
tcp_connection->server.collect++;
tcp_connection->server.collect_urg++;
tcp_connection->client.collect_urg++;
printf("%sTCP connection sets up\n", address_string);
state[NIDS_JUST_EST]++;
return;
case NIDS_CLOSE:
printf("--------------------------------\n");
printf("%sTCP connection closes normally\n", address_string);
state[NIDS_CLOSE]++;
return;
case NIDS_RESET:
printf("--------------------------------\n");
printf("%sTCP Connection closed by RST\n", address_string);
state[NIDS_RESET]++;
return;
case NIDS_DATA:
{
state[NIDS_DATA]++;
struct half_stream *hlf;
if (tcp_connection->server.count_new_urg)
{
printf("--------------------------------\n");
strcpy(address_string, inet_ntoa(*((struct in_addr *)&(ip_and_port.saddr))));
sprintf(address_string + strlen(address_string), " : %i", ip_and_port.source);
strcat(address_string, " urgent---> ");
strcat(address_string, inet_ntoa(*((struct in_addr *)&(ip_and_port.daddr))));
sprintf(address_string + strlen(address_string), " : %i", ip_and_port.dest);
strcat(address_string, "\n");
address_string[strlen(address_string) + 1] = 0;
address_string[strlen(address_string)] = tcp_connection->server.urgdata;
printf("%s", address_string);
return;
}
if (tcp_connection->client.count_new_urg)
{
printf("--------------------------------\n");
strcpy(address_string, inet_ntoa(*((struct in_addr *)&(ip_and_port.saddr))));
sprintf(address_string + strlen(address_string), " : %i", ip_and_port.source);
strcat(address_string, " <--- urgent ");
strcat(address_string, inet_ntoa(*((struct in_addr *)&(ip_and_port.daddr))));
sprintf(address_string + strlen(address_string), " : %i", ip_and_port.dest);
strcat(address_string, "\n");
address_string[strlen(address_string) + 1] = 0;
address_string[strlen(address_string)] = tcp_connection->client.urgdata;
printf("%s", address_string);
return;
}
if (tcp_connection->client.count_new)
{
hlf = &tcp_connection->client;
strcpy(address_string, inet_ntoa(*((struct in_addr *)&(ip_and_port.saddr))));
sprintf(address_string + strlen(address_string), ":%i", ip_and_port.source);
strcat(address_string, " <--- ");
strcat(address_string, inet_ntoa(*((struct in_addr *)&(ip_and_port.daddr))));
sprintf(address_string + strlen(address_string), ":%i", ip_and_port.dest);
strcat(address_string, "\n");
printf("--------------------------------\n");
printf("%s", address_string);
memcpy(content, hlf->data, hlf->count_new);
content[hlf->count_new] = '\0';
printf("client side receive data\n");
for (i = 0; i < hlf->count_new; i++) {
printf("%s", char_to_ascii(content[i]));
}
printf("\n");
return;
}
else
{
hlf = &tcp_connection->server;
strcpy(address_string, inet_ntoa(*((struct in_addr *)&(ip_and_port.saddr))));
sprintf(address_string + strlen(address_string), ":%i", ip_and_port.source);
strcat(address_string, " ---> ");
strcat(address_string, inet_ntoa(*((struct in_addr *)&(ip_and_port.daddr))));
sprintf(address_string + strlen(address_string), ":%i", ip_and_port.dest);
strcat(address_string, "\n");
printf("--------------------------------\n");
printf("%s", address_string);
memcpy(content, hlf->data, hlf->count_new);
content[hlf->count_new] = '\0';
printf("Server side receive data:\n");
for (i = 0; i < hlf->count_new; i++) {
printf("%s", char_to_ascii(content[i]));
}
printf("\n");
return;
}
for (int i = 10; i < 20; i += 1) {
memcpy(&content[i * 1024], &content[(i - 10) * 1024], 1024);
}
return;
}
default:
state[0]++;
break;
}
return;
}
static void nids_syslog(int type, int errnum, struct ip *iph, void *data)
{
fprintf(stderr, "nids_syslog not implemented\n");
}
void nids_no_mem(char *func)
{
fprintf(stderr, "Out of memory in %s.\n", func);
exit(1);
}
static int nids_ip_filter(struct ip *x, int len)
{
(void)x;
(void)len;
return 1;
}
static void local_nids_init()
{
nids_params.n_tcp_streams = 1040;
nids_params.n_hosts = 256;
nids_params.device = NULL;
nids_params.filename = NULL;
nids_params.sk_buff_size = 168;
nids_params.dev_addon = -1;
nids_params.syslog = nids_syslog;
nids_params.syslog_level = 1;
nids_params.scan_num_hosts = 256;
nids_params.scan_delay = 3000;
nids_params.scan_num_ports = 10;
nids_params.no_mem = nids_no_mem;
nids_params.ip_filter = nids_ip_filter;
nids_params.pcap_filter = NULL;
nids_params.promisc = 1;
nids_params.one_loop_less = 0;
nids_params.pcap_timeout = 1024;
nids_params.multiproc = 0;
nids_params.queue_limit = 20000;
nids_params.tcp_workarounds = 0;
nids_params.pcap_desc = NULL;
nids_params.tcp_flow_timeout = 3600;
}
int main(int argc, char *argv[], char **env)
{
struct nids_chksum_ctl temp;
temp.netaddr = 0;
temp.mask = 0;
temp.action = 1;
nids_register_chksum_ctl(&temp, 1);
// sign... tiangou inside executable. This is just a quick check to see if there is other problems
// beside copy relocation
// local_nids_init();
nids_params.filename = "/dev/shm/huawei_tcp.pcap";
// nids_params.device = "all";
if (!nids_init())
{
printf("Error:%s\n", nids_errbuf);
exit(1);
}
nids_register_tcp((void *)tcp_protocol_callback);
nids_run();
return 0;
}
<file_sep>/readme.md
Simple experiments I made to load executables using dlopen<file_sep>/src/Time.c
// previous tests show that localtime called in dlopen-ed executables may get SEGFAULT
// since we now have a self-compiled version of glibc, it benefits to see if the problem persists
/* July. 5 update:
* I found out where the problem lies using a self-compiled glibc which is not stripped
* and it really comes to my rescue.
* Using a separate copy of renamed glibc may lack some critical initialization happens in rtld.c,
* making `malloc' calls internal to glibc fails. The program crashes when dl_addr ask for a lock,
* at dl-addr.c:131
* So it comes to a dilemma again, we have to rethink about the design choice: glibc may have another
* 100 of subtle bugs even reading the source won't help a lot. Of course we could cherry-pick, but
* the impact remains uncertain. To me, I think making initialized libc and ld.so shared might be a
* better choice. This can be done if we are using PKU, for the consistency of address space is no
* longer an issue.
* TO achieve this, dlmopen and deepbind are almost absolutely disabled. Also, the symbols inside global
* scope also need to be considered wisely.
* Another issue is that I still can't make audit interface working when dealing with dlopen-ed libararies.
* If I can get this working, deepbind or not might not be an issue.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
time_t t = 1555332781;
struct tm *tm = localtime(&t);
printf("daylight: %d\n", daylight);
printf("isdst: %d\n", tm->tm_isdst);
return 0;
}<file_sep>/audit/libnids-audit.c
// this audit interface is a test to hopefully fix the copy relocation
#define _GNU_SOURCE
#include <link.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
#include <nids.h>
// *** do a little tiangou-ing ***
// the reason why I have to do this in a hard way is that
// some functions like nids_ip_filter are static, I just cannot get the address outside the SO
// Plus, AUDIT interface is not powerful enough to refuse a symbol binding:
// once there is a hit, hit it is. Nothing can change this
// So the only thing I can do is to provide a set of definitions here, and interpose using audit
static void nids_syslog(int type, int errnum, struct ip *iph, void *data)
{
fprintf(stderr, "nids_syslog not implemented\n");
}
void nids_no_mem(char *func)
{
fprintf(stderr, "Out of memory in %s.\n", func);
exit(1);
}
static int nids_ip_filter(struct ip *x, int len)
{
(void)x;
(void)len;
return 1;
}
struct nids_prm nids_params = {
1040, /* n_tcp_streams */
256, /* n_hosts */
NULL, /* device */
NULL, /* filename */
168, /* sk_buff_size */
-1, /* dev_addon */
nids_syslog, /* syslog() */
1, /* syslog_level */
256, /* scan_num_hosts */
3000, /* scan_delay */
10, /* scan_num_ports */
nids_no_mem, /* no_mem() */
nids_ip_filter, /* ip_filter() */
NULL, /* pcap_filter */
1, /* promisc */
0, /* one_loop_less */
1024, /* pcap_timeout */
0, /* multiproc */
20000, /* queue_limit */
0, /* tcp_workarounds */
NULL, /* pcap_desc */
3600 /* tcp_flow_timeout */
};
// *** end of tiangou-ing ***
unsigned int la_version(unsigned int version)
{
return LAV_CURRENT;
}
unsigned int la_objopen(struct link_map *map, Lmid_t lmid, uintptr_t *cookie)
{
if(strcmp(map->l_name, "/usr/local/lib/libnids.so.1.25") == 0)
{
fprintf(stderr, "libnids reporting\n");
return LA_FLG_BINDTO | LA_FLG_BINDFROM;
}
if(strcmp(map->l_name, "/home/hypermoon/Qcloud/TST-load-exe/src/main-libnids") == 0)
{
fprintf(stderr, "PIE executable reporting\n");
return LA_FLG_BINDTO | LA_FLG_BINDFROM;
}
return LA_FLG_BINDTO | LA_FLG_BINDFROM;
}
uintptr_t la_symbind64(Elf64_Sym *sym, unsigned int ndx, uintptr_t *refcook, uintptr_t *defcook, unsigned int *flags, const char *symname)
{
printf("binding symbol: %s\n", symname);
// if (strcmp (symname, "nids_params") == 0)
// {
// fprintf(stderr, "bind for nids_params\n");
// return (uintptr_t)&nids_params;
// }
return sym->st_value;
}<file_sep>/build.sh
#!/usr/bin/env bash
set -eux
gcc \
-L/home/hypermoon/Qcloud/glibc/build/install/lib \
-I/home/hypermoon/Qcloud/glibc/build/install/include \
-Wl,-rpath=/home/hypermoon/Qcloud/glibc/build/install/lib \
-Wl,--dynamic-linker=/home/hypermoon/Qcloud/glibc/build/install/lib/ld-linux-x86-64.so.2 \
-std=c11 \
-o "$1" \
-g \
"$1.c" \
-ldl
# build Loader, nothing special
<file_sep>/Loader.c
// 'clean' version of a rewriter and loader
// To start loader:
// LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib/ ./Loader [path to executable]
// To debug loader:
// LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib/ gdb --args ./Loader [path to executable]
// patched ELF outputs at /usr/local/lib, so it's necessary to include it as a library path
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <elf.h>
#include <link.h>
void rewrite(const char *filename)
{
// ugh! we still have to rewrite the ELF header to HOAX poor little ld.so...
FILE *f = fopen(filename, "rb+");
char *tHeader = malloc(sizeof(Elf64_Ehdr));
if(fread(tHeader, sizeof(Elf64_Ehdr), 1, f) <= 0)
{
fprintf(stderr, "reading ELF header from %s failed\n", filename);
exit(-1);
}
Elf64_Ehdr *etmp = (Elf64_Ehdr *)tHeader;
// this won't work because PIEs are considered as shared objects and has ET_DYN type
// printf("the type of ELf is %s\n", etmp->e_type == ET_DYN? "ET_DYN": "ET_EXEC");
// etmp->e_type = ET_DYN;
Elf64_Addr entry = etmp->e_entry;
Elf64_Addr phoff = etmp->e_phoff;
Elf64_Addr phlen = etmp->e_phnum * sizeof(Elf64_Phdr);
Elf64_Half phnum = etmp->e_phnum;
Elf64_Phdr *phdr = malloc(phlen);
fseek(f, phoff, SEEK_SET);
fread(phdr, phlen, 1, f);
Elf64_Dyn *ld;
Elf64_Sxword ldlen;
Elf64_Off ldoff;
for(Elf64_Phdr *ph = phdr; ph < &phdr[phnum]; ph++)
{
if (ph->p_type == PT_DYNAMIC)
{
ld = malloc(ph->p_memsz);
ldoff = ph->p_offset;
fseek(f, ldoff, SEEK_SET);
ldlen = ph->p_memsz;
fread(ld, ldlen, 1, f);
break;
}
}
for(Elf64_Dyn *d = ld; ;d++)
{
if(d->d_tag == DT_FLAGS_1)
{
d->d_un.d_val = 0;
break;
}
}
fseek(f, ldoff, SEEK_SET);
if(fwrite(ld, ldlen, 1, f) <= 0)
{
fprintf(stderr, "overwrite the content of dynamic section failed\n");
exit(-1);
}
fclose(f);
}
static void debug_stop()
{
int sleeper;
scanf("%d", &sleeper);
}
int main(int argc, char *argv[])
{
if (argc != 2 && argc != 3)
{
fprintf(stderr, "usage: ./Loader [exe name] (optional)[address of main]\n");
exit(-1);
}
rewrite(argv[1]);
// now life is sane, we finally can dlopen the modified version of executable
void *handle1 = dlopen(argv[1], RTLD_NOW);
// void *handle1 = dlopen(argv[1], RTLD_NOW | RTLD_DEEPBIND);
// void *handle1 = dlmopen(LM_ID_NEWLM, argv[1], RTLD_NOW);
if(!handle1)
{
fprintf(stderr, "cannot loader shared object because: %s\n", dlerror());
exit(-1);
}
// void *handle1 = dlmopen(LM_ID_NEWLM, argv[1], RTLD_NOW);
// note that I don't bother to compile without -rdynamic when testing, it saves useless job
int (*main1)() = dlsym(handle1, "main");
// debug_stop();
if (main1 != NULL)
main1();
else
{
if(argc == 3)
{
printf("using address of main at %s\n", argv[2]);
unsigned long main_num = strtoul(argv[2], NULL, 0);
struct link_map *l = (struct link_map *)handle1;
main_num += l->l_addr;
main1 = (void *)main_num;
main1();
}
else
{
fprintf(stderr, "cannot find main of executable, nor you provide one. Try recompile with rdynamic\n");
exit(-1);
}
}
return 0;
}
|
33d6673dad1fdedea72fd62d0defa12dedc40268
|
[
"Markdown",
"C",
"Shell"
] | 7
|
Shell
|
Qcloud1223/exe-loading
|
8e3fde298b95e435da0661e7695006b8a39ec0fe
|
584662595fc2f8de150549c186d26f35d3945556
|
refs/heads/main
|
<repo_name>maryletteroa/gcp-cloud-resources-mgt<file_sep>/gcp_commands.sh
# set zone / region, project
gclud auth list
gcloud projects list
gcloud config set compute/zone us-east1-b
gcloud config set compute/region us-east1
gcloud config set project my-project
#### Virtual machine instance
# create vm instance
gcloud compute instances create nucleus-jumphost --machine-type f1-micro ## or if this doesn't work, set it up manually in the ui
### Kubernetes service cluster
# create a kubernetes cluster
gcloud container clusters create my-cluster
gcloud container clusters get-credentials my-cluster
# deploy and image
kubectl create deployment hello-server --image=gcr.io/google-samples/hello-app:2.0
# expose the app on port 8080
kubectl expose deployment hello-server --type=LoadBalancer --port 8080
watch -n 1 kubectl get service ## check until an external ip has been assigned
#### HTTP load balancer
# Create startup script
cat << EOF > startup.sh
#! /bin/bash
apt-get update
apt-get install -y nginx
service nginx start
sed -i -- 's/nginx/Google Cloud Platform - '"\$HOSTNAME"'/' /var/www/html/index.nginx-debian.html
EOF
# Create an instance template
gcloud compute instance-templates create nginx-template --metadata-from-file startup-script=startup.sh
# Create a target pool
gcloud compute target-pools create nginx-pool
# Create managed instance group
gcloud compute instance-groups managed create nginx-group --base-instance-name nginx --size 2 --template nginx-template --target-pool nginx-pool
gcloud compute instances list
# Create firewall rule to allow traffic (80/tcp)
gcloud compute firewall-rules create www-firewall --allow tcp:80
gcloud compute forwarding-rules create nginx-lb --ports=80 --target-pool nginx-pool
gcloud compute forwarding-rules list
# Create a health check
gcloud compute http-health-checks create http-basic-check
gcloud compute instance-groups managed set-named-ports nginx-group --named-ports http:80
# Create a backend service, and attach the managed instance group
gcloud compute backend-services create nginx-backend --protocol HTTP --http-health-checks http-basic-check --global
gcloud compute backend-services add-backend nginx-backend --instance-group nginx-group --global
# Create a URL map, and target the HTTP proxy to route requests to your URL map
gcloud compute url-maps create web-map --default-service nginx-backend
gcloud compute target-http-proxies create http-lb-proxy --url-map web-map
# Create a forwarding rule
gcloud compute forwarding-rules create http-content-rule --global --target-http-proxy http-lb-proxy --ports 80
gcloud compute forwarding-rules list
<file_sep>/README.md
#### About
Commands to manage GCP resources
#### Reference
[Qwiklabs](https://google.qwiklabs.com)
|
e0979d989f02659e04f706357c8dc1e3e74f951a
|
[
"Markdown",
"Shell"
] | 2
|
Shell
|
maryletteroa/gcp-cloud-resources-mgt
|
47e8616478c625c982f45f0e80e4b4c75dda99ae
|
bde744e22ba0a799d4a04827c109b3059aa486e0
|
refs/heads/master
|
<file_sep>from flask import Flask
app = Flask(__name__)
from sys import platform as _platform
if _platform == "linux" or _platform == "linux2":
# linux
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost/icarus'
pass
elif _platform == "darwin":
# OS X
pass
elif _platform == "win32":
# Windows...
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://postgres:postgres@localhost:5432/icarus'
pass
# set the secret key. keep this really secret:
app.secret_key = '<KEY>'
app.debug = False
print("App Created...")
'''initilializing the database connection to SQLLite db'''
from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from datetime import datetime
from sqlalchemy.types import NVARCHAR
import random
import datetime
from flask import render_template, redirect
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
password = db.Column(db.String(500))
email = db.Column(db.String(120), unique=True)
region = db.Column(db.String(120))
country = db.Column(db.String(120))
language = db.Column(db.String(120))
sex = db.Column(db.String(10))
age=db.Column(db.Numeric(10))
avatar = db.Column(db.String(120))
fb_token = db.Column(db.String(250))
g_token = db.Column(db.String(250))
registered_on = db.Column(db.DateTime)
updated_on = db.Column(db.DateTime)
def __init__(self, username, password, email, avatar, fb_token):
self.username = username
self.password = <PASSWORD>
self.email = email
self.avatar = avatar
self.fb_token = fb_token
self.registered_on = datetime.utcnow()
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return self.id
def __repr__(self):
return '<User %r>' % (self.username)
class Event(db.Model):
__tablename__ = "event"
id = db.Column(db.Integer, primary_key=True)
device_id=db.Column(db.Numeric(10))
v1=db.Column(db.Float(10))
v2=db.Column(db.Float(10))
v3=db.Column(db.Float(10))
v4=db.Column(db.Float(10))
v5=db.Column(db.Float(10))
v6=db.Column(db.Float(10))
v7=db.Column(db.Float(10))
v8=db.Column(db.Float(10))
v9=db.Column(db.Float(10))
device_time = db.Column(db.DateTime, default=datetime.datetime.utcnow)
created_on = db.Column(db.DateTime, default=datetime.datetime.utcnow)
def __init__(self, device_id, v1, v2, v3, v4, v5, v6, v7, v8, v9,device_time):
self.device_id = device_id
self.v1 = v1
self.v2 = v2
self.v3 = v3
self.v4 = v4
self.v5 = v5
self.v6 = v6
self.v7 = v7
self.v8 = v8
self.v9 = v9
self.device_time = device_time
print("Classes Created...")
db.create_all()
db.session.commit()
print("Tables Created...")
def populate_users(db):
users = User.query.all()
if not users:
user = User("admin","admin","1", "1","1")
db.session.add(user)
db.session.commit()
else:
pass
populate_users(db)
@app.route('/')
def render_home():
return render_template('index.html')
@app.route('/logout')
def render_logout():
return redirect("/login", code=302)
@app.route('/login')
def render_login():
return render_template('login.html')
@app.route('/map')
def render_map():
return render_template('map.html')
@app.route('/charts')
def render_charts():
return render_template('charts.html')
@app.route('/vehicle_table')
def render_vehicle():
return render_template('vehicle_table.html')
@app.route('/fuel_table')
def render_fuel_table():
return render_template('fuel_table.html')
@app.route('/api/v1/data_logger', methods = ['POST', 'GET'])
def api_solar_logger():
from flask import request
content = request.json
if request.method == 'GET':
print('GET')
else:
# print('OTHER')
pass
# if 'type' in content:
# try:
# event = Event(content['type'],content['value'],content['device_id'])
# db.session.add(event)
# db.session.commit()
# print("Success")
# return 'Success'
# except Exception:
# db.session.rollback()
# print("Failure")
# return 'Failure'
if "id" in content:
for datum in content['data']:
try:
event = Event(device_id=content['id'],v1=datum['v1'],
v2=datum['v2'],v3=datum['v3'],
v4=datum['v4'],v5=datum['v5'],
v6=datum['v6'],v7=datum['v7'],
v8=datum['v8'],v9=datum['v9'],
device_time=datum['t1'])
db.session.add(event)
db.session.commit()
except Exception:
db.session.rollback()
return 'Failure'
return 'Success'
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
import os
port = int(os.environ.get('PORT', 5000))
app.run(debug=True, use_reloader=False, host='0.0.0.0', port=port)
<file_sep>
ALL YOU NEED:
https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-14-04
did everything except ran gunicorn --workers=3 --bind ... icarus_server:app
also use pip3 to install everything
postgres remote access:
http://www.cyberciti.biz/tips/postgres-allow-remote-access-tcp-connection.html
# Grab psycopg2 and pip
apt-get install python3-pip python3-psycopg2
# Remove the Python 2.7 version of gunicorn, so we can...
pip uninstall gunicorn
# Install the Python 3 version of gunicorn, and a couple of dependencies.
pip3 install gunicorn tornado django
# Sadly, at time of writing, gevent isn't Python 3 compatible... But tornado is!
# So, switch them out with a little sed magic
sed 's/worker_class = '\''gevent'\''/worker_class='\''tornado'\''/' /etc/gunicorn.d/gunicorn.py -i.orig
# Restart gunicorn to make the changes take effect...
service gunicorn restart
###############################################
# To start SERVERS:
sudo start icarus
sudo start icarus_tcp //listens on localhost 8888
solartruckingisbadass
logs: sudo /var/log/upstart/icarus.log only right after server has been restarted
HAD TO RUN THIS: sudo chown -R username:group directory
<file_sep>__author__ = 'Waldo'
'''
Simple socket server using threads
'''
import socket, json
from threading import *
import re
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "0.0.0.0"
port = 8888
serversocket.bind((host, port))
class client(Thread):
def __init__(self, socket, address):
Thread.__init__(self)
self.sock = socket
self.addr = address
self.start()
def run(self):
while 1:
# try:
try:
json_load = self.sock.recv(1024).decode()
print("1024 Decoded Load:")
print(json_load)
except:
json_load = self.sock.recv(1024)
print("1024 Un-Decoded Load:")
print(json_load)
try:
db_events = json.loads(json_load)
from icarus_server import db, Event
for db_event in db_events['data']:
event = Event(device_id=db_events['id'],v1=db_event['v1'],
v2=db_event['v2'],v3=db_event['v3'],
v4=db_event['v4'],v5=db_event['v5'],
v6=db_event['v6'],v7=db_event['v7'],
v8=db_event['v8'],v9=db_event['v9'],
device_time=db_event['t1'])
db.session.add(event)
db.session.commit()
print('Client sent:',db_events )
self.sock.send(b'Success')
except Exception as e:
try:
self.sock.send(b'Failure')
except Exception as e2:
print("Connection Prematurely Terminated")
break
serversocket.listen(5)
host_port = str(host) + ":" + str(port)
print ('TCP Server Listening on', host_port)
while 1:
clientsocket, address = serversocket.accept()
client(clientsocket, address)
# import socket
# import sys
#
# HOST = '0.0.0.0' # Symbolic name, meaning all available interfaces
# PORT = 8888 # Arbitrary non-privileged port
#
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# print('Socket created')
#
# #Bind socket to local host and port
# try:
# s.bind((HOST, PORT))
# except socket.error as msg:
# print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
# sys.exit()
#
# print('Socket bind complete')
#
# #Start listening on socket
# s.listen(10)
# print('Socket now listening')
#
# #now keep talking with the client
# while 1:
# #wait to accept a connection - blocking call
# conn, addr = s.accept()
# print('Connected with ' + addr[0] + ':' + str(addr[1]))
#
# s.close()<file_sep>__author__ = 'Waldo'
#!/usr/bin/env python
import socket, json
TCP_IP = '172.16.58.3'
TCP_PORT = 8888
BUFFER_SIZE = 1024
MESSAGE = '''{"id":"1","data": [{"v1": 1,"v2": "99999","v3": "1","v4": "1","v5": "1","v6": "1","v7": "1","v8": "1","v9": "1","t1":"2015-12-19T15:28:46.493Z"},{"v1": 9999,"v2": "1","v3": "1","v4": 2.9997,"v5": "1","v6": "1","v7": "1","v8": "1","v9": "1","t1":"2015-12-19T15:28:46.493Z"}]}'''
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE.encode())
data = s.recv(BUFFER_SIZE)
s.close()
print("Response data:", data)
|
11d04840f77770c46b231ee0ec96f6d6f28b2ec6
|
[
"Markdown",
"Python"
] | 4
|
Python
|
sirwoetang/icarus_server
|
95325ffcc9674414a371f400d3e2e44b94ca3c33
|
b701a303a008807f8d4aaf306ac714b9505fd168
|
refs/heads/master
|
<repo_name>msnyder909/golang-cli-playbook<file_sep>/module6/module6.go
package module6
// FunctionForModule6GoDoc This is the function for module6
func FunctionForModule6GoDoc() {
}
|
f8b9463eddb3383fe82584964ce5873acefcbf8d
|
[
"Go"
] | 1
|
Go
|
msnyder909/golang-cli-playbook
|
8d39b3c9594d7207e3ecf45fc5f6612d9d5c0113
|
1f9c839c845e283cb81f50d1e6091a47c032b406
|
refs/heads/master
|
<repo_name>kanntaim/selenium_task<file_sep>/src/main/java/framework/drivers/WebDriver.java
package framework.drivers;
import framework.utils.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.ArrayList;
import java.util.List;
public class WebDriver {
private static WebDriver ourInstance = new WebDriver();
private org.openqa.selenium.WebDriver driver;
private WebDriver() {
Properties properties = Properties.getInstance();
String browserName = properties.getBrowserName();
switch (browserName) {
case "Firefox":
driver = new FirefoxDriver();
break;
case "Chrome":
driver = new ChromeDriver();
}
}
public static WebDriver getInstance() {
return ourInstance;
}
public void switchTab(int number) {
ArrayList<String> tabs = new ArrayList<>(driver.getWindowHandles());
if (number >= 0) {
driver.switchTo().window(tabs.get(number));
} else {
driver.switchTo().window(tabs.get(tabs.size() + number));
}
}
public void returnToMainPage() {
Properties properties = Properties.getInstance();
String url = properties.getUrl();
this.switchTab(0);
driver.get(url);
driver.navigate().refresh();
}
public String getTitle() {
return driver.getTitle();
}
public void quit() {
driver.quit();
}
public String getPageSource() {
return driver.getPageSource();
}
public void get(String url) {
driver.get(url);
}
public org.openqa.selenium.WebDriver.Options manage() {
return driver.manage();
}
public List<WebElement> findElements(By by) {
return driver.findElements(by);
}
public WebElement findElement(By by) {
return driver.findElement(by);
}
public org.openqa.selenium.WebDriver getDriver() {
return driver;
}
}
<file_sep>/src/test/java/pages/CategoryNamesMap.java
package pages;
import java.util.HashMap;
import java.util.Map;
class CategoryNamesMap {
static private Map categoryNamesMap = createMap();
static private HashMap<String, String> createMap() {
HashMap<String, String> map = new HashMap<>();
map.put("Компьютеры", "Компьютерная техника");
map.put("Зоотовары", "Товары для животных");
map.put("Дом, дача, ремонт", "Товары для дома");
map.put("Красота и здоровье", "Товары для красоты и здоровья");
map.put("Авто", "Товары для авто- и мототехники");
return map;
}
static boolean compareCategoryName(String categoryInList, String categoryOnPage) {
if (categoryInList.compareTo(categoryOnPage) == 0) {
return true;
}
return categoryNamesMap.get(categoryInList).toString().compareTo(categoryOnPage) == 0;
}
}
<file_sep>/src/main/java/framework/utils/Properties.java
package framework.utils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Properties {
private static Properties ourInstance = new Properties();
private String url;
private String webdriverPath;
private String webdriverName;
private String browserName;
private Properties() {
String propertiesPath = System.getProperty("propertiesFilePath");
try (BufferedReader propertyReader = new BufferedReader(new FileReader(propertiesPath))) {
String line;
while ((line = propertyReader.readLine()) != null) {
String[] property = line.split("=");
String propertyName = property[0];
String propertyValue = property[1];
switch (propertyName) {
case "url":
url = propertyValue;
break;
case "webdriverPath":
webdriverPath = propertyValue;
break;
case "webdriverName":
webdriverName = propertyValue;
break;
case "browserName":
browserName = propertyValue;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static Properties getInstance() {
return ourInstance;
}
public String getUrl() {
return url;
}
public String getWebdriverPath() {
return webdriverPath;
}
public String getWebdriverName() {
return webdriverName;
}
public String getBrowserName() {
return browserName;
}
}
<file_sep>/src/test/java/pages/CategoryPage.java
package pages;
import framework.drivers.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class CategoryPage {
private final By categoryNameLocator = By.tagName("h1");
private final By categoryCurrentButtonLocator = By.xpath("//li[contains(@class, \"topmenu__item_mode_current\")]");
private final WebDriver driver = WebDriver.getInstance();
CategoryPage() {
(new WebDriverWait(driver.getDriver(), 5))
.until(ExpectedConditions.visibilityOfElementLocated(categoryNameLocator));
}
public boolean compareCategoryNames() {
String buttonText = driver.findElement(categoryCurrentButtonLocator).getAttribute("data-department");
String pageText = driver.findElement(categoryNameLocator).getText();
return CategoryNamesMap.compareCategoryName(buttonText, pageText);
}
}
<file_sep>/src/test/java/pages/MainPage.java
package pages;
import framework.drivers.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainPage {
private final By loginLocator = By.xpath("//span[contains(text(), \"Войти\")]/ancestor::a[@role=\"button\"]");
private final By categoriesLocator = By.xpath("//ul[@class=\"topmenu__list\"]/.//li");
private final By userLocator = By.className("n-passport-suggest-popup-opener");
private final By popularGoodsLocator = By.xpath("//h3[contains(text(), \"Популярные товары\")]");
private final By userLogOutLocator = By.cssSelector(".user__logout");
private final String userNameLocatorTemplate = "//span[contains(text(), \"%s\")]";
private final WebDriver driver = WebDriver.getInstance();
public MainPage() {
if (!driver.getTitle().startsWith("Яндекс.Маркет")) {
throw new IllegalStateException("This is not the main page");
}
}
public LoginPage navigateLogin() {
List<WebElement> loginButtons = driver.findElements(loginLocator);
for (WebElement button : loginButtons) {
if (button.isEnabled() && button.isDisplayed()) {
button.click();
driver.switchTab(-1);
return new LoginPage();
}
}
throw new IllegalStateException("Login button not found");
}
public CategoryPage navigateRandomCategory() {
List<WebElement> categoryList = driver.findElements(categoriesLocator);
Random rand = new Random();
WebElement btnRandomCategory = categoryList.get(rand.nextInt(categoryList.size() - 2));
btnRandomCategory.click();
return new CategoryPage();
}
public boolean isAuthorized(String login) {
String userNameLocatorString = String.format(userNameLocatorTemplate, login.substring(1));
By userNameLocator = By.xpath(userNameLocatorString);
List<WebElement> userName = driver.findElements(userNameLocator);
return !userName.isEmpty();
}
public List<String> getPopularGoods(String pageSource) {
String popularGoodsFieldRegexp = "Популярные товары</h3>.*</div></div></div></div></div></div></a></div></div>";
String popularGoodsRegexp = ".*?reactid=\"\\d*\">([A-ZА-Я][^<]*?)<.*?";
List<String> popularGoods = new LinkedList<>();
Pattern popularGoodsFieldPattern = Pattern.compile(popularGoodsFieldRegexp);
Matcher popularGoodsFieldMatcher = popularGoodsFieldPattern.matcher(pageSource);
if (!popularGoodsFieldMatcher.find()) {
driver.returnToMainPage();
((JavascriptExecutor) driver.getDriver()).executeScript("window.scrollTo(0,500);");
new WebDriverWait(driver.getDriver(), 10)
.until(ExpectedConditions.visibilityOfElementLocated(popularGoodsLocator));
return getPopularGoods(driver.getPageSource());
}
String popularGoodsField = popularGoodsFieldMatcher.group();
Pattern popularGoodsPattern = Pattern.compile(popularGoodsRegexp);
Matcher popularGoodsMatcher = popularGoodsPattern.matcher(popularGoodsField);
while (popularGoodsMatcher.find()) {
popularGoods.add(popularGoodsMatcher.group(1));
}
return popularGoods;
}
public void logOut() {
Wait<org.openqa.selenium.WebDriver> wait = new FluentWait<>(driver.getDriver()).withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofMillis(600))
.ignoring(NoSuchElementException.class);
WebElement user = wait.until(ExpectedConditions.elementToBeClickable(userLocator));
Actions actions = new Actions(driver.getDriver());
actions.click(user).build().perform();
WebElement userLogOut = new WebDriverWait(driver.getDriver(), 5)
.until(ExpectedConditions.elementToBeClickable(userLogOutLocator));
userLogOut.click();
}
public boolean CheckIsNotAuthorized() {
List<WebElement> loginButtons = driver.findElements(loginLocator);
for (WebElement button : loginButtons) {
if (button.isEnabled() && button.isDisplayed()) {
return true;
}
}
return false;
}
}
<file_sep>/src/resources/.properties
url=https://market.yandex.ru/
webdriverPath=src/resources/drivers/win32/chromedriver.exe
webdriverName=webdriver.chrome.driver
browserName=Chrome
|
3e7b624579e2cad2bf7581db9c6d8bde3bdac015
|
[
"Java",
"INI"
] | 6
|
Java
|
kanntaim/selenium_task
|
3b497aa2d80d7026f073517bfc3ff831be58e4a9
|
ef3f7113f6f3c4280a27a141e4ea0c960922096f
|
refs/heads/master
|
<file_sep># About the project
this is a simple quiz app created with Javascript.<file_sep>// variables that control the quiz
let rightQuestions = 0;
let wrongQuestions = 0;
let questionIndex = 0;
let currentQuestion = null;
let isAnswered = false;
let timerID = null;
// Get all necessary elements
const startScene = document.querySelector('#start-quiz');
const restartScene = document.querySelector('#restart-quiz');
const modal = document.querySelector('.modal');
const startButton = document.querySelector('#start');
const restartButton = document.querySelector('#restart');
const resultDisplay = document.querySelector('#result-display');
const questionTitle = document.querySelector('#question-title');
const questionAlternatives = document.querySelector('#question-alternatives');
const nextButton = document.querySelector('#next');
const timerSeconds = document.querySelector('#timer-seconds');
startButton.addEventListener('click', () => {
startScene.style.display = 'none';
startQuiz();
});
restartButton.addEventListener('click', () => {
restartScene.style.display = 'none';
startQuiz();
});
questionAlternatives.addEventListener('click', event => {
if (isAnswered) return;
const answerUser = event.target;
if (answerUser.tagName !== 'LI') return;
if (answerUser === currentQuestion.correctEl) {
answerUser.classList.add('alternative--check');
rightQuestions++;
} else {
answerUser.classList.add('alternative--wrong');
currentQuestion.correctEl.classList.add('alternative--check');
wrongQuestions++;
}
clearInterval(timerID);
isAnswered = true;
nextButton.disabled = false;
});
nextButton.addEventListener('click', () => {
questionIndex++;
timerSeconds.innerText = '15';
prepareQuestion();
});
// Functions
function startQuiz() {
rightQuestions = 0;
wrongQuestions = 0;
questionIndex = 0;
modal.style.display = 'flex';
prepareQuestion();
}
function prepareQuestion() {
if (questionIndex >= questions.length) {
modal.style.display = 'none';
restartScene.style.display = 'block';
displayResults();
return;
}
let timeLeft = 15;
isAnswered = false;
currentQuestion = questions[questionIndex];
showQuestion(currentQuestion);
timerID = setInterval(() => {
timeLeft--;
if (timeLeft <= 0) {
currentQuestion.correctEl.classList.add('alternative--check');
wrongQuestions++;
nextButton.disabled = false;
clearInterval(timerID)
}
timerSeconds.innerText = timeLeft;
}, 1000);
}
function showQuestion(question) {
questionTitle.innerText = `${questionIndex + 1}. ${currentQuestion.title}`;
questionAlternatives.innerHTML = '';
for (let alternative of question.alternatives) {
const item = document.createElement('li');
item.innerHTML = `
${alternative}
<div class="alternative__icons">
<i class="icon icon--check far fa-check-circle"></i>
<i class="icon icon--wrong far fa-times-circle"></i>
</div>
`;
item.className = 'alternative';
questionAlternatives.appendChild(item);
if (alternative === question.correctAlternative) currentQuestion.correctEl = item;
}
}
function displayResults() {
resultDisplay.innerHTML = `Right questions: ${rightQuestions} <br> Wrong Questions: ${wrongQuestions}`;
}
|
aa8490e468aeb68afaf4747c3674403a616fd290
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
jose-uilton-ferreira/quiz-app
|
2a4d7dd772d5ddac499f422c3512e454ea30984b
|
a25d97a099c5eece8b5eea03a825d4fefdaec891
|
refs/heads/master
|
<repo_name>yellowsimulator/INF5620-solutions<file_sep>/decay_plot_error.py
from numpy import *
from matplotlib.pyplot import *
def solver(I, a, T, dt, theta):
"""Solve u'=-a*u, u(0)=I, for t in (0,T] with steps of dt."""
dt = float(dt) # avoid integer division
Nt = int(round(T/dt)) # no of time intervals
T = Nt*dt # adjust T to fit time step dt
u = zeros(Nt+1) # array of u[n] values
t = linspace(0, T, Nt+1) # time mesh
u[0] = I # assign initial condition
for n in range(0, Nt): # n=0,1,...,Nt-1
u[n+1] = (1 - (1-theta)*a*dt)/(1 + theta*dt*a)*u[n]
return u, t
def exact_solution(t, I, a):
return I*exp(-a*t)
def explore(I, a, T, dt, theta=0.5, makeplot=True):
"""
Run a case with the solver, compute error measure,
and plot the numerical and exact solutions (if makeplot=True).
"""
figure()
for dt in dt_values:
u, t = solver(I, a, T, dt, theta) # Numerical solution
u_e = exact_solution(t, I, a)
e = u_e - u
plot(t,e)
hold('on')
legend(['dt=%g' %dt for dt in dt_values])
xlabel('t')
ylabel('u')
title('theta=%g %theta')
theta2name = {0: 'FE', 1: 'BE', 0.5: 'CN'}
#savefig('%s_%g.png' % (theta2name[theta], dt))
#savefig('%s_%g.pdf' % (theta2name[theta], dt))
def main(I, a, T, dt_values, theta_values=(0, 0.5, 1)):
for theta in theta_values:
explore(I, a, T, dt_values, theta)
dt=0.1
dt_values=[dt,dt/4.,dt/8]
main(I=1, a=2, T=5, dt_values=dt_values)
show()
<file_sep>/exponential_growth.py
from numpy import *
from matplotlib.pyplot import *
def solver(I, a, b, T, dt, theta):
"""
Solve u'=-a(t)*u + b(t), u(0)=I,
for t in (0,T] with steps of dt.
a and b are Python functions of t.
"""
dt = float(dt)
Nt = int(round(T/dt))
T = Nt*dt
u = zeros(Nt+1)
t = linspace(0, T, Nt+1)
u[0] = I
for n in range(0, Nt):
u[n+1] = ((1 - dt*(1-theta)*a(t[n]))*u[n] + \
dt*(theta*b(t[n+1]) + (1-theta)*b(t[n])))/\
(1 + dt*theta*a(t[n+1]))
return u, t
def plote():
"""
plot exact and numerical
solution
"""
def exact(t):
return 1*exp(1*t)
def a(t):
return -1
def b(t):
return 0
theta = 1; I = 1; dt = 1.25
Nt = 40
T=Nt*dt
t0=linspace(0,T,1000)
u, t = solver(I=I, a=a, b=b, T=Nt*dt, dt=dt, theta=theta)
ue=exact(t0)
plot(t,u,'-o',t0,ue)
#plot(t,u,'-o')
#legend( ['numerical', 'exact'])
show()
if __name__ == '__main__':
plote()
<file_sep>/decay_plot_fd_error.py
from numpy import logspace, exp
import matplotlib.pyplot as pl
from matplotlib.pyplot import semilogx
def error_plot():
"""
error fraction for Forward Euler, backward Euler
and centered finite difference scheme.
p=a*dt, where a is a constant and dt is the mesh size
"""
p = logspace(-6, -0.5, 101)
Ef = (1-exp(-p))/p
Eb = (-1+exp(p))/p
Ec=(exp(0.5*p)-exp(-0.5*p))/p
semilogx(p, Ec,'-',p,Ef,'r',p,Eb,'o')
pl.legend( ['CN', 'FE','BE'])
pl.show()
def taylor():
"""
Perfom taylor serie expansion of the error fraction
for Forward Euler, Backward Euler and <NAME>
finite difference scheme
"""
from sympy import Symbol,exp,series, Rational
p = Symbol('p')
Ef = (1-exp(-p))/p
Eb = (-1+exp(p))/p
r = Rational(1,2)
Ec=(exp(r*p)-exp(-r*p))/p
Taylor_Ef=series(Ef,p,0,2)
Taylor_Eb=series(Eb,p,0,2)
Taylor_Ec=series(Ec,p,0,3)
print Taylor_Ef
#error_plot()
taylor()
<file_sep>/mesh_function.py
import numpy as np
import pylab as pl
from math import pi, sin
def mesh_function(f,t):
"""
given a function f, and an array t
such that t=t0,t1,...tN, compute
f(t0),...,f(tN)
"""
g=np.zeros(len(t)) #initialise the mesh function g
# loop over the array t
for i in range(len(t)):
g[i]=f(t[i])
#return g
return g
def mesh_function_plot(a,b,dt):
"""
this function plot a mesh function at n mesh points,
given a continuous function
f defined on an interval [a,b].
"""
#define f
def f(t):
if t <=3:
return np.exp(-t)
else:
return np.exp(-3*t)
#compute mesh function
n=int((b-a)/dt)
t=np.arange(a,b,dt)
u=mesh_function(f,t)
pl.plot(t,u)
pl.xlabel('t')
pl.ylabel('mesh function')
pl.title('plot of a mesh function for %d mesh points' %n)
pl.show()
# input values from command
a=int(raw_input("Enter first interval point a :" ))
b=int(raw_input("Enter second interval point b :" ))
dt=float(raw_input("Enter mesh size dt :" ))
mesh_function_plot(a,b,dt)
<file_sep>/README.md
# INF5620-solutions
<file_sep>/differentiate.py
import numpy as np
def differentiate(u,dt):
"""
this function differentiates
a mesh function with centered difference
at inner points and forward and backward difference
at end points
"""
dudt=np.zeros(len(u))
#centered difference , n=1,..,N-1
for i in range(1,len(dudt)-1,1):
dudt[i]=(u[i+1]-u[i-1])/(2*dt)
#Forward difference at n=1
i=0
dudt[i]=(u[i+1]-u[i])/dt
#Backward fifference at n=N
i=len(dudt)-1
dudt[i]=(u[i]-u[i-1])/dt
return dudt
def test_differentiate():
"""
Given a quadratic function
test if the differentiation in differentiate
function is correct
"""
t=np.linspace(0,6,13)
u=10*t + 5
dt=t[1]-t[0]
dudt_computed=differentiate(u,dt)
dudt_expected=10
error=abs((dudt_computed-dudt_expected).max())
Tol=1E-15
assert error<Tol,"differetiation formula is incorrect"
print "test passed with error %15f: " %error
def differentiate_vec(u,dt):
"""
Using vectorization,
this function differentiates
a mesh function with centered difference
at inner points and forward and backward difference
at end points
"""
dudt=np.zeros(len(u))
#centered difference , n=1,..,N-1
dudt[1:-1]=(u[2:]-u[0:-2])/(2*dt)
#Forward difference at n=1
dudt[0]=(u[1]-u[0])/dt
#Backward fifference at n=N
i=len(dudt)-1
dudt[-1]=(u[-1]-u[-2])/dt
return dudt
def test_differentiate_vec():
"""
Given a quadratic function
test if the differentiation in differentiate
function is correct
"""
t=np.linspace(0,6,13)
u=10*t + 5
dt=t[1]-t[0]
dudt_computed=differentiate_vec(u,dt)
dudt_expected=10
error=abs((dudt_computed-dudt_expected).max())
Tol=1E-15
assert error<Tol,"differetiation formula is incorrect"
print "test passed with error %15f: " %error
test_differentiate_vec()
|
c449646bb56a05b2597188b06a37152e42fe088d
|
[
"Markdown",
"Python"
] | 6
|
Python
|
yellowsimulator/INF5620-solutions
|
acb94171922a38d97ba3d433dc8e1142a03e7194
|
46a888eee3069d706f5c37ce23807ccf1e9d9467
|
refs/heads/master
|
<file_sep>def on_button_pressed_a():
OLED.clear()
OLED.write_string_new_line("ahoj MATO")
input.on_button_pressed(Button.A, on_button_pressed_a)
def on_button_pressed_b():
OLED.new_line()
OLED.write_string("Teplota: ")
OLED.write_num(input.temperature())
OLED.new_line()
OLED.write_string("Osvetlenie: ")
OLED.write_num(input.light_level())
input.on_button_pressed(Button.B, on_button_pressed_b)
OLED.init(128, 64)
def on_forever():
pass
basic.forever(on_forever)
<file_sep>input.onButtonPressed(Button.A, function () {
OLED.clear()
OLED.writeStringNewLine("ahoj MUMAK")
OLED.drawRectangle(
0,
20,
50,
50
)
})
input.onButtonPressed(Button.B, function () {
OLED.clear()
OLED.newLine()
OLED.writeString("Teplota: ")
OLED.writeNum(input.temperature())
OLED.newLine()
OLED.writeString("Osvetlenie: ")
OLED.writeNum(input.lightLevel())
OLED.newLine()
OLED.writeString("Kompas:")
OLED.writeNum(input.compassHeading())
})
OLED.init(128, 64)
for (let index = 0; index <= 100; index++) {
OLED.drawLoading(index)
}
for (let index = 0; index <= 3; index++) {
OLED.newLine()
}
OLED.writeStringNewLine("Stlac A alebo B")
basic.forever(function () {
basic.showLeds(`
# . . . .
# . # # .
. . . . .
. . # . .
. . . . .
`)
music.playTone(262, music.beat(BeatFraction.Whole))
})
|
f059cdeab6c945ed55fa24ed8c3bbdcc91a36886
|
[
"Python",
"TypeScript"
] | 2
|
Python
|
motyliak/display
|
3f80e4c6c49d98b67503280a4c443e7aeb335a6d
|
3f9011f93b7c7c2bce83107b16526b9fd33029b6
|
refs/heads/master
|
<file_sep># Song-Genre-Classifier
A classifier for song genre detection using CNNs.
The GTZAN dataset was used for training the model.
Download from: http://opihi.cs.uvic.ca/sound/genres.tar.gz
The dataset consists of 30 second snippets of 1000 songs evenly spread across 10 genres.
The spectrogram_converter.py has the code for converting the songs into spectrograms.
The dataset.npz file is the numpy zip of the data.
Code for importing:<br>
<pre>
import numpy as np
data=np.load("dataset.npz")
X=dataset['arr_0'] #spectrograms converted to np array
y=dataset['arr_1'] #classes
</pre>
This approach yields a 77% accuracy on test set after training for 100 epochs.
The model.h5 file has the pretrained model that can be imported using tensorflow.
The model.png file has the network graph of the model.
<file_sep>import os
import sys
from subprocess import check_call
from tempfile import mktemp
from scipy.io import wavfile
import matplotlib.pyplot as plt
from pydub import AudioSegment
folderpath="/run/media/sangram/Games and Study Materials/Projects/Song Genre Classifier/genres/"
outpath="/run/media/sangram/Games and Study Materials/Projects/Song Genre Classifier/spectro/"
folderlist=os.listdir(folderpath)
for foldername in folderlist:
filepath=folderpath+foldername+"/"
filelist=os.listdir(filepath)
for filename in filelist:
aufilepath=filepath+filename
wname = mktemp('.wav')
sound=AudioSegment.from_file(aufilepath,'au')
sound.export(wname,format="wav")
samplingfreq,signaldata= wavfile.read(wname)
os.unlink(wname)
if(len(signaldata.shape)==2):
signaldata=signaldata[:,0]
fig=plt.figure(frameon=False)
ax=plt.Axes(fig, [1.,1.,1.,1.])
fig.set_size_inches(6,1)
ax.set_axis_off()
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
fig.add_axes(ax)
ax.specgram(signaldata, Fs=samplingfreq, NFFT=1024, noverlap=0 ,cmap="gray")
imgfilename=outpath+foldername+"/"+filename[:-3]+'.png'
fig.savefig(imgfilename,bbox_inches='tight',pad_inches=0,dpi=128)
plt.close(fig)
|
5ffcd571ce4a897dea9f71a918439ae2c43c24ba
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
sangramch/Song-Genre-Classifier
|
e9e3852bb2c2edd292315af6741763b5e402f139
|
d73a5ae6d6237f4cd349466bab4fe0f60b94cac9
|
refs/heads/master
|
<repo_name>ViktoriiaDavydova/Car-Rental<file_sep>/script/RentalClients.js
const CUSTOMERS = [{
"last_name": "Morecomb",
"first_name": "Gabriel",
"address": "73 Springs Street",
"state_prov": "West Virginia",
"email": "<EMAIL>",
"phone": "304-117-8595"
},
{
"last_name": "Valder",
"first_name": "Rianon",
"address": "2846 Transport Point",
"state_prov": "California",
"email": "<EMAIL>",
"phone": "818-578-4209"
},
{
"last_name": "Densey",
"first_name": "Morley",
"address": "5 Lakeland Drive",
"state_prov": "Wisconsin",
"email": "<EMAIL>",
"phone": "262-246-2949"
},
{
"last_name": "Canton",
"first_name": "Abbye",
"address": "54 Corben Alley",
"state_prov": "Oregon",
"email": "<EMAIL>",
"phone": "971-352-4372"
},
{
"last_name": "Corriea",
"first_name": "Fairlie",
"address": "34382 Thierer Place",
"state_prov": "Colorado",
"email": "<EMAIL>",
"phone": "303-942-0983"
},
{
"last_name": "Purdon",
"first_name": "Amandy",
"address": "1222 Anderson Junction",
"state_prov": "Massachusetts",
"email": "<EMAIL>",
"phone": "978-268-1573"
},
{
"last_name": "Vannikov",
"first_name": "Baron",
"address": "313 Manufacturers Way",
"state_prov": "South Carolina",
"email": "<EMAIL>",
"phone": "803-222-8159"
},
{
"last_name": "Dumbreck",
"first_name": "Ryan",
"address": "90841 Fordem Street",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "832-855-0298"
},
{
"last_name": "Paramore",
"first_name": "Kayley",
"address": "3 International Circle",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "214-700-2022"
},
{
"last_name": "Kryszkiecicz",
"first_name": "Chic",
"address": "8254 Eggendart Pass",
"state_prov": "Pennsylvania",
"email": "<EMAIL>",
"phone": "412-461-9039"
},
{
"last_name": "Keeling",
"first_name": "Faina",
"address": "00 Maple Parkway",
"state_prov": "New York",
"email": "<EMAIL>",
"phone": "212-379-6034"
},
{
"last_name": "Bushnell",
"first_name": "Christi",
"address": "0 Anzinger Road",
"state_prov": "Missouri",
"email": "<EMAIL>",
"phone": "816-160-0798"
},
{
"last_name": "Coaker",
"first_name": "Tallulah",
"address": "61 Buhler Junction",
"state_prov": "California",
"email": "<EMAIL>",
"phone": "559-463-3909"
},
{
"last_name": "Rubartelli",
"first_name": "Frannie",
"address": "77574 Haas Court",
"state_prov": "North Carolina",
"email": "<EMAIL>",
"phone": "336-393-1035"
},
{
"last_name": "Wardall",
"first_name": "Lorena",
"address": "57 Dottie Place",
"state_prov": "Maryland",
"email": "<EMAIL>",
"phone": "443-202-3446"
},
{
"last_name": "Retallack",
"first_name": "Lexy",
"address": "5739 Mitchell Trail",
"state_prov": "New Hampshire",
"email": "<EMAIL>",
"phone": "603-459-2213"
},
{
"last_name": "Sey",
"first_name": "Burgess",
"address": "9 Roxbury Lane",
"state_prov": "Nevada",
"email": "<EMAIL>",
"phone": "775-797-3964"
},
{
"last_name": "Hauch",
"first_name": "Karoly",
"address": "8 Bellgrove Crossing",
"state_prov": "New York",
"email": "<EMAIL>",
"phone": "212-969-7921"
},
{
"last_name": "Ashburne",
"first_name": "Deane",
"address": "4 Green Place",
"state_prov": "Wisconsin",
"email": "<EMAIL>",
"phone": "608-941-5466"
},
{
"last_name": "Carnew",
"first_name": "Colette",
"address": "5088 Garrison Junction",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "915-205-9791"
},
{
"last_name": "Firth",
"first_name": "Lynett",
"address": "811 Washington Plaza",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "915-445-4681"
},
{
"last_name": "Methuen",
"first_name": "Anthe",
"address": "75 Green Circle",
"state_prov": "New Mexico",
"email": "<EMAIL>",
"phone": "505-353-5395"
},
{
"last_name": "Hulk",
"first_name": "Stu",
"address": "7 Pierstorff Pass",
"state_prov": "Georgia",
"email": "<EMAIL>",
"phone": "678-815-2528"
},
{
"last_name": "Shenton",
"first_name": "Cherilyn",
"address": "9593 Continental Junction",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "936-896-1278"
},
{
"last_name": "Ardy",
"first_name": "Ella",
"address": "966 Dahle Avenue",
"state_prov": "California",
"email": "<EMAIL>",
"phone": "949-427-2961"
},
{
"last_name": "McGlone",
"first_name": "Audie",
"address": "70384 North Alley",
"state_prov": "Maryland",
"email": "<EMAIL>",
"phone": "410-585-4491"
},
{
"last_name": "Stoakley",
"first_name": "Gradey",
"address": "103 Nobel Junction",
"state_prov": "Utah",
"email": "<EMAIL>",
"phone": "801-654-9683"
},
{
"last_name": "Berrill",
"first_name": "Charlton",
"address": "74182 Cascade Parkway",
"state_prov": "Alabama",
"email": "<EMAIL>",
"phone": "334-951-8965"
},
{
"last_name": "Harmson",
"first_name": "Rudyard",
"address": "63 Schurz Circle",
"state_prov": "Virginia",
"email": "<EMAIL>",
"phone": "804-665-3300"
},
{
"last_name": "East",
"first_name": "Nick",
"address": "9 Magdeline Pass",
"state_prov": "Mississippi",
"email": "<EMAIL>",
"phone": "601-993-9105"
},
{
"last_name": "Corstan",
"first_name": "Ange",
"address": "94 Gerald Park",
"state_prov": "New York",
"email": "<EMAIL>",
"phone": "716-276-8420"
},
{
"last_name": "Creegan",
"first_name": "Taffy",
"address": "080 Petterle Drive",
"state_prov": "Illinois",
"email": "<EMAIL>",
"phone": "630-632-7408"
},
{
"last_name": "Tollmache",
"first_name": "Adda",
"address": "12776 Meadow Ridge Circle",
"state_prov": "New York",
"email": "<EMAIL>",
"phone": "347-584-2505"
},
{
"last_name": "Reyne",
"first_name": "Gae",
"address": "1946 Ridge Oak Hill",
"state_prov": "Massachusetts",
"email": "<EMAIL>",
"phone": "617-727-1730"
},
{
"last_name": "Elsbury",
"first_name": "Neal",
"address": "8931 Luster Way",
"state_prov": "Illinois",
"email": "<EMAIL>",
"phone": "312-232-9960"
},
{
"last_name": "Elizabeth",
"first_name": "Benjamen",
"address": "29472 Manitowish Court",
"state_prov": "Massachusetts",
"email": "<EMAIL>",
"phone": "508-917-3497"
},
{
"last_name": "Gerren",
"first_name": "Keefe",
"address": "670 Scott Avenue",
"state_prov": "Colorado",
"email": "<EMAIL>",
"phone": "303-277-7706"
},
{
"last_name": "Pratchett",
"first_name": "Denys",
"address": "3 Muir Way",
"state_prov": "Arizona",
"email": "<EMAIL>",
"phone": "480-286-3253"
},
{
"last_name": "Swindin",
"first_name": "Clemmy",
"address": "46856 Lukken Place",
"state_prov": "New York",
"email": "<EMAIL>",
"phone": "716-840-8595"
},
{
"last_name": "Allitt",
"first_name": "Marline",
"address": "53829 Ridgeview Park",
"state_prov": "Utah",
"email": "<EMAIL>",
"phone": "801-359-2079"
},
{
"last_name": "Halfacre",
"first_name": "Jenna",
"address": "62236 Mifflin Place",
"state_prov": "Florida",
"email": "<EMAIL>",
"phone": "727-844-0698"
},
{
"last_name": "Surby",
"first_name": "Debbie",
"address": "0 Laurel Place",
"state_prov": "Florida",
"email": "<EMAIL>",
"phone": "305-892-0728"
},
{
"last_name": "Durning",
"first_name": "Ethelda",
"address": "7 Oneill Road",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "915-140-8566"
},
{
"last_name": "Gaskal",
"first_name": "Ollie",
"address": "94 Clove Drive",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "210-189-5389"
},
{
"last_name": "<NAME>",
"first_name": "Kristy",
"address": "9866 Lillian Way",
"state_prov": "Florida",
"email": "<EMAIL>",
"phone": "305-661-1858"
},
{
"last_name": "Iori",
"first_name": "Ad",
"address": "7811 Mesta Center",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "214-477-7446"
},
{
"last_name": "Crimmins",
"first_name": "Ben",
"address": "6365 Clove Point",
"state_prov": "Washington",
"email": "<EMAIL>",
"phone": "253-671-7504"
},
{
"last_name": "Paige",
"first_name": "Barry",
"address": "8951 Derek Plaza",
"state_prov": "Florida",
"email": "<EMAIL>",
"phone": "321-401-9109"
},
{
"last_name": "Kitchaside",
"first_name": "Arley",
"address": "4375 Summer Ridge Lane",
"state_prov": "Virginia",
"email": "<EMAIL>",
"phone": "703-939-4713"
},
{
"last_name": "Kemer",
"first_name": "Olly",
"address": "38698 Kropf Parkway",
"state_prov": "Washington",
"email": "<EMAIL>",
"phone": "360-216-9898"
},
{
"last_name": "Bream",
"first_name": "Elizabeth",
"address": "777 Moland Street",
"state_prov": "Alabama",
"email": "<EMAIL>",
"phone": "334-396-0354"
},
{
"last_name": "Ceschi",
"first_name": "Zared",
"address": "8 Huxley Hill",
"state_prov": "Pennsylvania",
"email": "<EMAIL>",
"phone": "412-124-0363"
},
{
"last_name": "Bradock",
"first_name": "Rochelle",
"address": "526 Rusk Avenue",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "915-394-2800"
},
{
"last_name": "Parkins",
"first_name": "Marcy",
"address": "93437 Fallview Road",
"state_prov": "California",
"email": "<EMAIL>",
"phone": "559-193-3117"
},
{
"last_name": "Shortcliffe",
"first_name": "Gael",
"address": "2 Old Shore Way",
"state_prov": "Florida",
"email": "<EMAIL>",
"phone": "786-704-8953"
},
{
"last_name": "Doudney",
"first_name": "Quillan",
"address": "13897 Gateway Alley",
"state_prov": "Georgia",
"email": "<EMAIL>",
"phone": "404-654-0181"
},
{
"last_name": "Crollman",
"first_name": "Marijn",
"address": "2516 Elka Plaza",
"state_prov": "Minnesota",
"email": "<EMAIL>",
"phone": "651-335-1062"
},
{
"last_name": "Danzelman",
"first_name": "Quinton",
"address": "1 Lunder Trail",
"state_prov": "Michigan",
"email": "<EMAIL>",
"phone": "734-535-6440"
},
{
"last_name": "Gilchriest",
"first_name": "Murry",
"address": "6 Gerald Drive",
"state_prov": "Illinois",
"email": "<EMAIL>",
"phone": "847-739-1825"
},
{
"last_name": "Claypole",
"first_name": "Maris",
"address": "1243 Grasskamp Park",
"state_prov": "New Mexico",
"email": "<EMAIL>",
"phone": "505-290-7244"
},
{
"last_name": "Pallasch",
"first_name": "Emalee",
"address": "19953 Golf Park",
"state_prov": "California",
"email": "<EMAIL>",
"phone": "650-776-6906"
},
{
"last_name": "Tankard",
"first_name": "Ivan",
"address": "848 Merchant Point",
"state_prov": "Missouri",
"email": "<EMAIL>",
"phone": "816-179-7122"
},
{
"last_name": "Didsbury",
"first_name": "Gallard",
"address": "12 Cherokee Lane",
"state_prov": "Louisiana",
"email": "<EMAIL>",
"phone": "318-505-7100"
},
{
"last_name": "Rhodef",
"first_name": "Esmaria",
"address": "74795 Graceland Way",
"state_prov": "New Jersey",
"email": "<EMAIL>",
"phone": "609-800-0751"
},
{
"last_name": "Gowen",
"first_name": "Claudell",
"address": "7 Roxbury Street",
"state_prov": "Nevada",
"email": "<EMAIL>",
"phone": "775-101-3639"
},
{
"last_name": "Scally",
"first_name": "Corbett",
"address": "26607 Sullivan Point",
"state_prov": "North Carolina",
"email": "<EMAIL>",
"phone": "336-980-3337"
},
{
"last_name": "Shoebottom",
"first_name": "Madel",
"address": "31482 Butterfield Road",
"state_prov": "New York",
"email": "<EMAIL>",
"phone": "518-724-9549"
},
{
"last_name": "Pickin",
"first_name": "Kaye",
"address": "5733 5th Hill",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "512-263-5115"
},
{
"last_name": "Theunissen",
"first_name": "Electra",
"address": "55424 Erie Plaza",
"state_prov": "Georgia",
"email": "<EMAIL>",
"phone": "706-862-6443"
},
{
"last_name": "Byer",
"first_name": "Bridget",
"address": "7 Eggendart Park",
"state_prov": "Massachusetts",
"email": "<EMAIL>",
"phone": "617-709-7221"
},
{
"last_name": "Catterick",
"first_name": "Ann-marie",
"address": "5 Independence Court",
"state_prov": "Alabama",
"email": "<EMAIL>",
"phone": "251-276-2797"
},
{
"last_name": "Hagergham",
"first_name": "Anselma",
"address": "49 Prairie Rose Terrace",
"state_prov": "Iowa",
"email": "<EMAIL>",
"phone": "515-244-8767"
},
{
"last_name": "Danieli",
"first_name": "Amity",
"address": "26 Jana Avenue",
"state_prov": "Alabama",
"email": "<EMAIL>",
"phone": "205-629-3978"
},
{
"last_name": "Bawme",
"first_name": "Janeen",
"address": "32 Homewood Trail",
"state_prov": "Florida",
"email": "<EMAIL>",
"phone": "352-693-3276"
},
{
"last_name": "Abelovitz",
"first_name": "Rubin",
"address": "2046 5th Street",
"state_prov": "Pennsylvania",
"email": "<EMAIL>",
"phone": "215-234-9892"
},
{
"last_name": "Sebrook",
"first_name": "Britt",
"address": "16050 Summerview Street",
"state_prov": "Wisconsin",
"email": "<EMAIL>",
"phone": "920-707-1467"
},
{
"last_name": "Orsman",
"first_name": "Sanson",
"address": "3 Hooker Hill",
"state_prov": "Kentucky",
"email": "<EMAIL>",
"phone": "859-840-4184"
},
{
"last_name": "Gissop",
"first_name": "Devon",
"address": "4149 Eggendart Park",
"state_prov": "Virginia",
"email": "<EMAIL>",
"phone": "571-758-6318"
},
{
"last_name": "Gilbee",
"first_name": "Quentin",
"address": "99 Hanover Drive",
"state_prov": "California",
"email": "<EMAIL>",
"phone": "619-583-2054"
},
{
"last_name": "Harner",
"first_name": "Brynn",
"address": "796 Tennessee Street",
"state_prov": "California",
"email": "<EMAIL>",
"phone": "562-466-4278"
},
{
"last_name": "Scarbarrow",
"first_name": "Lowrance",
"address": "757 Atwood Junction",
"state_prov": "Alabama",
"email": "<EMAIL>",
"phone": "334-174-5925"
},
{
"last_name": "Tasch",
"first_name": "Ronnie",
"address": "63366 Di Loreto Court",
"state_prov": "Georgia",
"email": "<EMAIL>",
"phone": "706-446-9334"
},
{
"last_name": "Pattillo",
"first_name": "Dolf",
"address": "79 Ridge Oak Road",
"state_prov": "Missouri",
"email": "<EMAIL>",
"phone": "816-939-5130"
},
{
"last_name": "Tolomelli",
"first_name": "Jeana",
"address": "55 Goodland Terrace",
"state_prov": "New York",
"email": "<EMAIL>",
"phone": "315-432-1023"
},
{
"last_name": "McMychem",
"first_name": "Isidoro",
"address": "344 Laurel Trail",
"state_prov": "District of Columbia",
"email": "<EMAIL>",
"phone": "202-274-6829"
},
{
"last_name": "MacDonough",
"first_name": "Willi",
"address": "06 Hansons Terrace",
"state_prov": "Georgia",
"email": "<EMAIL>",
"phone": "770-181-2995"
},
{
"last_name": "Cow",
"first_name": "Clerissa",
"address": "533 Kim Trail",
"state_prov": "Virginia",
"email": "<EMAIL>",
"phone": "571-904-4083"
},
{
"last_name": "Lalonde",
"first_name": "Terza",
"address": "61336 Melody Park",
"state_prov": "Massachusetts",
"email": "<EMAIL>",
"phone": "508-140-1215"
},
{
"last_name": "Gregon",
"first_name": "Evyn",
"address": "8 Monterey Terrace",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "214-461-1733"
},
{
"last_name": "Vala",
"first_name": "Ira",
"address": "1 Esker Way",
"state_prov": "South Dakota",
"email": "<EMAIL>",
"phone": "605-161-7528"
},
{
"last_name": "Corhard",
"first_name": "Davidson",
"address": "566 Michigan Center",
"state_prov": "Iowa",
"email": "<EMAIL>",
"phone": "319-865-3218"
},
{
"last_name": "McCarrison",
"first_name": "Sascha",
"address": "26 Northland Way",
"state_prov": "Minnesota",
"email": "<EMAIL>",
"phone": "651-448-6623"
},
{
"last_name": "Haime",
"first_name": "Wernher",
"address": "06862 Grayhawk Parkway",
"state_prov": "Utah",
"email": "<EMAIL>",
"phone": "801-935-3338"
},
{
"last_name": "Laurentin",
"first_name": "Harley",
"address": "43 Judy Pass",
"state_prov": "Ohio",
"email": "<EMAIL>",
"phone": "614-838-1378"
},
{
"last_name": "Fuidge",
"first_name": "Joela",
"address": "82427 Westend Terrace",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "254-104-6726"
},
{
"last_name": "<NAME>",
"first_name": "Ettore",
"address": "14021 Forest Circle",
"state_prov": "Arkansas",
"email": "<EMAIL>",
"phone": "501-406-6448"
},
{
"last_name": "Titterington",
"first_name": "Melli",
"address": "63461 Burrows Place",
"state_prov": "California",
"email": "<EMAIL>",
"phone": "415-952-2825"
},
{
"last_name": "Wiltshire",
"first_name": "Cissiee",
"address": "5372 Golf Trail",
"state_prov": "Massachusetts",
"email": "<EMAIL>",
"phone": "617-509-4738"
},
{
"last_name": "Padilla",
"first_name": "Mike",
"address": "3 Northwestern Lane",
"state_prov": "New York",
"email": "<EMAIL>",
"phone": "716-259-9814"
},
{
"last_name": "Ryman",
"first_name": "Donella",
"address": "365 Sundown Avenue",
"state_prov": "California",
"email": "<EMAIL>",
"phone": "619-175-8671"
},
{
"last_name": "Union",
"first_name": "Eugenie",
"address": "092 Elka Parkway",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "972-987-3730"
},
{
"last_name": "Strickland",
"first_name": "Gillan",
"address": "31815 Manley Lane",
"state_prov": "Florida",
"email": "<EMAIL>",
"phone": "352-688-2637"
},
{
"last_name": "Prigmore",
"first_name": "Dar",
"address": "9815 Tennessee Lane",
"state_prov": "Pennsylvania",
"email": "<EMAIL>",
"phone": "215-514-1973"
},
{
"last_name": "McHale",
"first_name": "Storm",
"address": "5605 Larry Place",
"state_prov": "New York",
"email": "<EMAIL>",
"phone": "917-695-1376"
},
{
"last_name": "Haith",
"first_name": "Erie",
"address": "247 Valley Edge Terrace",
"state_prov": "California",
"email": "<EMAIL>",
"phone": "916-144-2141"
},
{
"last_name": "Matthewman",
"first_name": "Harley",
"address": "717 Onsgard Plaza",
"state_prov": "South Carolina",
"email": "<EMAIL>",
"phone": "843-662-8144"
},
{
"last_name": "Byllam",
"first_name": "Jemmy",
"address": "0257 Shasta Point",
"state_prov": "Georgia",
"email": "<EMAIL>",
"phone": "706-163-8463"
},
{
"last_name": "Morgan",
"first_name": "Lorry",
"address": "9 Village Plaza",
"state_prov": "District of Columbia",
"email": "<EMAIL>",
"phone": "202-113-2279"
},
{
"last_name": "Rickert",
"first_name": "Neala",
"address": "81 Reinke Crossing",
"state_prov": "Delaware",
"email": "<EMAIL>",
"phone": "302-275-1707"
},
{
"last_name": "Piddocke",
"first_name": "Shea",
"address": "7 Burning Wood Drive",
"state_prov": "West Virginia",
"email": "<EMAIL>",
"phone": "304-305-0117"
},
{
"last_name": "Delaprelle",
"first_name": "Prent",
"address": "0 Rieder Park",
"state_prov": "Georgia",
"email": "<EMAIL>",
"phone": "404-976-4429"
},
{
"last_name": "Shearston",
"first_name": "Harri",
"address": "94 Homewood Place",
"state_prov": "Pennsylvania",
"email": "<EMAIL>",
"phone": "412-119-3318"
},
{
"last_name": "Tumbridge",
"first_name": "Renata",
"address": "09363 Leroy Junction",
"state_prov": "Washington",
"email": "<EMAIL>",
"phone": "509-569-3172"
},
{
"last_name": "Knotton",
"first_name": "Dianne",
"address": "1 Lunder Point",
"state_prov": "Washington",
"email": "<EMAIL>",
"phone": "425-358-8289"
},
{
"last_name": "McCumesky",
"first_name": "Yorgo",
"address": "88 Summer Ridge Terrace",
"state_prov": "Oklahoma",
"email": "<EMAIL>",
"phone": "405-172-1692"
},
{
"last_name": "Ventris",
"first_name": "Ruthe",
"address": "5790 Helena Way",
"state_prov": "California",
"email": "<EMAIL>",
"phone": "415-379-9101"
},
{
"last_name": "Staterfield",
"first_name": "Claiborn",
"address": "17 Grasskamp Hill",
"state_prov": "Ohio",
"email": "<EMAIL>",
"phone": "513-300-1610"
},
{
"last_name": "Manis",
"first_name": "Reagen",
"address": "1 Ohio Center",
"state_prov": "Ohio",
"email": "<EMAIL>",
"phone": "419-393-8995"
},
{
"last_name": "Isaksson",
"first_name": "Brett",
"address": "81 Northview Parkway",
"state_prov": "Georgia",
"email": "<EMAIL>",
"phone": "404-688-7148"
},
{
"last_name": "Barham",
"first_name": "Melanie",
"address": "6 Bartillon Road",
"state_prov": "Virginia",
"email": "<EMAIL>",
"phone": "757-168-3622"
},
{
"last_name": "Addey",
"first_name": "Amandy",
"address": "35944 Meadow Vale Lane",
"state_prov": "Pennsylvania",
"email": "<EMAIL>",
"phone": "215-207-0312"
},
{
"last_name": "Bardell",
"first_name": "Britta",
"address": "14643 Florence Junction",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "469-791-4456"
},
{
"last_name": "<NAME>",
"first_name": "Alexia",
"address": "9 Rieder Crossing",
"state_prov": "Missouri",
"email": "<EMAIL>",
"phone": "573-661-5466"
},
{
"last_name": "Vaan",
"first_name": "Twyla",
"address": "966 Summer Ridge Point",
"state_prov": "Tennessee",
"email": "<EMAIL>",
"phone": "901-656-1881"
},
{
"last_name": "O'Luney",
"first_name": "Orlando",
"address": "5362 Maywood Avenue",
"state_prov": "Michigan",
"email": "<EMAIL>",
"phone": "616-717-3242"
},
{
"last_name": "Duddridge",
"first_name": "Gerek",
"address": "24 Arapahoe Center",
"state_prov": "Georgia",
"email": "<EMAIL>",
"phone": "404-701-8413"
},
{
"last_name": "Dorricott",
"first_name": "Denys",
"address": "489 Myrtle Crossing",
"state_prov": "Florida",
"email": "<EMAIL>",
"phone": "850-516-4258"
},
{
"last_name": "Lawman",
"first_name": "Esra",
"address": "413 Grayhawk Court",
"state_prov": "South Carolina",
"email": "<EMAIL>",
"phone": "843-678-5150"
},
{
"last_name": "Ibbs",
"first_name": "Rene",
"address": "3902 Shoshone Terrace",
"state_prov": "Michigan",
"email": "<EMAIL>",
"phone": "810-271-2177"
},
{
"last_name": "Fourmy",
"first_name": "Laverne",
"address": "8700 Merchant Street",
"state_prov": "New Mexico",
"email": "<EMAIL>",
"phone": "505-414-0681"
},
{
"last_name": "Holhouse",
"first_name": "Ward",
"address": "46 Sommers Avenue",
"state_prov": "Utah",
"email": "<EMAIL>",
"phone": "801-463-5309"
},
{
"last_name": "Ellington",
"first_name": "Berne",
"address": "71801 Anhalt Way",
"state_prov": "Colorado",
"email": "<EMAIL>",
"phone": "303-251-8415"
},
{
"last_name": "Osgerby",
"first_name": "Benton",
"address": "87 Trailsway Trail",
"state_prov": "Florida",
"email": "<EMAIL>",
"phone": "239-591-2906"
},
{
"last_name": "Heinssen",
"first_name": "Madelyn",
"address": "5601 Knutson Terrace",
"state_prov": "California",
"email": "<EMAIL>",
"phone": "510-352-2921"
},
{
"last_name": "Laverenz",
"first_name": "Winni",
"address": "188 2nd Alley",
"state_prov": "South Dakota",
"email": "<EMAIL>",
"phone": "605-325-1845"
},
{
"last_name": "Switland",
"first_name": "Freemon",
"address": "127 Continental Alley",
"state_prov": "North Carolina",
"email": "<EMAIL>",
"phone": "704-755-0181"
},
{
"last_name": "Diggles",
"first_name": "Linc",
"address": "2 Elgar Pass",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "830-273-2634"
},
{
"last_name": "Everest",
"first_name": "Cristina",
"address": "9871 Hooker Road",
"state_prov": "Alabama",
"email": "<EMAIL>",
"phone": "334-280-3671"
},
{
"last_name": "Huish",
"first_name": "Elinore",
"address": "8039 Johnson Crossing",
"state_prov": "California",
"email": "<EMAIL>",
"phone": "661-978-0011"
},
{
"last_name": "Broxis",
"first_name": "Benjamin",
"address": "2 Sutteridge Hill",
"state_prov": "Georgia",
"email": "<EMAIL>",
"phone": "770-859-9197"
},
{
"last_name": "Vannuccini",
"first_name": "Gasparo",
"address": "784 Lakewood <NAME>",
"state_prov": "Texas",
"email": "<EMAIL>",
"phone": "713-582-3140"
},
{
"last_name": "Ketteridge",
"first_name": "Raina",
"address": "946 Farragut Lane",
"state_prov": "South Carolina",
"email": "<EMAIL>",
"phone": "803-941-4186"
},
{
"last_name": "Jonas",
"first_name": "Dodi",
"address": "32197 Crownhardt Way",
"state_prov": "Pennsylvania",
"email": "<EMAIL>",
"phone": "717-302-8054"
},
{
"last_name": "Stainbridge",
"first_name": "Karlan",
"address": "81 Dennis Street",
"state_prov": "Tennessee",
"email": "<EMAIL>",
"phone": "901-342-1843"
},
{
"last_name": "Grenville",
"first_name": "Arielle",
"address": "4451 Westerfield Junction",
"state_prov": "Indiana",
"email": "<EMAIL>",
"phone": "260-617-4474"
},
{
"last_name": "Rudolf",
"first_name": "Elspeth",
"address": "545 High Crossing Court",
"state_prov": "Connecticut",
"email": "<EMAIL>",
"phone": "203-956-6161"
},
{
"last_name": "Marrill",
"first_name": "Carolan",
"address": "019 Barnett Pass",
"state_prov": "New York",
"email": "<EMAIL>",
"phone": "518-655-5562"
},
{
"last_name": "Martignon",
"first_name": "Nealon",
"address": "5538 Arapahoe Terrace",
"state_prov": "Alabama",
"email": "<EMAIL>",
"phone": "205-361-2364"
},
{
"last_name": "Callar",
"first_name": "Kaleena",
"address": "7 Washington Plaza",
"state_prov": "Missouri",
"email": "<EMAIL>",
"phone": "314-580-6946"
},
{
"last_name": "Doyle",
"first_name": "Meriel",
"address": "4 Coolidge Place",
"state_prov": "California",
"email": "<EMAIL>",
"phone": "714-826-5771"
}
]<file_sep>/script/script.js
"use strict";
var results = "";
var customer = "";
function search() {
var output = "";
const qInput = document.querySelector("#qInput");
const qValue = qInput.value.trim();
if (!qValue) {
return;
}
output = document.getElementById("searchresult");
output.innerHTML = "";
results = CUSTOMERS.filter(customer => {
return customer.last_name.toUpperCase().startsWith(qValue.toUpperCase());
});
for (let customer of results) {
var breakTag = document.createElement("br");
var btn = document.createElement("button");
btn.style.width = '200px';
btn.name = 'customerButton';
btn.setAttribute("onclick", "enableForm(this);");
btn.setAttribute("data-btnid", customer.last_name);
btn.innerHTML += customer.first_name + " " + customer.last_name;
document.getElementById('searchresult').appendChild(btn);
document.getElementById('searchresult').appendChild(breakTag);
}
}
function enableForm(btn) {
document.querySelector("#orderinfo").innerHTML = "";
for (let CUSTOMERS of results) {
if (btn.getAttribute("data-btnid") === CUSTOMERS.last_name) {
document.getElementById("carsize").disabled = false;
document.getElementById("bicyclerack").disabled = false;
document.getElementById("gps").disabled = false;
document.getElementById("childseat").disabled = false;
document.getElementById("duration").disabled = false;
document.getElementById("calculateprice").disabled = false;
document.getElementById("fName").innerText = CUSTOMERS.first_name;
document.getElementById("lName").innerText = CUSTOMERS.last_name + " ";
document.getElementById("adr").innerText = CUSTOMERS.address;
document.getElementById("stProv").innerText = CUSTOMERS.state_prov;
document.getElementById("emails").innerText = CUSTOMERS.email;
document.getElementById("tel").innerText = CUSTOMERS.phone;
}
}
}
function calculateOrder() {
if (document.getElementById('duration').value < 1) {
document.getElementById('duration').value = 1;
} else if (document.getElementById('duration').value > 30) {
document.getElementById('duration').value = 30;
}
var orderList = document.querySelector("#orderinfo");
orderList.innerHTML = "";
var carSizeSelector = document.getElementById('carsize');
var carSizePrice = carSizeSelector[carSizeSelector.selectedIndex].value;
var rentPeriod = document.querySelector("input[name = quantity]").value;
var orderTotal = 0;
var additon = "";
var carType = "";
if (carSizeSelector[carSizeSelector.selectedIndex].value == '15') {
carType = 'Compact';
}
if (carSizeSelector[carSizeSelector.selectedIndex].value == '20') {
carType = 'Mid-size';
}
if (carSizeSelector[carSizeSelector.selectedIndex].value == '35') {
carType = 'Luxury';
}
if (carSizeSelector[carSizeSelector.selectedIndex].value == '40') {
carType = 'Van/Truck';
}
if (document.querySelector('input[name=bicycleRack]:checked')) {
additon += "Roof Rack or Bicycle Rack $" + (document.getElementById('bicyclerack').value) * rentPeriod + "<br>";
orderTotal += (document.getElementById('bicyclerack').value) * rentPeriod;
}
if (document.querySelector('input[name=GPS]:checked')) {
additon += "GPS $" + (document.getElementById('gps').value) + "<br>";
orderTotal += parseInt(document.getElementById('gps').value);
}
if (document.querySelector('input[name=childSeat]:checked')) {
additon += "Child Seat $" + (document.getElementById('childseat').value) + "<br>";
orderTotal += parseInt(document.getElementById('childseat').value);
}
orderTotal += carSizePrice * rentPeriod;
orderList.innerHTML = 'Your Order Information:' + "<br>" + document.getElementById("lName").innerText + " " +
document.getElementById("fName").innerText + "<br>" + document.getElementById("adr").innerText + "<br>" +
document.getElementById("stProv").innerText + "<br>" + document.getElementById("emails").innerText + "<br>" +
document.getElementById("tel").innerText + "<br><br>";
orderList.innerHTML += "Car type " + carType + " $" +
carSizePrice * rentPeriod + "<br>" + additon + "<br>";
orderList.innerHTML += "Your order final Price" + "<br>" + "for " + rentPeriod + " days is " + "$" +
orderTotal;
}
<file_sep>/README.md
# Car-Rental
Small School Project
|
9b9e5dd211d72342764e9bb9a8f15d9e70ce47c0
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
ViktoriiaDavydova/Car-Rental
|
fa1bda54f38f40943aa3bc17c4355643131413e1
|
86a2b78f135f5d91180c394ab0f2b86df23ec0ea
|
refs/heads/master
|
<repo_name>Bracketeers/web-collective<file_sep>/react-redux-scss/src/redux/actions/TestAction.ts
export function TestAction(name : string) {
return {
type: "TEST_ACTION",
name: name
};
}<file_sep>/README.md
# web-collective
A collection of boilerplate web projects
<file_sep>/react-redux-scss/src/redux/reducers/TestReducer.ts
import { ITestObject } from "../Store";
function testReducerMethod(stateTestObject : ITestObject = {name: ""}, action) {
if(action.type == "TEST_ACTION") {
let newObj : ITestObject = {...stateTestObject};
newObj.name = action.name;
return newObj;
}
return {...stateTestObject};
}
export default testReducerMethod;<file_sep>/vanilla-scss/src/tests/Sum.ts
function Sum(x : number, y : number) : number {
return x + y;
}
export default Sum;<file_sep>/react-redux-scss/src/redux/Store.ts
import { createStore, applyMiddleware, compose } from "redux";
import CombinedReducers from "./reducers/index";
export interface ITestObject {
name : string
}
export interface IStoreDispatch {
TestAction(name : string);
}
export interface IStoreModel {
testObject : ITestObject;
}
//combined interface for easy include in React Components
export interface IStore extends IStoreDispatch, IStoreModel {
}
const defaultModel : IStoreModel = {
testObject: {
name: ""
}
};
const enhancers = compose(
window["devToolsExtension"] ? window["devToolsExtension"]() : f => f
);
const store = createStore(CombinedReducers, defaultModel, enhancers);
if(module["hot"]) {
module["hot"].accept("./reducers", () => {
const nextRootReducer = require("./reducers/index").default;
store.replaceReducer(nextRootReducer);
});
}
export default store;<file_sep>/vanilla-scss/src/Main.ts
import "../scss/main.scss";
let node : HTMLParagraphElement = document.createElement("p");
node.textContent = "Hello There!";
document.getElementById("app").appendChild(node);
|
16af76649feb2926212812d3ec4770e66982b625
|
[
"Markdown",
"TypeScript"
] | 6
|
TypeScript
|
Bracketeers/web-collective
|
0966089327b656bc183e7edf93010531a7a1cf3e
|
8c282ec17a46501c9ba875e39163a1f51330a7b5
|
refs/heads/master
|
<repo_name>zipkinlab/Rossman_etal_2016_EcolAndEvol<file_sep>/dolphin_example_wrapper.R
############################################################
# Dolphin Case Study Wrapper
############################################################
# 1.) Section 1: Libraries and functions
# 2.) Section 2: JAGS Model
# 3.) Section 3: Data Processing and JAGS run
# 4.) Section 4: Results post processing
# 5.) Section 5: Graphing
############################################################
# Section 1: libraries and functions
############################################################
# load needed libraries
library(MASS)
library(clusterGeneration)
library(repmis)
library(rgl)
library(shape)
library(magick)
library(jagsUI) # to run jags
#Function to calcuate SEV
SEV.function<-function(sigma) {
if (eigen(sigma)$values[3] > 0)
{
axises<-sqrt(eigen(sigma)$values)
}
else {
axises<-NA
}
#out<-list()
#out$a<-axises[1]
#out$b<-axises[2]
#out$c<-axises[3]
#out$SEV<-prod(axises,pi,4/3)
return(prod(axises,pi))
}
# Calculate convex hull
hull<-function (x, y)
{
chI <- chull(x, y)
chI <- c(chI, chI[1])
hullx <- x[chI]
hully <- y[chI]
out<- list()
out$x<-hullx
out$y<-hully
out
}
# calculate standard ellipse area
SEA.function<-function(sigma) {
axises<-sqrt(eigen(sigma)$values)
out<-list()
out$a<-axises[1]
out$b<-axises[2]
out$SEV<-prod(axises,pi)
return(out)
}
# calculate distance between two points in 3D
distance<-function(a,b){
l<-sqrt((a[,1]-b[,1])^2+(a[,2]-b[,2])^2)
return(l)
}
# shortcut for quantile calculation
quants<-function(x){
quantile(x,probs=c(0.025,0.5,0.975),na.rm=TRUE)
}
# calculate mode
mode <- function(s) {
d <- density(s,na.rm=TRUE)
d$x[which.max(d$y)]
}
# Functions for ellipsoid overlap
MVNdist <- function(mu,S){function(x){t(x-mu)%*%solve(S)%*%(x-mu)}}
CubeCount3D <- function(mu1,mu2,S1,S2,HowFine=1.0,ShowProgress=TRUE){
# set-up stuff:
OneStep <- 10^(-HowFine)
CubeVol <- OneStep^3
CubeCt <- 0
A1 <- eigen(S1)$vect
dD1 <- eigen(S1)$val
MVNdist2 <- MVNdist(mu2,S2)
# the loops:
zlist <- seq(from=0,to=dD1[2]^.5,by=OneStep)
zlist <- if(length(zlist)>1){c(rev(-zlist),zlist[2:length(zlist)])}
for(Z in zlist){
yBd <- (dD1[2]*(1-Z^2/dD1[3]))^.5
# if(is.nan(yBd)|is.na(yBd)){errorlog <- c(errorlog,list(yBd,Z))}
ylist <- seq(from=0,to=yBd,by=OneStep)
ylist <- if(length(ylist)>1){c(rev(-ylist),ylist[2:length(ylist)])}
for(Y in ylist){
xBd <- (dD1[1]*(1-Y^2/dD1[2]-Z^2/dD1[3]))^.5
# if(is.nan(xBd)|is.na(xBd)){errorlog <- c(errorlog,list(xBd,Y,Z))}
xlist <- seq(from=0,to=xBd,by=OneStep)
xlist <- if(length(xlist)>1){c(rev(-xlist),xlist[2:length(xlist)])}
for(X in xlist){
if(MVNdist2(A1%*%c(X,Y,Z)+mu1)<1){CubeCt=CubeCt+1}
}
}
# This will show a "progress report" in the console window as this script is running:
# (0=start, 1=end)
if(ShowProgress){print((.5*(Z+dD1[3]^.5))/dD1[3]^.5)}
}
return(CubeCt*CubeVol)
}
############################################################
# Section 2: Model File
############################################################
sink("Dolphin_example.txt")
cat("
model{
#priors
for (k in 1:nGroups){
# Mean Vector
mu[k,1] ~ dnorm(0,0.001)
mu[k,2] ~ dnorm(0,0.001)
mu[k,3] ~ dnorm(0,0.001)
# Covariance Matrix
prec[1:3,1:3,k] ~ dwish(S3,4)
cov[1:3,1:3,k] <- inverse(prec[1:3,1:3,k])
}#k
#likelihood
for (i in 1:obs){
y[i,1:3] ~ dmnorm(mu[stock[i],],prec[,,stock[i]])
}#i
}
",fill = TRUE)
sink()
############################################################
# Section 3: Data Processing and JAGS Run
############################################################
# Read in data
# Other data files can be used but formated as [observations, c(group, isotope1, isotope2....)]
dolphin<-as.data.frame(matrix(c(
"G", -10.533, 11.513, 7.2,
"G", -11.665, 13.495, 8.7,
"G", -12.66, 11.928, 9.2,
"G", -13.734, 12.814, 9.9,
"G", -12.61, 12.736, 10.1,
"G", -11.723, 12.877, 11.6,
"G", -11.223, 12.179, 12.7,
"G", -10.953, 12.787, 12.8,
"G", -12.7, 12.132, 15,
"G", -12.381, 12.537, 15.7,
"IN", -10.482, 11.049, 4.5,
"IN", -11.727, 11.956, 6.2,
"IN", -10.53, 10.82, 7.9,
"IN", -11.592, 12.56, 10.2,
"IN", -10.54, 11.69, 5.5,
"IN", -13.63, 11.794, 5.8,
"IN", -8.23, 10.906, 6,
"IN", -11.47, 11.83, 6.1,
"IN", -8.27, 10.561, 6.1,
"IN", -8.48, 10.33, 6.4,
"IN", -8.797, 12.949, 6.7,
"IN", -8.85, 13.694, 7,
"IN", -10, 11.3, 7.5,
"IN", -12.2, 11.6, 8.3,
"IN", -12.413, 15.838, 8.8,
"IN", -12.584, 14.672, 8.8,
"IN", -12.22, 12.57, 9.2,
"OFF", -11.085, 11.833, 7,
"OFF", -12.134, 12.764, 13.8,
"OFF", -10.447, 12.503, 15.7,
"OFF", -13.992, 14.04, 15.9,
"OFF", -12.46, 12.53, 15.9,
"OFF", -11.392, 14.743, 16.8,
"OFF", -11.237, 13.312, 17,
"OFF", -12.637, 13.277, 17.8,
"OFF", -12.941, 13.578, 18.4), ncol=4, byrow = TRUE))
colnames(dolphin)<-c("Stock", "d13C", "d15N", "d34S")
dolphin[,2:ncol(dolphin)]<-apply(dolphin[,2:ncol(dolphin)], 2, as.numeric)
# Make objects for jags
nIsotopes<-ncol(dolphin)-1
isotope.names<-colnames(dolphin)[-1]
stock.names<-unique(dolphin$Stock)
nGroups<-length(stock.names)
obs<-nrow(dolphin)
stock<-as.numeric(as.factor(dolphin$Stock))
#package the data
jags.data=list(y=as.matrix(dolphin[,2:(nIsotopes+1)]),
nGroups=nGroups, obs=obs, S3=(diag(3)*3),
stock=stock)
# Provide intial values for covariance matrix
init.prec<-array(NA, dim=c(nIsotopes,nIsotopes,nGroups))
for (i in 1:nGroups){
temp<-colMeans(apply(dolphin[,2:(nIsotopes+1)], 2, as.numeric))
init.prec[,,i]<-cov(cbind(rnorm(5,temp[1],5),rnorm(5,temp[2],5),rnorm(5,temp[3],5)))
}
inits=function(){list( prec=init.prec)}
# Parameters to save
params<-c("mu","cov")
# MCMC settings
nt <- 5
nb <- 10000
nc <- 3
na<-10000
ni <- 20000
# Run Jags
out <- jags(data = jags.data,
#inits = inits,
parameters.to.save = params,
model.file = "Dolphin_example.txt",
n.chains = nc,
n.adapt = na,
n.iter = ni,
n.burnin = nb,
n.thin = nt#,parallel=TRUE
)
# Check trace
#traceplot(out)
# Summary
out
############################################################
# Section 4: Results Post Processing
############################################################
# Calculate SEV
SEV<-matrix(NA,ncol=nGroups,nrow=nrow(out$sims.list$cov))
SEV.summary<-matrix(NA,nrow=nGroups,ncol=5)
colnames(SEV.summary)<-c("n","2.5","50.0","97.5","mode")
for (k in 1:nGroups){
SEV[,k]<-apply(out$sims.list$cov[,,,k],c(1),SEV.function)
SEV.summary[k,]<-c(sum(dolphin$Stock==stock.names[k]),quants(SEV[,k]),mode(SEV[,k]))
}
rownames(SEV.summary)<-stock.names
colnames(SEV.summary)<-c("n","2.5","50","97.5","mode")
print(SEV.summary,digits=3)
# SEV Pairwise comparison
SEV.diff<-rep(list(matrix(NA,ncol=nGroups,nrow=nrow(SEV))),nGroups)
for (i in 1:nGroups){
for (j in 1:nGroups){
SEV.diff[[i]][,j]<-SEV[,i]-SEV[,j]
}
}
diff.table<-matrix(NA,nrow=nGroups,ncol=3)
for (i in 1:nGroups){
for (j in 1:nGroups){
diff.table[i,j]<-sum(SEV.diff[[i]][,j]>0)/length(SEV.diff[[i]][,j])
}
}
p.table<-matrix(NA,nrow=nGroups,ncol=nGroups)
colnames(p.table)<-paste(">",stock.names, sep="")
rownames(p.table)<-stock.names
for (i in 1:nGroups){
for (j in 1:nGroups){
p.table[i,j]<-sum(SEV.diff[[i]][,j]>0)/length(SEV.diff[[i]][,j])
}
}
print(p.table)
#Pairwise comparison centroid
mu.diff<-array(NA, dim=c(nIsotopes,nrow(out$sims.list$mu),nGroups,nGroups))
for (k in 1:nIsotopes){
for (i in 1:nrow(out$sims.list$mu)){
for (j in 1:nGroups){
for (m in 1:nGroups){
mu.diff[k,i,j,m]<-out$sims.list$mu[i,j,k]-out$sims.list$mu[i,m,k]
}}}}
mu.p<-rep(list(matrix(NA,ncol=nGroups,nrow=nGroups)),3)
for (k in 1:3){
for(j in 1:nGroups){
for(m in 1:nGroups){
mu.p[[k]][j,m]<-sum(mu.diff[k,,j,m]>0)/nrow(out$sims.list$mu)
}}}
for (i in 1:nGroups){
rownames(mu.p[[i]])<-stock.names
colnames(mu.p[[i]])<-paste(">",stock.names, sep="")
}
names(mu.p)<-isotope.names
mu.p
# Distance between centroids
null_mu<-array(out$sims.list$mu[seq(1,nrow(out$sims.list$mu),by=2),,],dim=c(nrow(out$sims.list$mu)/2,3,nGroups))
test_mu<-array(out$sims.list$mu[seq(2,nrow(out$sims.list$mu),by=2),,],dim=c(nrow(out$sims.list$mu)/2,3,nGroups))
dist.diff1<-array(NA, dim=c(nGroups,nGroups,nrow(out$sims.list$mu)/2))
for (j in 1:nGroups){
for (m in 1:nGroups){
dist.diff1[j,m,]<-distance(test_mu[,j,],test_mu[,m,]) - distance(test_mu[,j,],null_mu[,j,]) - distance(test_mu[,m,],null_mu[,m,])
}}
dist.diff2<-array(NA, dim=c(nGroups,nGroups,nrow(out$sims.list$mu)/2))
for (j in 1:nGroups){
for (m in 1:nGroups){
dist.diff2[j,m,]<-distance(test_mu[,j,],test_mu[,m,])
}}
dist.sum<-rep(list(matrix(NA,ncol=nGroups,nrow=nGroups)),3)
for (i in 1:3){
for (j in 1:nGroups){
for (m in 1:nGroups){
dist.sum[[i]][j,m]<-quantile(dist.diff2[j,m,],probs=c(0.025,0.5,0.975)[i])
}}}
names(dist.sum)<-c("q2.5","q50","q97.5")
for(i in 1:3){
colnames(dist.sum[[i]])<-stock.names
rownames(dist.sum[[i]])<-stock.names
}
pdist<-matrix(NA, nrow=nGroups,ncol=nGroups)
for(j in 1:nGroups){
for(m in 1:nGroups){
pdist[j,m]<-sum(dist.diff1[j,m,]>0)/(nrow(out$sims.list$mu)/2)
}
}
colnames(pdist)<-row.names(pdist)<-stock.names
print(pdist, digits=2)
print(dist.sum, digits=2)
############################################################
# Section 5: Graphs
############################################################
# 3D Graphs
#get mean covariance matrix and mean vector
sigma<-out$mean$cov
mu<-out$mean$mu
# Call and construct plot
colorit<-c("red","yellow","blue")
open3d()
for (k in nGroups:1){
nam <- paste("A", k, sep = "")
assign(nam, ellipse3d(qmesh=TRUE,sigma[,,k],centre=out$mean$mu[k,],level=0.40, subdivide = 5, trans=diag(4)))
wire3d(get(paste("A", k, sep="")), col=colorit[k])
nam2 <- paste("cords", k, sep = "")
assign(nam2,t(get(paste("A", k, sep=""))$vb)[,1:3])
}
axes3d(lwd=5, col="black")
grid3d("x+",lwd=5,col="black")
grid3d("y+",lwd=5,col="black")
grid3d("z+",lwd=5,col="black")
axes3d(c('x--','x++','y--','y++','z--','z++'),expand=2)
title3d(,,'Carbon','Nitrogen','Sulfur')
# Save a movie rotation
M <- par3d("userMatrix")
if (!rgl.useNULL())
play3d( par3dinterp(time=(0:2)*0.75,userMatrix=list(M,
rotate3d(M, pi/2, 1, 0, 0),
rotate3d(M, pi/2, 0, 1, 0) ) ),
duration=3 )
movie3d( spin3d(axis=c(0,1,0),rpm=3), duration=10, dir=getwd() )
# 2D Graphs (must run 3d graph first)
cords<-data.frame(matrix(NA, nrow=nrow(cords1),ncol=nGroups*3))
seq3<-seq(1,nGroups*3,by=3)
for (i in 1:nGroups){
cords[,seq3[i]:(seq3[i]+2)]<-get(paste("cords",i,sep=""))
}
cmin<-floor(min(cords[,seq3]))
cmax<-ceiling(max(cords[,seq3]))
nmin<-floor(min(cords[,(seq3+1)]))
nmax<-ceiling(max(cords[,(seq3+1)]))
smin<-floor(min(cords[,(seq3+2)]))-1
smax<-ceiling(max(cords[,(seq3+2)]))
carbon<-expression(paste(delta^"13"*"C (\211)"))
nitrogen<-expression(paste(delta^"15"*"N (\211)"))
sulfur<-expression(paste(delta^"34"*"S (\211)"))
rgb<-matrix(c(1,0,0,0,1,0,0,0,1),ncol=3)
#Carbon Nitrogen
par(las=1)
par(mgp=c(0, 0.7, 0))
plot(NA,NA,ylim=c(nmin,nmax),xlim=c(cmin,cmax),xlab="",ylab="", bty="n",
xaxt="n",yaxt="n",xaxs="i",yaxs="i", main="", cex.lab=2, cex.main=2)
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "lightgray", border=NA)
abline(v=seq(-100,100,by=1),col="white")
abline(h=seq(-100,100,by=1),col="white")
axis(side = 1, at = seq(-100,100,by=1), cex.axis=1.5,lwd=0, lwd.ticks=0)
axis(side = 2, at = seq(-100,100,by=1),cex.axis=1.5, lwd=0, lwd.ticks=0)
mtext(carbon, side=1, line=3.3, cex=2)
par(las=3)
mtext(nitrogen, side=2, line=1.8, cex=2)
for(i in 1:nGroups){
polygon(hull(cords[,seq3[i]],cords[,(seq3[i]+1)]),col="lightgray",border=NA)
}
for(i in 1:nGroups){
polygon(hull(cords[,seq3[i]],cords[,(seq3[i]+1)]),col=rgb(rgb[i,1],rgb[i,2],rgb[i,3],0.5),border=NA)
}
#Carbon Sulfur
par(las=1)
par(mgp=c(0, 0.7, 0))
plot(NA,NA,ylim=c(smin,smax),xlim=c(cmin,cmax),xlab="",ylab="", bty="n",
xaxt="n",yaxt="n",xaxs="i",yaxs="i", main="", cex.lab=2, cex.main=2)
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "lightgray", border=NA)
abline(v=seq(-100,100,by=1),col="white")
abline(h=seq(-100,100,by=2),col="white")
axis(side = 1, at = seq(-100,100,by=1), cex.axis=1.5,lwd=0, lwd.ticks=0)
axis(side = 2, at = seq(-100,100,by=2),cex.axis=1.5, lwd=0, lwd.ticks=0)
mtext(carbon, side=1, line=3.3, cex=2)
par(las=3)
mtext(sulfur, side=2, line=1.8, cex=2)
for(i in 1:nGroups){
polygon(hull(cords[,seq3[i]],cords[,(seq3[i]+2)]),col="lightgray",border=NA)
}
for(i in 1:nGroups){
polygon(hull(cords[,seq3[i]],cords[,(seq3[i]+2)]),col=rgb(rgb[i,1],rgb[i,2],rgb[i,3],0.5),border=NA)
}
# Sulfur Nitrogen
par(las=1)
par(mgp=c(0, 0.7, 0))
plot(NA,NA,xlim=c(smin,smax),ylim=c(nmin,nmax),xlab="",ylab="", bty="n",
xaxt="n",yaxt="n",xaxs="i",yaxs="i", main="", cex.lab=2, cex.main=2)
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = "lightgray", border=NA)
abline(v=seq(-100,100,by=2),col="white")
abline(h=seq(-100,100,by=1),col="white")
axis(side = 1, at = seq(-100,100,by=2), cex.axis=1.5,lwd=0, lwd.ticks=0)
axis(side = 2, at = seq(-100,100,by=1),cex.axis=1.5, lwd=0, lwd.ticks=0)
mtext(sulfur, side=1, line=3.3, cex=2)
par(las=3)
mtext(nitrogen, side=2, line=1.8, cex=2)
for(i in 1:nGroups){
polygon(hull(cords[,(seq3[i]+2)],cords[,(seq3[i]+1)]),col="lightgray",border=NA)
}
for(i in 1:nGroups){
polygon(hull(cords[,(seq3[i]+2)],cords[,(seq3[i]+1)]),col=rgb(rgb[i,1],rgb[i,2],rgb[i,3],0.5),border=NA)
}
<file_sep>/README.md
# [Beyond carbon and nitrogen: guidelines for estimating three‐dimensional isotopic niche space](https://onlinelibrary.wiley.com/doi/abs/10.1002/ece3.2013)
### <NAME>, <NAME>, <NAME>, and <NAME>
### Ecology and Evolution
### Please contact the first author for questions about the code or data: <NAME> (<EMAIL>)
______________________________________________________________________________________________________________________________________
## Abstract
Isotopic niche has typically been characterized through carbon and nitrogen ratios and most modeling approaches are limited to two dimensions. Yet, other stable isotopes can provide additional power to resolve questions associated with foraging, migration, dispersal and variations in resource use. The ellipse niche model was recently generalized to n‐dimensions. We present an analogous methodology which incorporates variation across three stable dimensions to estimate the significant features of a population's isotopic niche space including: 1) niche volume (referred to as standard ellipsoid volume, SEV), 2) relative centroid location (CL), 3) shape and 4) area of overlap between multiple ellipsoids and 5) distance between two CLs. We conducted a simulation study showing the accuracy and precision of three dimensional niche models across a range of values. Importantly, the model correctly identifies differences in SEV and CL among populations, even with small sample sizes and in cases where the absolute values cannot precisely be recovered. We use these results to provide guidelines for sample size in conducting multivariate isotopic niche modeling. We demonstrate the utility of our approach with a case study of three bottlenose dolphin populations which appear to possess largely overlapping niches when analyzed with only carbon and nitrogen isotopes. Upon inclusion of sulfur, we see that the three dolphin ecotypes are in fact segregated on the basis of salinity and find the stable isotope niche of inshore bottlenose dolphins significantly larger than coastal and offshore populations.
## Code
[simulation.R](https://github.com/zipkinlab/Rossman_etal_2016_EcolAndEvol/blob/master/simulation.R) – This file contains the code to simulate tri-variate data for four populations using known “true” SEV values and centroid locations. The code will first write the JAGS model to the working directory then run data through the model. Metrics such as SEV, centroid location, percent overlap, and statistical test between SEV and centroid location are calculated in the code following the JAGS run.
[dolphin_example_wrapper.R](https://github.com/zipkinlab/Rossman_etal_2016_EcolAndEvol/blob/master/dolphin_example_wrapper.R) – This file contains the code to run the case study quantifying the isotopic niche of three Florida dolphin stocks. Code contains the following parts: 1.) libraries and shortcut functions, 2.) code to write and sink the JAGS Model, 3.) data, data processing and code to run JAGS, 4.) Results post processing to calculate SEV, centroid location and statistical tests and 5.) Graphing results.
<file_sep>/simulation.R
#Appendix A: Additional details on the simulation study
#This appendix includes the R and JAGS code used to run the simulation study
#The R and JAGS code used to simulate CL and SEV for four different populations with
#various true CL and SEV values: We assigned each population a true CL and SEV
#values. The true SEV value is then used to calculate a semi-random covariance
#matrix, ??, with the function "getcov(SEV)". The true CL was used as the mean
#vector, µ, for each ellipsoid. For illustrative purposes, the code below generates
#20 observations for each population from a multivariate normal distribution with
#the mean vector µ and the simulated covariance matrix ??. SEV was calculated as a
#derived quantity based on posterior estimates of ?? after the JAGS model run was
#completed in R. The code used for hypothesis testing for differences in CL, SEV,
#and distance between centroids is also included.
library(MASS) # for mvrnorm
library(jagsUI) # to run jags
#Function to calcuate SEV
SEV.function<-function(sigma) {
if (eigen(sigma)$values[3] > 0)
{
axises<-sqrt(eigen(sigma)$values)
}
else {
axises<-NA
}
out<-list()
out$a<-axises[1]
out$b<-axises[2]
out$c<-axises[3]
out$SEV<-prod(axises,pi,4/3)
return(out$SEV)
}
#create a matrix of group combinations for pairwise comparisons
pairwise<-function(ngroups){
groups<-seq(1,ngroups)
max.compare<-((ngroups-1)*ngroups)/2
i=0
counter=ngroups
pairs<-c(0,0)
while (counter>0){
i=1+i
counter=counter-1
if (counter!=0){
temp1<-rep(groups[i],counter)
temp2<-seq(i+1,ngroups)
pairs<-rbind(pairs,cbind(temp1,temp2))
if (i==1){
pairs<-pairs[-1,]
}
}}
colnames(pairs)<-c('group1','group2')
return(pairs)
}
#Function to generate a random covariance matrix based on given SEV value
getcov<-function(SEV){
options(warn=-1)
Sigma<-matrix(rep(NA,9),ncol=3)
while(is.na(Sigma[1,1]==TRUE)){
if (((3*SEV)/(4*pi))^2/3 < 1){
lambda1<-runif(1,1,((3*SEV)/(4*pi))^2)
}else {
lambda1<-runif(1,((3*SEV)/(4*pi))^2/3,((3*SEV)/(4*pi))^2)
}
lambda2<-runif(1,(((3*SEV)/(4*pi))^2)/lambda1,((3*SEV)/(4*pi)))
lambda3<-(((3*SEV)/(4*pi))^2)/(lambda1*lambda2)
u<-diag(c(lambda1,lambda2,lambda3))
Q<-qr.Q(qr(runif(3,-0.8,.8)),complete=TRUE)
Sigma <- Q %*% u %*% t(Q)
}
options(warn=0)
return(Sigma)
}
#Calculate euclidian distance between two 3 demensional points
distance<-function(a,b){
l<-sqrt((a[,1]-b[,1])^2+(a[,2]-b[,2])^2+(a[,3]-b[,3])^2)
return(l)
}
#calculate the mode of a posterior distrobution
mode <- function(s) {
d <- density(s,na.rm=TRUE)
d$x[which.max(d$y)]
}
#functions to calculate overlap
# This function calculates area of SEV overlap via naive for-loop numeric integration of one.
# ellipsoid step function (1 when MVNdist2<1) over the other ellipsoid, done as a 3D Riemann
# sum over little cubes of variable size. The user specifies the variable "HowFine", and
# this determines cube size on a log scale. Specifically, the cube width is equal to "OneStep",
# which is defined by OneStep <- 10^(-HowFine). This piece of code makes a big list to index
# all the little cubical regions inside the ellipsoid E1 at this resolution, counts how many
# of them are inside E2, and then multiplies this number by the volume of each little cube,
# which is CubeVol <- OneStep^3, to produce the approximate overlap volume.
CubeCount3D <- function(mu1,mu2,S1,S2,HowFine=1.0,ShowProgress=FALSE){
# set-up stuff:
MVNdist <- function(mu,S){function(x){t(x-mu)%*%solve(S)%*%(x-mu)}}
OneStep <- 10^(-HowFine);
CubeVol <- OneStep^3;
CubeCt <- 0;
A1 <- eigen(S1)$vect
dD1 <- eigen(S1)$val
MVNdist2 <- MVNdist(mu2,S2);
# the loops:
zlist <- seq(from=0,to=dD1[3]^.5,by=OneStep)
zlist <- if(length(zlist)>1){c(rev(-zlist),zlist[2:length(zlist)])}
for(Z in zlist){
yBd <- (dD1[2]*(1-Z^2/dD1[3]))^.5
ylist <- seq(from=0,to=yBd,by=OneStep)
ylist <- if(length(ylist)>1){c(rev(-ylist),ylist[2:length(ylist)])}
for(Y in ylist){
xBd <- (dD1[1]*(1-Y^2/dD1[2]-Z^2/dD1[3]))^.5
xlist <- seq(from=0,to=xBd,by=OneStep)
xlist <- if(length(xlist)>1){c(rev(-xlist),xlist[2:length(xlist)])}
for(X in xlist){
if(MVNdist2(A1%*%c(X,Y,Z)+mu1)<1){CubeCt=CubeCt+1}
}
}
# This will show a "progress report" in the console window as this script is running:
# (0=start, 1=end)
if(ShowProgress){print((.5*(Z+dD1[3]^.5))/dD1[3]^.5)}
}
return(CubeCt*CubeVol)
}
##############################################################################
#Jags mode
##############################################################################
sink("ellipsoid_example.txt")
cat("
model{
#priors
for (k in 1:ngroups){
mu[k,1] ~ dnorm(0,0.001)
mu[k,2] ~ dnorm(0,0.001)
mu[k,3] ~ dnorm(0,0.001)
prec[1:3,1:3,k] ~ dwish(S3,4)
cov[1:3,1:3,k] <- inverse(prec[1:3,1:3,k])
#likelihood
for (i in 1:maxn){
y[i,1:3,k] ~ dmnorm(mu[k,],prec[,,k])
}#i
}
}
",fill = TRUE)
sink()
##############################################################################
# Generate Data
##############################################################################
# Data should be supplied as a four column table, the fist column is a grouping
# variable which can be catagorical or numeric
ngroups<-4
n<-20
TrueSEV<-c(5,7.5,10,20)
S<-array(NA, dim=c(3,3,ngroups))
for (i in 1:ngroups){
S[,,i]<-getcov(TrueSEV[i])
}
TrueMu<-rbind(c(0,0,0),c(1,1,1),c(2,2,2),c(3,3,3))
thedata<-array(NA, dim=c(n,4,ngroups))
for (i in 1:ngroups){
thedata[,,i]<-cbind(rep(paste("group",i),n),mvrnorm(n,TrueMu[i,],S[,,i]))
}
thedata<-as.data.frame(apply(thedata,2,c))
colnames(thedata)<-c("groups","isotope1","isotope2","isotope3")
##############################################################################
# Preparing the data
##############################################################################
#generate list names of each group
groupnames<-levels(as.factor(thedata[,1]))
#generate list of isotope names and number of isotopes
isotope_names<-colnames(thedata)[2:4]
isotopes<-3
#convert group names to numeric factors
thedata[,1]<-as.numeric(as.factor(thedata[,1]))
ngroups<-max(thedata[,1])
#find the groups with the largest n and the n per group
nstart<-c(NA)
nend<-c(NA)
for (i in 1:ngroups){
nstart[i]<-min(as.numeric(rownames(thedata[thedata[,1]==i,])))
nend[i]<-max(as.numeric(rownames(thedata[thedata[,1]==i,])))
}
maxn<-max(nend+1-nstart)
npergroup<-nend+1-nstart
# create an array where nrow = the n of the largest group, for groups with smaller n's
# some rows will have NA's to account for uneven replication
y<-array(NA,dim=c(maxn,3,ngroups))
for (i in 1:ngroups){
y[1:nrow(thedata[thedata[,1]==i,2:4]),,i]<-as.matrix(thedata[thedata[,1]==i,2:4])
}
#ensure y is a completely numeric array
y<-array(as.numeric(y),dim=dim(y))
#####################################
#package the data
#####################################
#objects passed to jags
data=list(y=y,ngroups=ngroups, maxn=maxn, S3=(diag(3)*3))
#initial values
mu0<-matrix(NA, nrow=ngroups, ncol=3)
prec0<-array(0,dim=c(3,3,ngroups))
for (k in 1:ngroups){
mu0[k,]<-mvrnorm(1,c(0,0,0),diag(3)*100)
prec0[,,k]<-getcov(runif(1,5,30))
}
inits=function(){list( mu=mu0, prec=prec0)}
# parameters to moniter
params<-c("mu","cov")
# MCMC settings
nt <- 1
nb <- 1000
nc <- 3
na<-1000
ni <- 5000
#################################################
# Run Jags
################################################
out <- jags(data = data,
inits = inits,
parameters.to.save = params,
model.file = 'ellipsoid_example.txt',
n.chains = nc,
n.adapt = na,
n.iter = ni,
n.burnin = nb,
n.thin = nt)
plot(out)
#Summary
out
#################################################
# Calulate SEV
###############################################
# a list to index pairwise comparisons
pl<-cbind(sort(rep(seq(1:ngroups),ngroups)),rep(seq(1:ngroups),ngroups))
# probabilities to posterior distrobutions
probs<-c(0.025,0.5,0.975)
# Calculate an estimate of SEV from each posterior estimate of sigma and sumarize
SEV<-matrix(NA,ncol=ngroups,nrow=nrow(out$sims.list$cov))
SEV.summary<-matrix(NA,nrow=ngroups,ncol=3+length(probs))
for (k in 1:ngroups){
SEV[,k]<-apply(out$sims.list$cov[,,,k],1,SEV.function)
SEV.summary[k,]<-c(nend[k]+1-nstart[k],quantile(SEV[,k],probs=probs),mode(SEV[,k]), mean(SEV[,k]))
}
rownames(SEV.summary)<-groupnames
colnames(SEV.summary)<-c("n",paste(probs,"%",sep=""),"mode","mean")
print(SEV.summary,digits=2)
#################################################
# SEV Pairwise comparison
###############################################
#Compare each posterior SEV estimate to those of other groups
SEV.diff<-array(NA,dim=c(ngroups,ngroups,nrow(SEV)))
for(i in 1:(ngroups*ngroups)){
SEV.diff[pl[i,1],pl[i,2],]<-SEV[,pl[i,1]]-SEV[,pl[i,2]]
}
p.table<-matrix(NA,nrow=ngroups,ncol=ngroups)
colnames(p.table)<-paste(">",groupnames, sep="")
rownames(p.table)<-groupnames
for (i in 1:(ngroups*ngroups)){
p.table[pl[i,1],pl[i,2]]<-sum(SEV.diff[pl[i,1],pl[i,2],]>0)/nrow(SEV)
}
print(p.table,digits=2)
#################################################
#Pairwise comparison centroid
###############################################
#compare posterior estimates of mu (isotope mean values) to those other groups
mu.diff<-array(NA, dim=c(nrow(out$sims.list$mu),3,ngroups*ngroups))
for (i in 1:(ngroups*ngroups)){
mu.diff[,,i]<-out$sims.list$mu[,pl[i,1],]-out$sims.list$mu[,pl[i,2],]
}
mu.p<-rep(list(matrix(NA,ncol=ngroups,nrow=ngroups)),3)
for (k in 1:3){
for(i in 1:(ngroups*ngroups)){
mu.p[[k]][pl[i,1],pl[i,2]]<-sum(mu.diff[,k,i]>0)/nrow(out$sims.list$mu)
}}
for (k in 1:3){
rownames(mu.p[[k]])<-groupnames
colnames(mu.p[[k]])<-paste(">",groupnames, sep="")
}
names(mu.p)<-isotope_names
print(mu.p,digits=2)
#################################################
# Distance between centroids
###############################################
# Divide posterior estimates of mu into test and null distrobutions
null_mu<-array(out$sims.list$mu[seq(1,nrow(out$sims.list$mu),by=2),,],dim=c(nrow(out$sims.list$mu)/2,ngroups,3))
test_mu<-array(out$sims.list$mu[seq(2,nrow(out$sims.list$mu),by=2),,],dim=c(nrow(out$sims.list$mu)/2,ngroups,3))
dist.diff<-array(NA, dim=c(ngroups,ngroups,nrow(out$sims.list$mu)/2))
dist.diff.test<-array(NA, dim=c(ngroups,ngroups,nrow(out$sims.list$mu)/2))
#Calculate distance estites for each posterior of mu and a distanace measure adjusted based on the
# null distrobution
for (i in 1:(ngroups*ngroups)){
dist.diff[pl[i,1],pl[i,2],]<-distance(test_mu[,pl[i,1],],test_mu[,pl[i,2],])
dist.diff.test[pl[i,1],pl[i,2],]<-distance(test_mu[,pl[i,1],],test_mu[,pl[i,2],]) -
distance(test_mu[,pl[i,1],],null_mu[,pl[i,1],]) - distance(test_mu[,pl[i,2],],null_mu[,pl[i,2],])
}
#summarize posterior
dist.sum<-matrix(NA, nrow=nrow(pl),ncol=7)
probs<-c(0.025,0.5,0.975)
for(i in 1:(ngroups*ngroups)){
dist.sum[i,]<-c(pl[i,1:2],quantile(dist.diff[pl[i,1],pl[i,2],],probs=probs),mode(dist.diff[pl[i,1],pl[i,2],]),mean(dist.diff[pl[i,1],pl[i,2],]))
}
dist.sum<-dist.sum[c(-1,-6,-11,-16),]
colnames(dist.sum)<-c("group","group",paste(probs,"%",sep=""),"mode","mean")
# Calculate probabilities that the distance estimates overlap zero
pdist<-matrix(NA, nrow=ngroups,ncol=ngroups)
for (i in 1:(ngroups*ngroups)){
pdist[pl[i,1],pl[i,2]]<-sum(dist.diff.test[pl[i,1],pl[i,2],]>0)/(nrow(out$sims.list$mu)/2)
}
colnames(pdist)<-groupnames
rownames(pdist)<-groupnames
print(pdist,digits=2)
#######################################################################################################
# Area Overlap
#######################################################################################################
# define objects for mu and sigma values from the posterior
mus<-out$sims.list$mu
sigmas<-out$sims.list$cov
#create a matrix of all pair-wise comparisons
pairs<-pairwise(ngroups)
# Create a loop to 1) calculate the area of over lap for each pair-wise comparison
# and 2) compare that value to each group's respective SEV value
overlap<-matrix(NA, nrow=nrow(mus), ncol=nrow(pairs))
overlap.SEV<-array(1, dim=c(ngroups,ngroups,nrow(mus)))
for(i in 1:nrow(pairs)){
for(j in 1:nrow(mus)){
overlap[j,i]<-CubeCount3D(mus[j,pairs[i,1],],
mus[j,pairs[i,2],],
sigmas[j,,,pairs[i,1]],
sigmas[j,,,pairs[i,2]])
}
overlap.SEV[pairs[i,1],pairs[i,2],]<-overlap[,i]/SEV[,pairs[i,1]]
overlap.SEV[pairs[i,2],pairs[i,1],]<-overlap[,i]/SEV[,pairs[i,2]]
}
#summarize results
overlap.2.5<-matrix(NA, nrow=ngroups, ncol=ngroups)
overlap.50<-matrix(NA, nrow=ngroups, ncol=ngroups)
overlap.975<-matrix(NA, nrow=ngroups, ncol=ngroups)
for (i in 1:nrow(pairs)){
overlap.2.5[pairs[i,1],pairs[i,2]]<-quantile(overlap.SEV[pairs[i,1],pairs[i,2],], probs=0.025)
overlap.50[pairs[i,1],pairs[i,2]]<-quantile(overlap.SEV[pairs[i,1],pairs[i,2],], probs=0.5)
overlap.975[pairs[i,1],pairs[i,2]]<-quantile(overlap.SEV[pairs[i,1],pairs[i,2],], probs=0.75)
}
#####################################################################################################
# Print results
print(SEV.summary,digits=2)
print(p.table, digits=2)
print(mu.p,digits=2)
print(dist.sum,digits=2)
print(pdist,digits=2)
print(overlap.2.5,digits=2)
print(overlap.50,digits=2)
print(overlap.975,digits=2)
|
1efa0fa49694c950c38b2e2b32931a13af07fbef
|
[
"Markdown",
"R"
] | 3
|
R
|
zipkinlab/Rossman_etal_2016_EcolAndEvol
|
496714085ff751385c4de57dca5e9f12a97a5922
|
bdc52dc5c8ef55d3dc36b73a363de26b5e11faa8
|
refs/heads/master
|
<repo_name>liuyunhe/zheye-app<file_sep>/src/helper.ts
import { ColumnProps } from './store'
export function generateFitUrl(
column: ColumnProps,
width: number,
height: number
): void {
if (column.avatar) {
column.avatar.fitUrl =
column.avatar.url +
`?x-oss-process=image/resize,m_pad,h_${height},w_${width}`
} else {
column.avatar = {
fitUrl: require('@/assets/column.jpg')
}
}
}
interface CheckCondition {
format?: string[]
size?: number
}
type ErrorType = 'size' | 'format' | null
// eslint-disable-next-line
export function beforeUploadCheck(file: File, condition: CheckCondition) {
const { format, size } = condition
const isValidFormat = format ? format.includes(file.type) : true
const isValidSize = size ? file.size / 1024 / 1024 < size : true
let error: ErrorType = null
if (!isValidFormat) {
error = 'format'
}
if (!isValidSize) {
error = 'size'
}
return {
passed: isValidFormat && isValidSize,
error
}
}
// eslint-disable-next-line
export const arrToObj = <T extends { _id?: string }>(arr: T[]) => {
return arr.reduce((prev, current) => {
if (current._id) {
prev[current._id] = current
}
return prev
}, {} as { [key: string]: T })
}
export const objToArr = <T>(obj: { [key: string]: T }): T[] => {
return Object.values(obj)
}
<file_sep>/src/http.ts
import axios from 'axios'
import { nextTick } from 'vue'
import store from './store'
axios.defaults.baseURL = '/api/'
axios.interceptors.request.use((config) => {
store.commit('setLoading', true)
store.commit('setError', { status: false })
return config
})
axios.interceptors.response.use(
(config) => {
nextTick(() => {
store.commit('setLoading', false)
})
return config
},
(e) => {
const { error } = e.response.data
store.commit('setError', { status: true, message: error })
nextTick(() => {
store.commit('setLoading', false)
})
return Promise.reject(error)
}
)
export default axios
<file_sep>/src/hooks/useLoadMore.ts
import { ComputedRef, ref } from '@vue/reactivity'
import { computed } from '@vue/runtime-core'
import { useStore } from 'vuex'
interface LoadParams {
currentPage: number
pageSize: number
cid?: string
}
// eslint-disable-next-line
const useLoadMore = (
actionName: string,
total: ComputedRef<number>,
params: LoadParams = { currentPage: 2, pageSize: 5 }
) => {
const store = useStore()
const currentPage = ref(params.currentPage)
const requestParams = computed(() => ({
currentPage: currentPage.value,
pageSize: params.pageSize,
cid: params.cid
}))
const loadMorePage = () => {
store.dispatch(actionName, requestParams.value).then(() => {
currentPage.value++
})
}
const isLastPage = computed(() => {
return Math.ceil(total.value / params.pageSize) < currentPage.value
})
return {
loadMorePage,
isLastPage,
currentPage
}
}
export default useLoadMore
<file_sep>/README.md
# 从零到一 高仿知乎专栏
## 前言
### 一个复杂的 SPA 项目都要包括哪些知识点?
- 第一,要有数据的展示,这个是所有网站共有的特性,而且最好是有多级复杂数据的展示
- 第二,要有数据的创建,这就是表单的作用,有展示自然要有创建。在创建中,我们会发散很多问题,比如数据的验证怎样做,文件的上传如何处理,创建和编辑怎样共享单个页面等等。
- 第三,要有组件的抽象,vue 是组件的世界,组件是最重要的一环,编写组件是最基本的能力,对于一些常用的功能,我们需要高可用性和可定制性的组件,也就是说我们在整个项目中一般不会用到第三方组件,比如 element,都是从零开始,而且会循序渐进,不断抽象。甚至行成自己的一套小组件库。
- 第四,整体状态数据结构的设计和实现,SPA 一般使用状态工具管理整理状态,并且给多个路由使用,在 vue 中,我们使用 vuex,一个项目的整体数据结构的复杂程度就代表了这个能力的高低,最好是要有多层次的数据结构,相互依赖的关系,还要将数据的获取,结构设计,缓存进行一系列的考量。
- 第五,权限管理和控制,一个项目需要有用户权限的实现,不仅仅是后端,前端作为一个整体的 SPA 的项目,权限控制也尤为重要,我们需要有权限的获取,权限的持久化,权限的更新,那个路由可访问,哪个需要权限才可以访问。发送异步请求的全局 token 注入,全局拦截,全局信息提示等等和权限相关的内容。
- 第六,真实的后端API,和后端的交互是整个项目的最重要一环。一些同学在开发项目的时候会使用 mock server,但是由于后端的数据结构常常和最初的文档设计背道而驰,造成最后项目需要再次回炉修改。
## 项目部分页面预览

## 使用 Typescript + Vue3 开发
- Vue3 + Typescript:Vue3 配合 Typescript ,使用新版Vuex 和 Vue-Router 全家桶完成前后端分离复杂项目
- 组件库为脉络:实现一系列由易到难的通用组件开发,可谓学会一个基本的组件库的开发。
- 提供真实后端API:告别 mock 数据,并提供swagger 在线调试查询。
### 项目演示与服务
- Github:[传送门](https://github.com/liuyunhe/zheye-app)
- 项目演示站点:[传送门](http://zhihu.vikingship.xyz/)
- 在线后端API 查询和使用站点:[传送门](http://api.vikingship.xyz/)
- 项目在线文档:[传送门](http://docs.vikingship.xyz/)
- 完成的组件库展示:[传送门](http://showcase.vikingship.xyz/)
- 页面所有原型图地址:[传送门](https://whimsical.com/Djb2TcWsLTPeapFdM3NaX)
### 技术要点
#### Typescript
- 简单类型
- 复杂类型
- 接口-Interface
- 类 - Class
- 泛型 - Generics
- 声明文件
#### Vue3
- Ref 和 Reactive
- watch 和 computed
- 生命周期
- 自定义函数 Hooks
- Teleport 和 Suspense
- 全局 API 修改
- 复杂组件设计和实现
#### Vue-Router
- 动态路由匹配
- 导航守卫
- 路由元信息
#### Vuex
- State
- Getter
- Mutation
- Action
- 中大型Store 结构设计与实现
#### 前后端结合
- Axios 基础和用法
- swagger 在线调试异步请求
- JSON web token 实现权限验证
- axios 拦截器实现全局处理
- 前端缓存设计与实现
- 文件上传原理和组件实现
### 项目结构

### 路由结构
路由使用了vue-router,对应添加了路由守卫,结构如下图所示

### 文章数据结构

文章数据结构是这个应用的核心,涉及到几乎所有功能
```ts
export interface ImageProps {
_id?: string;
url?: string;
createdAt?: string;
fitUrl?: string
}
export interface ColumnProps {
_id: string; // 专栏识别标识
title: string;
avatar?: ImageProps;
description: string;
}
export interface PostProps {
_id?: string; // 文章识别标识
title: string;
excerpt?: string;
content?: string;
image?: ImageProps | string;
createdAt?: string;
column: string;
author?: string | Userprops;
isHTML?: boolean;
}
```
### 组件一览
应用中用到的各种组件,上文已附带组件库文档

### 项目启动
```
npm run serve
```
### Lints and fixes files
```
npm run lint
```
### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).
|
253f6f7f133b5a8caa06d020cce6424fcc92f58d
|
[
"Markdown",
"TypeScript"
] | 4
|
TypeScript
|
liuyunhe/zheye-app
|
343b6b44a8a732734c892bc34b5cc5d2d114b855
|
7dd56d0e0edaff808b4bc4b7b2dd7cd73fdead1d
|
refs/heads/master
|
<repo_name>rolandschulz/mpp<file_sep>/test/simple_sendrecv.cc
#include <gtest/gtest.h>
#include <mpp.h>
#include <iostream>
#include <cmath>
using namespace mpi;
TEST(SendRecv, Scalar) {
if(comm::world.rank() == 0) {
comm::world(1) << 4.2;
int val;
auto s = comm::world(1) >> val;
EXPECT_EQ(4, val);
EXPECT_EQ( 1, s.source().rank() );
EXPECT_EQ( 0, s.tag() );
} else if (comm::world.rank() == 1) {
double val;
auto s = comm::world(0) >> val;
EXPECT_EQ(4.2,val);
EXPECT_EQ( 0, s.source().rank() );
EXPECT_EQ(0, s.tag());
comm::world(0) << static_cast<int>(floor(val));
}
}
TEST(SendRecv, Array) {
int datav[] = {2, 4, 6, 8};
std::vector<int> data(datav, datav+sizeof(datav)/sizeof(int));
if(comm::world.rank() == 0) {
comm::world(1) << data;
} else if (comm::world.rank() == 1) {
std::vector<int> vec(4);
comm::world(0) >> vec;
EXPECT_EQ( static_cast<size_t>(4), vec.size() );
// check whether received data is equal to original data
EXPECT_TRUE( std::equal(vec.begin(), vec.end(), data.begin(), std::equal_to<int>()) );
}
}
TEST(SendRecv, Future) {
if ( comm::world.rank() == 0 ) {
comm::world(1) << 100;
} else if(comm::world.rank() == 1) {
int k;
request<int> r = comm::world(0) > k;
r.get();
EXPECT_EQ(100, k);
}
}
TEST(SendRecv, Tags) {
if ( comm::world.rank() == 0 ) {
comm::world(1) << msg<const int>(100, 11);
comm::world(1) << msg<const int>(101, 0);
} else if(comm::world.rank() == 1) {
int k;
comm::world(0) >> msg(k,0);
EXPECT_EQ(101, k);
comm::world(0) >> msg(k,11);
EXPECT_EQ(100, k);
}
}
TEST(SendRecv, PingPong) {
int p=0;
if(comm::world.rank() == 0) {
// start the ping
comm::world(1) << p;
}
while ( p <= 10 ) {
auto ep = (comm::world(mpi::any) >> p ).source();
ep << p+1;
EXPECT_TRUE(comm::world.rank()==0?p%2!=0:p%2==0);
}
}
TEST(SendRecv, Lists) {
if ( comm::world.rank() == 0 ) {
int data[] = {1,2,3,4,5};
std::list<int> l(data,data+sizeof(data)/sizeof(int));
comm::world(1) << l;
} else if(comm::world.rank() == 1) {
std::vector<int> l(5);
comm::world(0) >> l;
EXPECT_EQ(static_cast<size_t>(5), l.size());
EXPECT_EQ(1, l[0]);
EXPECT_EQ(2, l[1]);
EXPECT_EQ(3, l[2]);
EXPECT_EQ(4, l[3]);
EXPECT_EQ(5, l[4]);
}
}
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
// Disables elapsed time by default.
::testing::GTEST_FLAG(print_time) = false;
// This allows the user to override the flag on the command line.
::testing::InitGoogleTest(&argc, argv);
size_t errcode = RUN_ALL_TESTS();
MPI_Finalize();
return static_cast<int>(errcode);
}
<file_sep>/CMakeLists.txt
project(mmpi CXX)
# States that CMake required version must be >= 2.6
cmake_minimum_required(VERSION 2.6)
# enable ctest support for testing
enable_testing()
# get code root directory (based on current file name path)
get_filename_component( mmpi_dir ${CMAKE_CURRENT_LIST_FILE} PATH )
set ( mmpi_include_dir ${mmpi_dir}/include )
# enable tests for this project
find_package(GTest REQUIRED)
include_directories(${GTEST_INCLUDE_DIRS})
# enable MPI
find_package(MPI REQUIRED)
set(CMAKE_REQUIRED_DEFINITIONS ${MPI_COMPILE_FLAGS})
set(CMAKE_REQUIRED_INCLUDES ${MPI_INCLUDE_PATH})
set(CMAKE_REQUIRED_LIBRARIES ${MPI_LIBRARIES})
# enable C++0x support within gcc (if supported)
if (CMAKE_COMPILER_IS_GNUCXX)
# add general flags
add_definitions( -fshow-column )
add_definitions( -Wall )
# add flags for debug mode
set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -g -O0")
# ENABLE PROFILING
# add_definitions( -pg )
# SET(CMAKE_EXE_LINKER_FLAGS -pg)
# check for -std=c++0x
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag( -std=c++0x CXX0X_Support )
if(CXX0X_Support)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
message( "WARNING: --std=c++0x not supported by your compiler!" )
endif()
endif()
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${MPI_COMPILE_FLAGS}")
# avoid multiple import
if (NOT MEMORY_CHECK_SETUP)
option(CONDUCT_MEMORY_CHECKS "Checks all test cases for memory leaks using valgrind if enabled." OFF)
# add -all-valgrind target
add_custom_target(valgrind)
# define macro for adding tests
macro ( add_unit_test case_name )
# take value from environment variable
set(USE_VALGRIND ${CONDUCT_MEMORY_CHECKS})
# check whether there was a 2nd argument
if(${ARGC} GREATER 1)
# use last argument as a valgrind flag
set(USE_VALGRIND ${ARG2})
endif(${ARGC} GREATER 1)
# add test case
if(USE_VALGRIND)
# no valgrind support in MSVC
if(NOT MSVC)
# add valgrind as a test
add_test(NAME valgrind_${case_name}
COMMAND valgrind
--leak-check=full
--show-reachable=no
--track-fds=yes
--error-exitcode=1
#--log-file=${CMAKE_CURRENT_BINARY_DIR}/valgrind.log.${case_name}
${CMAKE_CURRENT_BINARY_DIR}/ut_${case_name}
WORKING_DIRECTORY
${CMAKE_CURRENT_BINARY_DIR}
)
endif(NOT MSVC)
else(USE_VALGRIND)
# add normal test
add_test(ut_${case_name} ut_${case_name})
# + valgrind as a custom target (only of not explicitly prohibited)
if ((NOT MSVC) AND ((NOT (${ARGC} GREATER 1)) OR (${ARG2})))
add_custom_target(valgrind_${case_name}
COMMAND valgrind
--leak-check=full
--show-reachable=no
--track-fds=yes
--error-exitcode=1
#--log-file=${CMAKE_CURRENT_BINARY_DIR}/valgrind.log.${case_name}
${CMAKE_CURRENT_BINARY_DIR}/ut_${case_name}
WORKING_DIRECTORY
${CMAKE_CURRENT_BINARY_DIR}
)
add_dependencies(valgrind valgrind_${case_name})
endif ((NOT MSVC) AND ((NOT (${ARGC} GREATER 1)) OR (${ARG2})))
endif(USE_VALGRIND)
endmacro(add_unit_test)
endif (NOT MEMORY_CHECK_SETUP)
# mark as defined
set(MEMORY_CHECK_SETUP OFF CACHE INTERNAL "Flag to avoid multiple setup" PARENT_SCOPE)
file(GLOB test_cases test/*.cc)
foreach ( case_file ${test_cases})
get_filename_component( case_name ${case_file} NAME_WE )
add_executable(ut_${case_name} ${case_file})
include_directories(ut_${case_name} ${mmpi_include_dir})
include_directories(ut_${case_name} ${MPI_INCLUDE_PATH})
target_link_libraries(ut_${case_name} ${GTEST_BOTH_LIBRARIES})
target_link_libraries(ut_${case_name} ${MPI_LIBRARIES})
add_unit_test(${case_name})
endforeach(case_file)
<file_sep>/include/mpp.h
// ============================================================================
//
// MPP: An MPI CPP Interface
//
// Author: <NAME>
// Date: 23 Apr. 2011
//
// ============================================================================
#pragma once
#include <mpi.h>
#include <vector>
#include <list>
#include <memory>
#include <stdexcept>
#include <sstream>
#include <algorithm>
#include <cassert>
#include <array>
namespace mpi {
class comm;
class endpoint;
//*****************************************************************************
// MPI Type Traits
//*****************************************************************************
template <class T>
struct mpi_type_traits {
static inline MPI_Datatype get_type(const T& raw);
static inline size_t get_size(const T& raw) { return 1; }
static inline const T* get_addr(const T& raw) { return &raw; }
};
// primitive type traits
template<>
inline MPI_Datatype mpi_type_traits<double>::get_type(const double&) {
return MPI_DOUBLE;
}
template <>
inline MPI_Datatype mpi_type_traits<int>::get_type(const int&) {
return MPI_INT;
}
template <>
inline MPI_Datatype mpi_type_traits<float>::get_type(const float&) {
return MPI_FLOAT;
}
template <>
inline MPI_Datatype mpi_type_traits<long>::get_type(const long&) {
return MPI_LONG;
}
// ... add missing types here ...
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// std::vector<T> traits
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <class T>
struct mpi_type_traits<std::vector<T>> {
static inline size_t get_size(const std::vector<T>& vec) {
return vec.size();
}
static inline MPI_Datatype get_type(const std::vector<T>& vec) {
return mpi_type_traits<T>::get_type( T() );
}
static inline const T* get_addr(const std::vector<T>& vec) {
return mpi_type_traits<T>::get_addr( vec.front() );
}
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// std::array<T> traits
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <class T, size_t N>
struct mpi_type_traits<std::array<T,N>> {
inline static size_t get_size(const std::array<T,N>& vec) { return N; }
inline static MPI_Datatype get_type(const std::array<T,N>& vec) {
return mpi_type_traits<T>::get_type( T() );
}
static inline const T* get_addr(const std::array<T,N>& vec) {
return mpi_type_traits<T>::get_addr( vec.front() );
}
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// std::list<T> traits
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <class T>
struct mpi_type_traits<std::list<T>> {
static inline size_t get_size(const std::list<T>& vec) { return 1; }
static MPI_Datatype get_type(const std::list<T>& l) {
// we have to get the create an MPI_Datatype containing the offsets
// of the current object
// we consider the offsets starting from the first element
std::vector<MPI_Aint> address( l.size() );
std::vector<int> dimension( l.size() );
std::vector<MPI_Datatype> types( l.size() );
std::vector<int>::iterator dim_it = dimension.begin();
std::vector<MPI_Aint>::iterator address_it = address.begin();
std::vector<MPI_Datatype>::iterator type_it = types.begin();
MPI_Aint base_address;
MPI_Address(const_cast<T*>(&l.front()), &base_address);
*(type_it++) = mpi_type_traits<T>::get_type( l.front() );
*(dim_it++) = static_cast<int>(mpi_type_traits<T>::get_size( l.front() ));
*(address_it++) = 0;
typename std::list<T>::const_iterator begin = l.begin();
++begin;
std::for_each(begin, l.cend(), [&](const T& curr) {
assert( address_it != address.end() &&
type_it != types.end() &&
dim_it != dimension.end() );
MPI_Address(const_cast<T*>(&curr), &*address_it);
*(address_it++) -= base_address;
*(type_it++) = mpi_type_traits<T>::get_type( curr );
*(dim_it++) = static_cast<int>(mpi_type_traits<T>::get_size( curr ));
}
);
MPI_Datatype list_dt;
MPI_Type_create_struct(static_cast<int>(l.size()), &dimension.front(), &address.front(), &types.front(), &list_dt);
MPI_Type_commit( &list_dt );
return list_dt;
}
static inline const T* get_addr(const std::list<T>& list) {
return mpi_type_traits<T>::get_addr( list.front() );
}
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// msg: represent a single message which can be provided to the <<, <, >>, >
// operations
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <class MsgTy>
struct msg_impl {
typedef MsgTy value_type;
// Builds a msg wrapping v
msg_impl(MsgTy& v, int tag = 0) : m_data(v), m_tag(tag){ }
// Returns the address to the first element of the contained data
inline void* addr() {
return (void*) mpi_type_traits<MsgTy>::get_addr(m_data);
}
inline const void* addr() const {
return (const void*) mpi_type_traits<MsgTy>::get_addr(m_data);
}
inline MsgTy& get() { return m_data; }
inline const MsgTy& get() const { return m_data; }
// Returns the dimension of this message
inline size_t size() const {
return mpi_type_traits<MsgTy>::get_size(m_data);
}
inline MPI_Datatype type() const {
return mpi_type_traits<MsgTy>::get_type(m_data);
}
// getter/setter for m_tag
inline const int& tag() const { return m_tag; }
inline int& tag() { return m_tag; }
private:
MsgTy& m_data;
int m_tag;
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Specializaton for class MsgTy for const types in this case we don't keep the
// reference to the object passed to the constructor, but we make a copy of it
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <class MsgTy>
struct msg_impl <const MsgTy> {
typedef const MsgTy value_type;
// Builds a msg wrapping v
msg_impl(const MsgTy& v, int tag = 0) : m_data(v), m_tag(tag){ }
// Returns the enclosed data
inline const void* addr() const {
return mpi_type_traits<MsgTy>::get_addr(m_data);
}
inline const MsgTy& get() const { return m_data; }
// Returns the dimension of this message
inline size_t size() const {
return mpi_type_traits<MsgTy>::get_size(m_data);
}
inline MPI_Datatype type() const {
return mpi_type_traits<MsgTy>::get_type(m_data);
}
// getter/setter for m_tag
inline const int& tag() const { return m_tag; }
inline int& tag() { return m_tag; }
private:
const MsgTy m_data;
int m_tag;
};
template <class T>
msg_impl<T> msg(T& raw, int tag=0) { return msg_impl<T>(raw, tag); }
// Expection which is thrown every time a communication fails
struct comm_error : public std::logic_error {
comm_error(const std::string& msg) :
std::logic_error(msg) { }
};
class status;
template <class T>
class request;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// comm: is the abstraction of the MPI_Comm class
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class comm{
MPI_Comm comm_m;
int comm_size;
comm(MPI_Comm comm): comm_m(comm), comm_size(-1) { }
// Check whether MPI_Init has been called
void check_init() {
int flag;
MPI_Initialized(&flag);
assert(flag != 0 &&
"FATAL: MPI environment not initialized (MPI_Init not called)");
}
public:
// MPI_COMM_WORLD
static comm world;
inline size_t rank() {
check_init();
int out_rank;
MPI_Comm_rank(comm_m, &out_rank);
return out_rank;
}
inline size_t size() {
check_init();
// Get the size for this communicator
if(comm_size == -1) {
MPI_Comm_size(comm_m, &comm_size);
}
return comm_size;
}
inline endpoint operator()( const int& rank_id );
};
comm comm::world = comm(MPI_COMM_WORLD);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// endpoint: represent the src or dest of an MPI channel. Provides streaming
// operations to send/recv messages (msg<T>) both in a synchronous or asynch
// ronous way.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class endpoint {
const int m_rank; // The rank of this endpoint
const MPI_Comm& m_comm; // The MPI communicator this endpoing
// belongs to
public:
endpoint(const int& rank, const MPI_Comm& com):
m_rank(rank), m_comm(com) { }
// Send a generic message to this endpoint (synchronously)
template <class MsgType>
inline endpoint& operator<<(const msg_impl<MsgType>& m) {
MPI_Datatype&& dt = m.type();
if ( MPI_Send( const_cast<void*>(m.addr()), static_cast<int>(m.size()), dt,
m_rank, m.tag(), m_comm
) == MPI_SUCCESS ) {
return *this;
}
std::ostringstream ss;
ss << "ERROR in MPI rank '" << comm::world.rank()
<< "': Failed to send message to destination rank '"
<< m_rank << "'";
throw comm_error( ss.str() );
}
// Send a generic raw type to this endpoint (synchronously)
template <class RawType>
inline endpoint& operator<<(const RawType& m) {
return operator<<(msg_impl<const RawType>(m));
}
// Receive from this endpoint (synchronously)
template <class RawType>
inline status operator>>(RawType& m);
template <class MsgType>
inline status operator>>(const msg_impl<MsgType>& m);
// Receive from this endpoing (asynchronously)
template <class MsgType>
inline request<MsgType> operator>(const msg_impl<MsgType>& m) {
MPI_Request req;
if( MPI_Irecv( const_cast<void*>(m.addr()), static_cast<int>(m.size()), m.type(),
m_rank, m.tag(), m_comm, &req
) != MPI_SUCCESS ) {
std::ostringstream ss;
ss << "ERROR in MPI rank '" << comm::world.rank()
<< "': Failed to receive message from destination rank '"
<< m_rank << "'";
throw comm_error( ss.str() );
}
return request<MsgType>(m_comm, req, m);
}
// Receive from this endpoing (asynchronously
template <class RawType>
inline request<RawType> operator>(RawType& m) {
return operator>( msg_impl<RawType>( m ) );
}
// Returns the rank of this endpoit
inline const int& rank() const { return m_rank; }
};
endpoint comm::operator()(const int& rank_id) {
return endpoint(rank_id, comm_m);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// status: keeps the status info for received messages.
// containes the sender of the message, tag and size of
// the message
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class status{
const MPI_Comm& m_comm;
const MPI_Status m_status;
const MPI_Datatype m_datatype;
public:
status(const MPI_Comm& com, const MPI_Status& s, const MPI_Datatype& dt):
m_comm(com), m_status(s), m_datatype(dt) { }
inline endpoint source(){
return endpoint(m_status.MPI_SOURCE, m_comm);
}
inline int count(){
int count;
MPI_Get_count(const_cast<MPI_Status*>(&m_status), m_datatype, &count);
return count;
}
inline int tag(){
return m_status.MPI_TAG;
}
inline int error(){
return m_status.MPI_ERROR;
}
};
template <class RawType>
inline status endpoint::operator>>(RawType& m) {
return operator>>( msg_impl<RawType>( m ) );
}
template <class MsgType>
inline status endpoint::operator>>(const msg_impl<MsgType>& m) {
MPI_Status s;
MPI_Datatype dt = m.type();
if(MPI_Recv( const_cast<void*>(m.addr()), static_cast<int>(m.size()), dt,
m_rank, m.tag(), m_comm, &s
) == MPI_SUCCESS ) {
return status(m_comm, s, dt);
}
std::ostringstream ss;
ss << "ERROR in MPI rank '" << comm::world.rank()
<< "': Failed to receive message from destination rank '"
<< m_rank << "'";
throw comm_error( ss.str() );
//sint size;
//MPI_Get_count(&s, MPI_BYTE, &size);
//std::cout << "RECEIVED " << size << std::endl;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// request<T> is an implementation of the future concept used for asynchronous
// receives/sends (TODO)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
template <class T>
class request{
MPI_Comm const& m_comm;
MPI_Request m_req;
const msg_impl<T> m_msg;
std::shared_ptr<status> m_status;
int done;
public:
request(MPI_Comm const& com, MPI_Request req, const msg_impl<T>& msg):
m_comm(com), m_req(req), m_msg(msg), done(0) { }
void cancel();
const T& get() {
if ( !done ) {
MPI_Status stat;
// wait to receive the message
MPI_Wait(&m_req, &stat);
done = 1;
m_status = std::make_shared<status>( m_comm, stat, m_msg.type() );
}
return m_msg.get();
}
status getStatus() {
if( isDone() ) {
return *m_status;
}
throw "not done";
}
bool isDone() {
if ( !done ) {
MPI_Status stat;
MPI_Test(&m_req, &done, &stat);
if ( done ) {
m_status = std::make_shared<status>( m_comm, stat, m_msg.type() );
}
}
return done;
}
};
const int any = MPI_ANY_SOURCE;
void init(int argc = 0, char* argv[] = NULL){ MPI_Init(&argc, &argv); }
void finalize(){ MPI_Finalize(); }
} // end mpi namespace
|
c948298eecda3995bc9a3264fa32a24b2d7ac27f
|
[
"CMake",
"C++"
] | 3
|
C++
|
rolandschulz/mpp
|
2a45581a28f5119c2277000e144bdfd71496bdde
|
9d2038fab290c2590a015b32d8f07b2f5b9c6400
|
refs/heads/master
|
<file_sep><script>
function changeImage()
{
element=document.getElementById('myimage')
if (element.src.match("star-bath"))
{
element.src="images/star-first.png";
}
else
{
element.src="images/star-bath.png";
}
}
</script>
<p>Нажмите на звезду, чтобы изменить цвет!</p>
<img id="myimage" onclick="changeImage()"
src="images/star-first.png" width="256" height="256">
|
aa7dfba4c526d6cb912414da146f905974c8c49d
|
[
"JavaScript"
] | 1
|
JavaScript
|
PlatonAlexandra/Repository1
|
cbd341d6ea7f4e339e3d101d3344fe365d9db635
|
78a44391fe2d3ded7078a2bd1c82011387fb283f
|
refs/heads/master
|
<file_sep>module["exports"] = [
"Xiaomi",
"Oppo",
"Apple",
"One Plus"
];<file_sep>var mobiles = {};
module["exports"] = mobiles;
mobiles.name = require("./name");
mobiles.price = require("./price");
mobiles.color = require("./color");
|
5799fdbd734f74760e04e92a08f4c407d98091bc
|
[
"JavaScript"
] | 2
|
JavaScript
|
Prashanth14/faker.js
|
ca432edbcb338dfe45530d4c126d01b22055ce03
|
96483e2a6999a6b8e9ff20e4092abc1153cb3e5f
|
refs/heads/master
|
<file_sep># CEXBlocks
[](https://travis-ci.org/Advanced-Jewish-Technologies/CEXBlocks)
[](https://cocoapods.org/pods/CEXBlocks)
[](https://cocoapods.org/pods/CEXBlocks)
[](https://cocoapods.org/pods/CEXBlocks)
## Example
To run the example project, clone the repo, and run `pod install` from the Example directory first.
## Requirements
## Installation
CEXBlocks is available through [CocoaPods](https://cocoapods.org). To install
it, simply add the following line to your Podfile:
```ruby
pod 'CEXBlocks'
```
## Author
<NAME>, <EMAIL>
## License
CEXBlocks is available under the MIT license. See the LICENSE file for more info.
<file_sep>use_frameworks!
target 'CEXBlocks_Tests' do
pod 'CEXBlocks', :path => '../'
end
<file_sep>#
# Be sure to run `pod lib lint CEXBlocks.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'CEXBlocks'
s.version = '0.6.0'
s.summary = 'Extension for default collection operations'
s.homepage = 'https://github.com/Advanced-Jewish-Technologies/CEXBlocks'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '<NAME>' => '<EMAIL>' }
s.requires_arc = true
s.source = { :git => 'https://github.com/Advanced-Jewish-Technologies/CEXBlocks.git', :tag => s.version.to_s }
s.ios.deployment_target = '8.0'
s.default_subspec = 'All'
s.subspec 'All' do |ss|
ss.dependency 'CEXBlocks/Core'
end
s.subspec 'Core' do |ss|
ss.source_files = 'CEXBlocks/BlocksKit.h', "CEXBlocks/BKDefines.h", 'CEXBlocks/Core/*.{h,m}'
end
end
|
4554f455e459618b435a242369500fb24414d9ce
|
[
"Markdown",
"Ruby"
] | 3
|
Markdown
|
Advanced-Jewish-Technologies/CEXBlocks
|
da32101ea3ed17c3836d19f8dd1d183cf87145a9
|
ec695102c9c04c9d61c66633506bfdd54d544a5a
|
refs/heads/master
|
<file_sep>/* Ejercicio Piedra Papel tijeras Propio
*/
// console.log("Piedra \=0, papel\=1 tijera\=2");
// Array
var elemento_juego = ["Piedra", "Papel", "Tijera"];
function game(jugador1, jugador2){
switch(elemento_juego) {
case jugador1 == jugador2 :
console.log('Empate');
break;
case jugador1 == 0 && jugador2 == 1 :
console.log('Gana Jugador jugador2');
break;
case jugador1 == 0 && jugador2 == 2 :
console.log('Gana Jugador jugador1');
break;
case jugador1 == 1 && jugador2 == 0 :
console.log('Gana Jugador jugador1');
break;
case jugador1 == 1 && jugador2 == 2 :
console.log('Gana Jugador jugador2');
break;
}
}
|
1398f80eaf1a7259dca7ba91ff62c745db50c101
|
[
"JavaScript"
] | 1
|
JavaScript
|
Ljotamr91/PiedraPapelTijera
|
eb61227920f2af0cbdb84a47e32b6bf262723952
|
53d16893220a58bbbb61004e0e9f55456a6ec315
|
refs/heads/master
|
<file_sep>package mvc.controller;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import test.bean.BoardDao;
public class deleteActAction implements superAction{
public String executeAction(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int num = Integer.parseInt(request.getParameter("num"));
String pageNum = request.getParameter("pageNum");
String passwd = request.getParameter("passwd");
BoardDao boarddao = BoardDao.getInstance();
boolean delete = false;
if(session.getAttribute("memid").equals("krack1")){
delete = boarddao.deleteArticleAdmin(num);
}else{
delete = boarddao.deleteArticle(num, passwd);
}
request.setAttribute("pageNum", pageNum);
request.setAttribute("delete", delete);
return "/board/deleteAct.jsp";
}
}
<file_sep>package mvc.controller;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import test.bean.Dao;
public class withdrawDoneAction implements superAction{
public String executeAction(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
String pw = request.getParameter("pw");
Dao dao = Dao.getInstance();
boolean result = dao.delete(session.getAttribute("memid").toString(), pw);
request.setAttribute("result", result);
if(result == true){
session.invalidate();
Cookie cookie = new Cookie("cooid", "");
cookie.setMaxAge(0);
response.addCookie(cookie);
}
return "/home/withdrawDone.jsp";
}
}
<file_sep>package test.bean;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.util.*;
public class BoardDao {
private Connection conn = null;
private ResultSet rs = null;
private PreparedStatement pstmt = null;
private static BoardDao boarddao = new BoardDao();
public static BoardDao getInstance() {
return boarddao;
}
private BoardDao() {}
private Connection getConnection() throws Exception {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)envCtx.lookup("jdbc/jsptest");
return ds.getConnection();
}
public int getArticleCount() throws Exception {
int count = 0;
try {
conn = getConnection();
pstmt = conn.prepareStatement("select count(*) from board");
rs = pstmt.executeQuery();
if(rs.next()) {
count = rs.getInt(1);
}
} catch(Exception ex) {
ex.printStackTrace();
} finally {
if (rs != null) try { rs.close(); } catch(SQLException ex) {}
if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {}
if (conn != null) try { conn.close(); } catch(SQLException ex) {}
}
return count;
}
public int getSearchArticleCount(String id) throws Exception {
int count = 0;
try {
conn = getConnection();
pstmt = conn.prepareStatement("select count(*) from board where writer = ?");
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()) {
count = rs.getInt(1);
}
} catch(Exception ex) {
ex.printStackTrace();
} finally {
if (rs != null) try { rs.close(); } catch(SQLException ex) {}
if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {}
if (conn != null) try { conn.close(); } catch(SQLException ex) {}
}
return count;
}
public List getArticles(int start, int end) throws Exception {
List articleList = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement("select num,writer,email,subject,passwd,reg_date,ref,re_step,re_level,content,ip,readcount,r "+
"from (select num,writer,email,subject,passwd,reg_date,ref,re_step,re_level,content,ip,readcount,rownum r " +
"from (select num,writer,email,subject,passwd,reg_date,ref,re_step,re_level,content,ip,readcount " +
"from board order by ref desc, re_step asc) order by ref desc, re_step asc ) where r >= ? and r <= ? ");
pstmt.setInt(1, start);
pstmt.setInt(2, end);
rs = pstmt.executeQuery();
if(rs.next()){
articleList = new ArrayList(end);
do{
BoardDto boarddto = new BoardDto();
boarddto.setNum(rs.getInt("num"));
boarddto.setWriter(rs.getString("writer"));
boarddto.setEmail(rs.getString("email"));
boarddto.setSubject(rs.getString("subject"));
boarddto.setPasswd(rs.getString("<PASSWORD>"));
boarddto.setReg_date(rs.getTimestamp("reg_date"));
boarddto.setReadcount(rs.getInt("readcount"));
boarddto.setRef(rs.getInt("ref"));
boarddto.setRe_step(rs.getInt("re_step"));
boarddto.setRe_level(rs.getInt("re_level"));
boarddto.setContent(rs.getString("content"));
boarddto.setIp(rs.getString("ip"));
articleList.add(boarddto);
}while(rs.next());
}
}catch(Exception e) {
e.printStackTrace();
}finally{
if (rs != null) try { rs.close(); } catch(SQLException ex) {}
if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {}
if (conn != null) try { conn.close(); } catch(SQLException ex) {}
}
return articleList;
}
public List getSearchArticles(int start, int end, String id) throws Exception {
List articleList = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement("select num,writer,email,subject,passwd,reg_date,ref,re_step,re_level,content,ip,readcount,r "
+ "from (select num,writer,email,subject,passwd,reg_date,ref,re_step,re_level,content,ip,readcount,rownum r "
+ "from (select num,writer,email,subject,passwd,reg_date,ref,re_step,re_level,content,ip,readcount "
+ "from board where writer=? order by reg_date desc)) where r >=? and r<=?");
pstmt.setString(1, id);
pstmt.setInt(2, start);
pstmt.setInt(3, end);
rs = pstmt.executeQuery();
if(rs.next()){
articleList = new ArrayList(end);
do{
BoardDto boarddto = new BoardDto();
boarddto.setNum(rs.getInt("num"));
boarddto.setWriter(rs.getString("writer"));
boarddto.setEmail(rs.getString("email"));
boarddto.setSubject(rs.getString("subject"));
boarddto.setPasswd(rs.getString("passwd"));
boarddto.setReg_date(rs.getTimestamp("reg_date"));
boarddto.setReadcount(rs.getInt("readcount"));
boarddto.setRef(rs.getInt("ref"));
boarddto.setRe_step(rs.getInt("re_step"));
boarddto.setRe_level(rs.getInt("re_level"));
boarddto.setContent(rs.getString("content"));
boarddto.setIp(rs.getString("ip"));
articleList.add(boarddto);
}while(rs.next());
}
}catch(Exception e) {
e.printStackTrace();
}finally{
if (rs != null) try { rs.close(); } catch(SQLException ex) {}
if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {}
if (conn != null) try { conn.close(); } catch(SQLException ex) {}
}
return articleList;
}
public BoardDto getArticle(int num) throws Exception {
BoardDto boarddto = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement("update board set readcount = readcount+1 where num = ?");
pstmt.setInt(1, num);
pstmt.executeUpdate();
pstmt = conn.prepareStatement("select * from board where num = ?");
pstmt.setInt(1, num);
rs = pstmt.executeQuery();
if(rs.next()) {
boarddto = new BoardDto();
boarddto.setNum(rs.getInt("num"));
boarddto.setWriter(rs.getString("writer"));
boarddto.setEmail(rs.getString("email"));
boarddto.setSubject(rs.getString("subject"));
boarddto.setPasswd(rs.<PASSWORD>("<PASSWORD>"));
boarddto.setReg_date(rs.getTimestamp("reg_date"));
boarddto.setReadcount(rs.getInt("readcount"));
boarddto.setRef(rs.getInt("ref"));
boarddto.setRe_step(rs.getInt("re_step"));
boarddto.setRe_level(rs.getInt("re_level"));
boarddto.setContent(rs.getString("content"));
boarddto.setIp(rs.getString("ip"));
}
}catch(Exception e) {
e.printStackTrace();
}finally{
if (rs != null) try { rs.close(); } catch(SQLException ex) {}
if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {}
if (conn != null) try { conn.close(); } catch(SQLException ex) {}
}
return boarddto;
}
public void insertArticle(BoardDto boarddto) throws Exception {
int num = boarddto.getNum();
int ref = boarddto.getRef();
int re_step = boarddto.getRe_step();
int re_level = boarddto.getRe_level();
int number = 0;
try {
conn = getConnection();
pstmt = conn.prepareStatement("select max(num) from board");
rs = pstmt.executeQuery();
if(rs.next()) {
number = rs.getInt(1)+1;
}
else {
number = 1;
}
if(num != 0) {
pstmt = conn.prepareStatement("update board set re_step = re_step+1 where ref = ? and re_step > ?");
pstmt.setInt(1, ref);
pstmt.setInt(2, re_step);
pstmt.executeUpdate();
re_step = re_step +1;
re_level = re_level+1;
}else{
ref = number;
re_step = 0;
re_level = 0;
}
pstmt = conn.prepareStatement("insert into board(num,writer,subject,email,content,passwd,reg_date,ip,ref,re_step,re_level) values(board_seq.nextval,?,?,?,?,?,?,?,?,?,?)");
pstmt.setString(1,boarddto.getWriter());
pstmt.setString(2,boarddto.getSubject());
pstmt.setString(3,boarddto.getEmail());
pstmt.setString(4,boarddto.getContent());
pstmt.setString(5,boarddto.getPasswd());
pstmt.setTimestamp(6,boarddto.getReg_date());
pstmt.setString(7,boarddto.getIp());
pstmt.setInt(8,ref);
pstmt.setInt(9,re_step);
pstmt.setInt(10,re_level);
pstmt.executeUpdate();
}catch(Exception e) {
e.printStackTrace();
}finally{
if (rs != null) try { rs.close(); } catch(SQLException ex) {}
if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {}
if (conn != null) try { conn.close(); } catch(SQLException ex) {}
}
}
public boolean deleteArticle(int num, String passwd) {
boolean delete = false;
try{
conn = getConnection();
pstmt = conn.prepareStatement("select passwd from board where num = ?");
pstmt.setInt(1, num);
rs = pstmt.executeQuery();
if(rs.next()){
if(rs.getString("passwd").equals(passwd)) {
pstmt = conn.prepareStatement("delete from board where num = ?");
pstmt.setInt(1, num);
pstmt.executeUpdate();
delete = true;
}
}
}catch(Exception e) {
e.printStackTrace();
}finally{
if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {}
if (conn != null) try { conn.close(); } catch(SQLException ex) {}
}
return delete;
}
public boolean deleteArticleAdmin(int num) {
boolean delete = true;
try{
conn = getConnection();
pstmt = conn.prepareStatement("delete from board where num = ?");
pstmt.setInt(1, num);
pstmt.executeUpdate();
}catch(Exception e) {
e.printStackTrace();
}finally{
if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {}
if (conn != null) try { conn.close(); } catch(SQLException ex) {}
}
return delete;
}
public BoardDto updateGetArticle(int num) throws Exception {
BoardDto boarddto = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement("select * from board where num = ?");
pstmt.setInt(1, num);
rs = pstmt.executeQuery();
if(rs.next()) {
boarddto = new BoardDto();
boarddto.setNum(rs.getInt("num"));
boarddto.setWriter(rs.getString("writer"));
boarddto.setEmail(rs.getString("email"));
boarddto.setSubject(rs.getString("subject"));
boarddto.setPasswd(<PASSWORD>("<PASSWORD>"));
boarddto.setReg_date(rs.getTimestamp("reg_date"));
boarddto.setReadcount(rs.getInt("readcount"));
boarddto.setRef(rs.getInt("ref"));
boarddto.setRe_step(rs.getInt("re_step"));
boarddto.setRe_level(rs.getInt("re_level"));
boarddto.setContent(rs.getString("content"));
boarddto.setIp(rs.getString("ip"));
}
}catch(Exception e) {
e.printStackTrace();
}finally{
if (rs != null) try { rs.close(); } catch(SQLException ex) {}
if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {}
if (conn != null) try { conn.close(); } catch(SQLException ex) {}
}
return boarddto;
}
public int updateArticle(BoardDto boarddto) {
int result = 0;
try{
conn = getConnection();
pstmt = conn.prepareStatement("select passwd from board where num = ?"); {
pstmt.setInt(1, boarddto.getNum());
rs = pstmt.executeQuery();
if(rs.next()) {
if(rs.getString("passwd").equals(boarddto.getPasswd())) {
pstmt = conn.prepareStatement(
"update board set "
+ "writer = ?, "
+ "subject = ?, "
+ "email = ?, "
+ "content = ? "
+ "where num = ?");
pstmt.setString(1, boarddto.getWriter());
pstmt.setString(2, boarddto.getSubject());
pstmt.setString(3, boarddto.getEmail());
pstmt.setString(4, boarddto.getContent());
pstmt.setInt(5, boarddto.getNum());
pstmt.executeUpdate();
result = 1;
}
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
if (rs != null) try { rs.close(); } catch(SQLException ex) {}
if (pstmt != null) try { pstmt.close(); } catch(SQLException ex) {}
if (conn != null) try { conn.close(); } catch(SQLException ex) {}
}
return result;
}
}
<file_sep>package mvc.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import test.bean.Dao;
public class findPwActAction implements superAction{
public String executeAction(HttpServletRequest request, HttpServletResponse response){
String id = request.getParameter("id");
Dao dao = Dao.getInstance();
String pw = dao.findPw(id);
request.setAttribute("pw", pw);
return "/home/findPwAct.jsp";
}
}
<file_sep>package mvc.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import test.bean.Dao;
public class findPwFormAction implements superAction {
public String executeAction(HttpServletRequest request, HttpServletResponse response){
return "/home/findPwForm.jsp";
}
}
<file_sep>package test.bean;
import java.sql.*;
import java.util.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class Dao {
private Connection conn = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
private static Dao dao = new Dao(); //�̱� �ν��Ͻ� ���� �ܺο��� ��ü�� �������� ���ϵ����Ѵ�.
private Dao() {};
public static Dao getInstance() {
return dao;
}
//������ �����Ѵ�.
private Connection getConnection() throws Exception {
/*Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:@masterkh.iptime.org:7000:orcl";
conn = DriverManager.getConnection(url, "java02", "java02");*/
Context ctx = new InitialContext(); //context�� ��� ������ �д´�.
Context env = (Context)ctx.lookup("java:comp/env"); // ���߿��� �ڹ� ���� �ڵ带 ����.
DataSource ds = (DataSource)env.lookup("jdbc/jsptest"); // ���߿��� ������ jdbc��/jsptest�� �ִ� �ڵ带 �ҷ��´�.
conn = ds.getConnection();
return conn;
}
//select query ����
public ArrayList<Dto> select() { //����Ÿ���� arrayList�� �Ѵ�.
ArrayList<Dto> list = new ArrayList<Dto>();
try {
conn = getConnection();
pstmt = conn.prepareStatement("select * from member_info");
rs = pstmt.executeQuery();
//rs�� ���� �о���� �����͵��� Dto�� �����Ͽ� Dto�� ArrayList�� �����Ѵ�.
while(rs.next()) {
Dto dto = new Dto();
dto.setId(rs.getString("id"));
dto.setPass1(rs.getString("pw"));
dto.setBirth(rs.getString("birth"));
dto.setSex(rs.getString("sex"));
dto.setAddress(rs.getString("address"));
dto.setFirst_number(rs.getString("first_number"));
dto.setSecond_number(rs.getString("second_number"));
dto.setThird_number(rs.getString("third_number"));
dto.setEmail_id(rs.getString("email_id"));
dto.setEmail_site_text(rs.getString("email_site"));
dto.setReceive(rs.getString("email_receive"));
dto.setname(rs.getString("name"));
dto.setReg_date(rs.getTimestamp("reg"));
list.add(dto);
}
}catch(Exception e) {
e.printStackTrace();
}finally{
try {if(rs != null)rs.close();}catch(SQLException s) {s.printStackTrace();}
try {if(pstmt != null)pstmt.close();}catch(SQLException s) {s.printStackTrace();}
try {if(conn != null)conn.close();}catch(SQLException s) {s.printStackTrace();}
}
return list;
}
public void insert(Dto dto) { //�Ű������� Dto�� �� �����Ͱ� ����Ǿ��ִ� dto�� �����´�.
try {
conn = getConnection();
//�Է¹��� data�� ���� insert query ����
pstmt = conn.prepareStatement("insert into member_info values(?,?,?,?,?,?,?,?,?,?,?,sysdate,?)");
pstmt.setString(1, dto.getId());
pstmt.setString(2, dto.getPass1());
pstmt.setString(3, dto.getBirth());
pstmt.setString(4, dto.getSex());
pstmt.setString(5, dto.getAddress());
pstmt.setString(6, dto.getFirst_number());
pstmt.setString(7, dto.getSecond_number());
pstmt.setString(8, dto.getThird_number());
pstmt.setString(9, dto.getEmail_id());
pstmt.setString(10, dto.getEmail_site_text());
pstmt.setString(11, dto.getReceive());
pstmt.setString(12, dto.getname());
pstmt.executeUpdate();
}catch(Exception e) {
e.printStackTrace();
}finally {
try {if(pstmt != null)pstmt.close();}catch(SQLException s) {s.printStackTrace();}
try {if(conn != null)conn.close();}catch(SQLException s) {s.printStackTrace();}
}
}
public int loginCheck(Dto dto){
int result = 0;
try {
conn = getConnection();
pstmt = conn.prepareStatement("select id, pw from member_info where id=?");
pstmt.setString(1, dto.getLogin_id());
rs = pstmt.executeQuery();
if(rs.next()) {
if(!rs.getString("pw").equals(dto.getLogin_pw())) {
result = 2;
}else{
result = 3;
}
}else {
result = 1;
}
}catch(Exception e) {
e.printStackTrace();
}finally{
try {if(rs != null)rs.close();}catch(SQLException s) {s.printStackTrace();}
try {if(pstmt != null)pstmt.close();}catch(SQLException s) {s.printStackTrace();}
try {if(conn != null)conn.close();}catch(SQLException s) {s.printStackTrace();}
}
return result;
}
public int select_id(String id){
int result = 0;
try {
conn = getConnection();
pstmt = conn.prepareStatement("select id, pw from member_info where id=?");
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()) {
result = 1;
}else{
result = 2;
}
}catch(Exception e) {
e.printStackTrace();
}finally{
try {if(rs != null)rs.close();}catch(SQLException s) {s.printStackTrace();}
try {if(pstmt != null)pstmt.close();}catch(SQLException s) {s.printStackTrace();}
try {if(conn != null)conn.close();}catch(SQLException s) {s.printStackTrace();}
}
return result;
}
public boolean delete(String login_id, String login_pw) {
boolean result = false;
try {
conn = getConnection();
//�Է¹��� data�� ���� insert query ����
pstmt = conn.prepareStatement("delete from member_info where id = ? and pw = ?");
pstmt.setString(1, login_id);
pstmt.setString(2, login_pw);
pstmt.executeUpdate();
pstmt = conn.prepareStatement("select id from member_info where id = ?");
pstmt.setString(1, login_id);
rs = pstmt.executeQuery();
if(rs.next()) {
result = false;
}else{
result = true;
}
}catch(Exception e) {
e.printStackTrace();
}finally {
try {if(pstmt != null)pstmt.close();}catch(SQLException s) {s.printStackTrace();}
try {if(conn != null)conn.close();}catch(SQLException s) {s.printStackTrace();}
}
return result;
}
public Dto modifiyInfo(String id) {
Dto dto = new Dto();
try {
conn = getConnection();
//�Է¹��� data�� ���� insert query ����
pstmt = conn.prepareStatement("select * from member_info where id = ?");
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()) {
dto.setId(rs.getString("id"));
dto.setPass1(rs.getString("pw"));
dto.setBirth(rs.getString("birth"));
dto.setSex(rs.getString("sex"));
dto.setAddress(rs.getString("address"));
dto.setFirst_number(rs.getString("first_number"));
dto.setSecond_number(rs.getString("second_number"));
dto.setThird_number(rs.getString("third_number"));
dto.setEmail_id(rs.getString("email_id"));
dto.setEmail_site_text(rs.getString("email_site"));
dto.setReceive(rs.getString("email_receive"));
dto.setname(rs.getString("name"));
}
}catch(Exception e) {
e.printStackTrace();
}finally {
try {if(pstmt != null)pstmt.close();}catch(SQLException s) {s.printStackTrace();}
try {if(conn != null)conn.close();}catch(SQLException s) {s.printStackTrace();}
}
return dto;
}
public void updateInfo(Dto dto) {
try {
conn = getConnection();
//�Է¹��� data�� ���� insert query ����
pstmt = conn.prepareStatement("update member_info set pw = ?, address = ?, first_number = ?, second_number = ?, third_number = ?, email_id = ?, email_site = ?, email_receive = ?, name = ? where id = ? ");
pstmt.setString(1, dto.getPass1());
pstmt.setString(2, dto.getAddress());
pstmt.setString(3, dto.getFirst_number());
pstmt.setString(4, dto.getSecond_number());
pstmt.setString(5, dto.getThird_number());
pstmt.setString(6, dto.getEmail_id());
pstmt.setString(7, dto.getEmail_site_text());
pstmt.setString(8, dto.getReceive());
pstmt.setString(9, dto.getname());
pstmt.setString(10, dto.getId());
pstmt.executeUpdate();
}catch(Exception e) {
e.printStackTrace();
}finally {
try {if(pstmt != null)pstmt.close();}catch(SQLException s) {s.printStackTrace();}
try {if(conn != null)conn.close();}catch(SQLException s) {s.printStackTrace();}
}
}
public boolean findId(String id) throws Exception {
boolean result = false;
try {
conn = getConnection();
pstmt = conn.prepareStatement("select * from member_info where id = ?");
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()) {
result= true;
}
}catch(Exception e) {
e.printStackTrace();
}finally {
try {if(rs != null)rs.close();}catch(SQLException s) {s.printStackTrace();}
try {if(pstmt != null)pstmt.close();}catch(SQLException s) {s.printStackTrace();}
try {if(conn != null)conn.close();}catch(SQLException s) {s.printStackTrace();}
}
return result;
}
public ArrayList<String> checkId(String first_number, String second_number, String third_number){
ArrayList<String> list = new ArrayList<String>();
try {
conn = getConnection();
pstmt = conn.prepareStatement("select id from member_info where first_number = ? and second_number = ? and third_number = ? ");
pstmt.setString(1, first_number);
pstmt.setString(2, second_number);
pstmt.setString(3, third_number);
rs = pstmt.executeQuery();
while(rs.next()) {
list.add(rs.getString("id"));
}
}catch(Exception e) {
e.printStackTrace();
}finally{
try {if(rs != null)rs.close();}catch(SQLException s) {s.printStackTrace();}
try {if(pstmt != null)pstmt.close();}catch(SQLException s) {s.printStackTrace();}
try {if(conn != null)conn.close();}catch(SQLException s) {s.printStackTrace();}
}
return list;
}
public boolean findPw_Check(String id, String email_id, String email_site_text) {
boolean result = false;
try {
conn = getConnection();
pstmt = conn.prepareStatement("select id from member_info where id=? and email_id = ? and email_site = ?");
pstmt.setString(1, id);
pstmt.setString(2, email_id);
pstmt.setString(3, email_site_text);
rs = pstmt.executeQuery();
if(rs.next()) {
result = true;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {if(rs != null)rs.close();}catch(SQLException s) {s.printStackTrace();}
try {if(pstmt != null)pstmt.close();}catch(SQLException s) {s.printStackTrace();}
try {if(conn != null)conn.close();}catch(SQLException s) {s.printStackTrace();}
}
return result;
}
public String findPw(String id) {
String pw = "";
try {
conn = getConnection();
pstmt = conn.prepareStatement("select pw from member_info where id=?");
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if(rs.next()){
pw = rs.getString("pw");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {if(rs != null)rs.close();}catch(SQLException s) {s.printStackTrace();}
try {if(pstmt != null)pstmt.close();}catch(SQLException s) {s.printStackTrace();}
try {if(conn != null)conn.close();}catch(SQLException s) {s.printStackTrace();}
}
return pw;
}
}
<file_sep>package mvc.controller;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import test.bean.Dao;
public class findPwAction implements superAction{
public String executeAction(HttpServletRequest request, HttpServletResponse response){
String id = request.getParameter("id");
String email_id = request.getParameter("email_id");
String email_site_text = request.getParameter("email_site_text");
Dao dao = Dao.getInstance();
boolean result = dao.findPw_Check(id, email_id, email_site_text);
if(result == true){
try{
String checknum = Integer.toString((int)(Math.random()*89999 + 10000));
request.setAttribute("checknum", checknum);
String host = "smtp.naver.com";
final String username = "<EMAIL>";
final String password = "<PASSWORD>";
int port=465;
String recipient = email_id+"@"+email_site_text;
String subject = "LEDhouse 비밀번호찾기 인증번호입니다.";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.trust", host);
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
String un=username;
String pw=<PASSWORD>;
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(un, pw);
}
});
session.setDebug(true); //for debug
Message mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress("<EMAIL>"));
mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
mimeMessage.setSubject(subject);
mimeMessage.setText("인증번호 : " + checknum);
Transport.send(mimeMessage);
}catch(Exception e){
e.printStackTrace();
}
request.setAttribute("id", id);
}
request.setAttribute("result", result);
return "/home/findPw.jsp";
}
}
<file_sep>/Mypage/confirmId.hjh=mvc.controller.confirmIdAction
/Mypage/enter_done.hjh=mvc.controller.enter_doneAction
/Mypage/enter.hjh=mvc.controller.enterAction
/Mypage/findId.hjh=mvc.controller.findIdAction
/Mypage/findIdAct.hjh=mvc.controller.findIdActAction
/Mypage/findPw.hjh=mvc.controller.findPwAction
/Mypage/findPwAct.hjh=mvc.controller.findPwActAction
/Mypage/findPwForm.hjh=mvc.controller.findPwFormAction
/Mypage/login_complete.hjh=mvc.controller.login_completeAction
/Mypage/login.hjh=mvc.controller.loginAction
/Mypage/logout.hjh=mvc.controller.logoutAction
/Mypage/modify.hjh=mvc.controller.modifyAction
/Mypage/modifyDone.hjh=mvc.controller.modifyDoneAction
/Mypage/withdraw.hjh=mvc.controller.withdrawAction
/Mypage/withdrawDone.hjh=mvc.controller.withdrawDoneAction
/Mypage/confirmPw.hjh=mvc.controller.confirmPwAction
/Mypage/content.hjh=mvc.controller.contentAction
/Mypage/delete.hjh=mvc.controller.deleteAction
/Mypage/deleteAct.hjh=mvc.controller.deleteActAction
/Mypage/list.hjh=mvc.controller.listAction
/Mypage/updateAct.hjh=mvc.controller.updateActAction
/Mypage/updateForm.hjh=mvc.controller.updateFormAction
/Mypage/writeForm.hjh=mvc.controller.writeFormAction
/Mypage/writeFormAct.hjh=mvc.controller.writeFormActAction<file_sep>package mvc.controller;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import test.bean.Dao;
public class confirmIdAction implements superAction {
public String executeAction(HttpServletRequest request, HttpServletResponse response) {
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String id = request.getParameter("id");
Dao dao = Dao.getInstance();
int result = dao.select_id(id);
request.setAttribute("result", result);
request.setAttribute("id", id);
return "/home/confirmId.jsp";
}
}
<file_sep>package mvc.controller;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import test.bean.Dao;
import test.bean.Dto;
public class login_completeAction implements superAction{
public String executeAction(HttpServletRequest request, HttpServletResponse response) {
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String login_id = request.getParameter("login_id");
String login_pw = request.getParameter("login_pw");
Dto dto = new Dto();
dto.setLogin_id(login_id);
dto.setLogin_pw(login_pw);
Dao dao = Dao.getInstance();
int result = dao.loginCheck(dto);
if(result == 3) {
if(request.getParameter("keeplogin") != null){
Cookie cookie = new Cookie("cooid", dto.getLogin_id());
cookie.setMaxAge(300);
response.addCookie(cookie);
}
HttpSession session = request.getSession();
session.setAttribute("memid", dto.getLogin_id());
}
request.setAttribute("result", result);
return "/home/login_complete.jsp";
}
}
<file_sep>package mvc.controller;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import test.bean.BoardDao;
import test.bean.BoardDto;
public class contentAction implements superAction {
public String executeAction(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
try {
request.setCharacterEncoding("utf-8");
int num = Integer.parseInt(request.getParameter("num"));
String pageNum = request.getParameter("pageNum");
String writer = request.getParameter("writer");
String passwd = request.getParameter("passwd");
String ok = request.getParameter("ok");
BoardDao boarddao = BoardDao.getInstance();
BoardDto boarddto = boarddao.getArticle(num);
int ref=boarddto.getRef();
int re_step=boarddto.getRe_step();
int re_level=boarddto.getRe_level();
String content = boarddto.getContent().replace("\r\n", "<br />");
boarddto.setContent(content);
request.setAttribute("ref", ref);
request.setAttribute("re_step", re_step);
request.setAttribute("re_level", re_level);
request.setAttribute("boarddto", boarddto);
session.getAttribute("memid");
request.setAttribute("num", num);
request.setAttribute("pageNum", pageNum);
request.setAttribute("writer", writer);
request.setAttribute("passwd", <PASSWORD>);
request.setAttribute("ok", ok);
} catch (Exception e) {
e.printStackTrace();
}
return "/board/content.jsp";
}
}
|
944865cd4f5cf5987c2e246709c7d1533fd12902
|
[
"Java",
"INI"
] | 11
|
Java
|
krack1/Mypage
|
a2ca121a95faf2ec2065b1fbba3a3cbc04aaae50
|
757925fed11c96cbe9de23c508f3f2c967c94dd4
|
refs/heads/master
|
<repo_name>arek-jozwiak-coderslab/katjees04m4<file_sep>/a_Zadania/a_Dzien_1/c_Wzorce_projektowe/SubscriberObserver.java
package a_Zadania.a_Dzien_1.c_Wzorce_projektowe;
public class SubscriberObserver implements Observer {
@Override
public void update(String title) {
}
}
<file_sep>/a_Zadania/b_Dzien_2/c_Strumienie/Employee.java
package a_Zadania.b_Dzien_2.c_Strumienie;
import java.time.LocalDate;
public class Employee {
private String firstName;
private String lastName;
private char sex;
private LocalDate birthday;
private double salary;
@Override
public String toString() {
return "Employee{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", sex=" + sex +
", birthday=" + birthday +
", salary=" + salary +
'}';
}
public Employee(String firstName, String lastName, char sex, LocalDate birthday, double salary) {
this.firstName = firstName;
this.lastName = lastName;
this.sex = sex;
this.birthday = birthday;
this.salary = salary;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public LocalDate getBirthday() {
return birthday;
}
public void setBirthday(LocalDate birthday) {
this.birthday = birthday;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
<file_sep>/a_Zadania/b_Dzien_2/c_Strumienie/README.md
<img alt="Logo" src="http://coderslab.pl/svg/logo-coderslab.svg" width="400">
# Java Zaawansowane - Strumienie
#### Zadanie 1 - rozwiązywane z wykładowcą.
1. Napisz program, który przy wykorzystaniu strumieni danych, dla podanej listy obiektów typu `String`:
- wypisze na ekranie wielkimi literami wszystkie łańcuchy zaczynające się na literę „a” lub „s”, posortowane alfabetycznie
- zwróci listę, która powstanie poprzez wybranie z listy unikalnych łańcuchów o długości równej 5
- utworzy obiekt typu `String`, zbudowany z posortowanych elementów listy ograniczonych do 3 pierwszych znaków każdego elementu, oddzielonych przecinkami
#### Zadanie 2 - rozwiązywane z wykładowcą.
2. Napisz program, który będzie posiadał klasę reprezentującą pracownika `Employee`, zawierającą atrybuty takie jak `imię`, `nazwisko`, `płeć`, `data urodzenia`, `wysokość wynagrodzenia`.
Utwórz kilka obiektów klasy `Employee`, a następnie:
- wypisz na ekranie wszystkich pracowników, których nazwisko zaczyna się na literę „N”
- wypisz na ekranie wszystkich pracowników, którzy są w wieku między 30 a 45 lat
- daj 5% podwyżki wszystkim kobietom, które są w wieku między 20 a 30 lat, a ich wynagrodzenie jest nie wyższe niż 3500 zł.
#### Zadanie 3
1. Na podstawie podanej listy:
````java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
````
utwórz listę, której elementy będą spełniać następujące warunki:
- kwadrat wartości pomniejszony o 5 będzie mniejszy od 20,
wykorzystaj gotowe wyrażenia lambda:
````
n -> n * n - 5
````
oraz:
````
n -> n < 20
````
#### Zadanie 4
1. Stwórz listę elementów typu `String`, następnie utwórz strumień, który:
- wypisze na konsoli długości elementów listy
- zwróci listę posortowaną alfabetycznie
- wypisze na konsoli elementy, które zawierają literę „c”
- zwróci sumę długości wszystkich elementów
- zwróci 3 pierwsze elementy posortowane alfabetycznie
**Repozytorium z ćwiczeniami zostanie usunięte 2 tygodnie po zakończeniu kursu. Spowoduje to też usunięcie wszystkich forków, które są zrobione z tego repozytorium.**
<file_sep>/a_Zadania/a_Dzien_1/a_Klasy_abstrakcyjne/dao/Main1.java
package a_Zadania.a_Dzien_1.a_Klasy_abstrakcyjne.dao;
import a_Zadania.a_Dzien_1.a_Klasy_abstrakcyjne.Car;
import a_Zadania.a_Dzien_1.a_Klasy_abstrakcyjne.Train;
import a_Zadania.a_Dzien_1.a_Klasy_abstrakcyjne.Vehicle;
public class Main1 {
public static void main(String[] args) {
Vehicle[] vehicles = new Vehicle[2];
Car car = new Car();
Train train = new Train();
vehicles[0] = car;
vehicles[1] = train;
for (int i = 0; i < vehicles.length; i++) {
System.out.println(vehicles[i]);
}
}
}
<file_sep>/a_Zadania/a_Dzien_1/c_Wzorce_projektowe/FacebookObserver.java
package a_Zadania.a_Dzien_1.c_Wzorce_projektowe;
public class FacebookObserver implements Observer {
@Override
public void update(String title) {
}
}
<file_sep>/c_Snippety/README.md
<img alt="Logo" src="http://coderslab.pl/svg/logo-coderslab.svg" width="400">
# Snippety
> Krótkie kawałki kodu, które pokazują zależności, rozwiązują popularne problemy oraz pokazują jak używać niektórych funkcji.
#### Klasy abstrakcyjne, interfejsy
* Aby zdefiniować metodę abstrakcyjną używamy słowa kluczowego **abstract**.
* Klasa jest abstrakcyjna jeżeli posiada przynajmniej jedną metodę abstrakcyjną.
* Aby zdefiniować interfejs używamy słowa kluczowego **interface** .
* Z klas abstrakcyjnych nie można tworzyć obiektów.
* Metody interfejsów są domyślnie abstrakcyjne i publiczne.
* Pola interfejsów są domyślnie statyczne i finalne.
* Klasa może implementować wiele interfejsów.
#### Przykład definicji interfejsu
````java
public interface Vehicle {
public void drive();
public void stop();
}
````
#### Przykład klasy implementującej interfejs
````java
public class Bike implements Vehicle{
@Override
public void drive() { }
@Override
public void stop() { }
}
````
#### Przykład metody domyślnej interfejsu (Java 8)
````java
public default int getPriority(){
return 0;
}
````
#### Przykład definicji klasy abstrakcyjnej
````java
public abstract class Vehicle {
public void go() {
this.startEngine();
}
public void stop() {
this.stopEngine();
}
abstract void startEngine();
abstract void stopEngine();
}
````
#### Podstawowe wbudowane interfejsy funkcyjne
- Predicate<T> - służy do testowania warunków. Metoda to - `boolean test(T t)`
Dokumentacja:
https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html
- Function<T,R> - zwraca wartość typu R, przyjmując jako argument atrybut typu T. Metoda to `R apply(T t)`
Dokumentacja:
https://docs.oracle.com/javase/8/docs/api/java/util/function/Function.html
-Consumer<T> - wykonuje operacje na przekazanym atrybucie nie zwraca wartości .Metoda to `void accept(T t)`
Dokumentacja:
https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html
Lista wszystkich wbudowanych interfejsów funkcyjnych z pakietu `java.util.function`:
https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
#### Wyrażenia lambda
Ogólna składnia wyrażenia lambda przedstawia się następująco:
````
(Type1 arg2, Type2 arg2, …) -> {
ciało wyrażenia
}
````
#### Przykład zastosowania strumieni
````java
List<String> fruits =
Arrays.asList("orange", "lemon", "peach", "banana", "plum",
"cherry", "apple", "pomelo");
fruits.stream()
.filter(s -> s.startsWith("p"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
````
**Repozytorium z ćwiczeniami zostanie usunięte 2 tygodnie po zakończeniu kursu. Spowoduje to też usunięcie wszystkich forków, które są zrobione z tego repozytorium.**
<file_sep>/a_Zadania/b_Dzien_2/b_Wyrazenia_lambda/README.md
<img alt="Logo" src="http://coderslab.pl/svg/logo-coderslab.svg" width="400">
# Java Zaawansowane - Wyrażenia lambda
#### Zadanie 1 - rozwiązywane z wykładowcą
1. Napisz program, który:
- pobierze od użytkownika n łańcuchów znaków
- umieści je w liście
- posortuje alfabetycznie
- wyświetli na ekranie.
Do sortowania kolekcji należy użyć wyrażenie lambda.
#### Zadanie 2 - rozwiązywane z wykładowcą
1. Korzystając z interfejsu funkcyjnego Predicate napisz wyrażenie lambda, które będzie sprawdzało czy podany parametr jest typu znakowego (String) i jeśli tak, to wypisze go na ekranie
#### Zadanie 3
1. Korzystając z interfejsu funkcyjnego Predicate napisz wyrażenie lambda, które będzie sprawdzało czy podany parametr jest typu liczbowego (Number) i jeśli tak, to wypisze go na ekranie.
#### Zadanie 4
1. Napisz interfejs funkcyjny, który pozwoli na obliczenie kwadratu i pierwiastka dowolnej liczby zmiennoprzecinkowej oraz silni liczby całkowitej.
2. Napisz wyrażenia lambda korzystające z tego interfejsu.
**Repozytorium z ćwiczeniami zostanie usunięte 2 tygodnie po zakończeniu kursu. Spowoduje to też usunięcie wszystkich forków, które są zrobione z tego repozytorium.**
<file_sep>/a_Zadania/a_Dzien_1/b_Interfejsy/Url.java
package a_Zadania.a_Dzien_1.b_Interfejsy;
public interface Url {
String getParam(String name, String url);
}
<file_sep>/a_Zadania/a_Dzien_1/c_Wzorce_projektowe/VirtualProduct.java
package a_Zadania.a_Dzien_1.c_Wzorce_projektowe;
public class VirtualProduct implements Product {
@Override
public String getName() {
return this.getClass().getName();
}
}
<file_sep>/a_Zadania/a_Dzien_1/a_Klasy_abstrakcyjne/ParentMen.java
package a_Zadania.a_Dzien_1.a_Klasy_abstrakcyjne;
public interface ParentMen {
void run();
default void jump(){
System.out.println("jump");
}
}
<file_sep>/a_Zadania/a_Dzien_1/a_Klasy_abstrakcyjne/README.md
<img alt="Logo" src="http://coderslab.pl/svg/logo-coderslab.svg" width="400">
# Klasy abstrakcyjne – zadania
Pamiętaj, aby rozwiązania do zadań umieszczać w odpowiednich plikach `java`, przygotowanych do zadań.
### Zadania rozwiązywane z wykładowcą:
#### Zadanie 1
1. Stwórz klasę abstrakcyjną o nazwie `Vehicle`. Klasa ma posiadać pola:
* maxSpeed (`Integer`)
* model (`String`)
2. Zdefiniuj metodę `toString`, zwracającą informacje w postaci:
`Class : <nazwa klasy>, model: <nazwa modelu>, speed: <maksymalna prędkość>`.
3. Utwórz klasę `Car`, która dziedziczy po klasie `Vehicle`.
4. Klasa ma zawierać dodatkowe pole typu `String` o nazwie `type`, reprezentującą typ (np. terenowy, SUV) oraz dodatkowe metody dostępowe (getter, setter).
Dodaj konstruktor umożliwiający ustawienie wszystkich atrybutów klasy.
5. Utwórz klasę `Train`, która dziedziczy po klasie `Vehicle`.
6. Klasa ma zawierać dodatkowe pole typu int o nazwie `trackWidth`, reprezentującą szerokość toru (np. 600 – kolej wąskotorowa, 1435 – standardowa szerokość) oraz dodatkowe metody dostępowe (getter, setter).
Dodaj konstruktor umożliwiający ustawienie wszystkich atrybutów klasy.
7. W klasie `main` utwórz tablicę dwóch elementów typu `Vehicle`.
8. Wstaw do tablicy elementy: pociąg oraz samochód, następnie w pętli wyświetl obiekty, wywołując metodę `toString`.
9. Przetestuj metody w metodzie `main` klasy **Main1**.
#### Zadanie 2 - rozwiązywane z wykładowcą
1. Dla dowolnej bazy danych wywołaj polecenie `sql`, znajdujące się w pliku **dump.sql**.
2. Zmodyfikuj dane połączenia z klasy **DbUtil** oraz dołącz do projektu sterownik bazy danych.
3. Uruchom metodę `main` z klasy **Main2**.
4. Przeanalizuj działanie poszczególnych klas oraz metod z przykładu.
-----------------------------------------------------------------------------
### Zadania rozwiązywane samodzielnie:
#### Zadanie 3
1. Utwórz klasę **Exercise** zawierającą pola:
* private Long id;
* private String title;
* private String description;
2. Utwórz klasę **ExerciseDao**, analogicznie do udostępnionej w przykładzie klasy **GroupDao**.
3. Zastanów się jakie modyfikacje można wprowadzić tak, by kod był bardziej uniwersalny.
#### Zadanie 4 - dodatkowe
1. Utwórz klasę **User** zawierającą dowolne pola użytkownika oraz połączenie z klasą **Group**.
2. Utwórz klasę **UserDao**, analogicznie do udostępnionej w przykładzie klasy **GroupDao**.
Zapoznaj się z definicją [*metody szablonowej*][template-method] repozytorium z zadaniami.
**Repozytorium z ćwiczeniami zostanie usunięte 2 tygodnie po zakończeniu kursu. Spowoduje to też usunięcie wszystkich forków, które są zrobione z tego repozytorium.**
<!-- Links -->
[template-method]: https://pl.wikipedia.org/wiki/Metoda_szablonowa_(wzorzec_projektowy)<file_sep>/a_Zadania/a_Dzien_1/c_Wzorce_projektowe/AdvanceProduct.java
package a_Zadania.a_Dzien_1.c_Wzorce_projektowe;
public class AdvanceProduct implements Product {
@Override
public String getName() {
return this.getClass().getName();
}
}
<file_sep>/a_Zadania/a_Dzien_1/a_Klasy_abstrakcyjne/dao/dump.sql
CREATE TABLE `user_group` (
`id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_polish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
ALTER TABLE `user_group`
ADD PRIMARY KEY (`id`);
ALTER TABLE `user_group`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;<file_sep>/a_Zadania/b_Dzien_2/c_Strumienie/Main11.java
package a_Zadania.b_Dzien_2.c_Strumienie;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main11 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a1aaa");
list.add("a2aaa");
list.add("cssss");
list.add("avvvvvvv");
list.stream().filter(s -> s.startsWith("a") || s.startsWith("s"))
.map(s->s.toUpperCase())
.sorted().forEach(s->System.out.println(s));
List<String> results = list.stream()
.filter(s->s.length()==5)
.distinct()
.collect(Collectors.toList());
String result3 = list.stream().sorted().map(s->s.substring(0,3))
.collect(Collectors.joining(","));
}
}
<file_sep>/a_Zadania/b_Dzien_2/a_Interfejsy_funkcyjne/NumberFilter.java
package a_Zadania.b_Dzien_2.a_Interfejsy_funkcyjne;
public class NumberFilter implements Filter<Integer> {
public boolean check(Integer v) {
return v < 20;
}
}
<file_sep>/a_Zadania/a_Dzien_1/a_Klasy_abstrakcyjne/dao/Some.java
package a_Zadania.a_Dzien_1.a_Klasy_abstrakcyjne.dao;
import a_Zadania.a_Dzien_1.a_Klasy_abstrakcyjne.ParentMen;
import a_Zadania.a_Dzien_1.a_Klasy_abstrakcyjne.ParentWomen;
public interface Some extends ParentMen, ParentWomen {
}
<file_sep>/a_Zadania/b_Dzien_2/a_Interfejsy_funkcyjne/Person.java
package a_Zadania.b_Dzien_2.a_Interfejsy_funkcyjne;
public class Person implements Comparable<Person> {
int age;
public Person(int age) {
this.age = age;
}
@Override
public int compareTo(Person o) {
if (age > o.age) {
return -1;
}
if (age < o.age) {
return 1;
}
return 0;
}
}
<file_sep>/a_Zadania/a_Dzien_1/c_Wzorce_projektowe/README.md
<img alt="Logo" src="http://coderslab.pl/svg/logo-coderslab.svg" width="400">
# Java Zaawansowane - Wzorce projektowe
Pamiętaj aby rozwiązania do zadań umieszczać w odpowiednich plikach `java`, przygotowanych do zadań.
#### Zadanie 1 - rozwiązywane z wykładowcą.
1. Utwórz implementację klasy `AppConfig`, której zadaniem będzie przechowywanie danych konfiguracyjnych.
2. Uzupełnij odpowiednie elementy klasy tak, by spełniała wymagania wzorca Singleton.
#### Zadanie 2 - rozwiązywane z wykładowcą.
1. Utwórz interfejs o nazwie `Product`, a następnie jego implementacje w postaci klas:
* SimpleProduct
* AdvanceProduct
* VirtualProduct
2. Utwórz implementację wzorca Fabryki.
-----------------------------------------------------------------------------
#### Zadanie 3
1. Utwórz implementację klasy `AtmApi` udostępniającą API dla bankomatów zgodnie z wzorcem Fasady.
2. Klasa ta ma umożliwiać wywołanie:
* metody `deposit` klasy `BankAccount`
* metody `payOut` klasy `BankAccout`
* metody `transferMoney` klasy `Transfer`
* metody `recharge` klasy `PhoneCard`
* metody `getLoan` klasy `Loan`
3. Utwórz wymagane klasy oraz ich metody
#### Zadanie 4
Dla zadanego interfejsu `Observer`:
```
public interface Observer {
void update(String title);
}
```
oraz `Subject`
```
public interface Subject {
void attach(Observer observer);
void detach(Observer observer);
void notifyObservers();
}
```
1. Utwórz klasę `Post` implementującą `Subject`, która będzie dodatkowo zawierać pola:
````
private String content;
private String title;
````
oraz metodę:
````
public void share() {
System.out.println("UPDATE OBSERVERS");
notifyObservers();
}
````
2. Utwórz implementacje interfejsu `Observer` w postaci klas:
* FacebookObserver - klasy imitującej umieszczenie postu na portalu Facebook
* SubscriberObserver - klasy imitującej powiadomienie subskrybentów o pojawieniu się nowego postu.
3. Uzupełnij implementacje zgodnie z wzorcem Obserwator.
4. Przykładowe wywołanie w metodzie testującej:
````
public static void main(String[] args) {
Post post = new Post();
post.setTitle("Some title");
post.setContent("Some content");
post.attach(new FacebookObserver());
post.attach(new TwitterObserver());
post.share();
}
````
**Repozytorium z ćwiczeniami zostanie usunięte 2 tygodnie po zakończeniu kursu.
Spowoduje to też usunięcie wszystkich forków, które są zrobione z tego repozytorium.**
<file_sep>/a_Zadania/a_Dzien_1/b_Interfejsy/UrlMain.java
package a_Zadania.a_Dzien_1.b_Interfejsy;
public class UrlMain {
public static void main(String[] args) {
Url standardUrl = new StandardUrl();
String url = "url_example?param1=99¶m2=string";
String param1 = standardUrl.getParam("param1", url);
System.out.println(param1);
Url extendedUrl = new ExtendedUrl();
String url2 = "url_example/param1.99/param2.string";
String param2 = extendedUrl.getParam("param1", url2);
System.out.println(param2);
}
}
<file_sep>/a_Zadania/b_Dzien_2/b_Wyrazenia_lambda/Main4.java
package a_Zadania.b_Dzien_2.b_Wyrazenia_lambda;
public class Main4 {
}
<file_sep>/a_Zadania/b_Dzien_2/c_Strumienie/Main4.java
package a_Zadania.b_Dzien_2.c_Strumienie;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
public class Main4 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("aaaaa");
list.add("bbbbb");
int sum = list.stream().mapToInt(s->s.length())
.sum();
System.out.println(sum);
Consumer<String> cons2 = e-> System.out.println(e);
Consumer<String> cons = System.out::println;
cons.accept("aa");
cons2.accept("bb");
List<Integer> integerList = new ArrayList<>();
for (int i = 0; i <20 ; i++) {
integerList.add(i);
}
integerList.stream().parallel()
.forEach(System.out::println);
}
}
<file_sep>/pl/coderslab/Snake.java
package pl.coderslab;
public class Snake extends Animal {
@Override
public void walk() {
System.out.println("~~~~~~~~~~~");
}
}
<file_sep>/a_Zadania/a_Dzien_1/a_Klasy_abstrakcyjne/ParentWomen.java
package a_Zadania.a_Dzien_1.a_Klasy_abstrakcyjne;
public interface ParentWomen {
void eat();
void run();
}
<file_sep>/a_Zadania/b_Dzien_2/a_Interfejsy_funkcyjne/Main2.java
package a_Zadania.b_Dzien_2.a_Interfejsy_funkcyjne;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import java.util.function.Supplier;
public class Main2 {
public static void main(String[] args) {
Supplier<Integer> sup = () -> 12;
Predicate<String> predicate = s -> s.length() > 300;
List<String> names = Arrays.asList("Wojtek", "Ania", "Magda", "Zosia");
List<Person> people = new ArrayList<>();
people.add(new Person(2));
people.add(new Person(12));
people.add(new Person(32));
Collections.sort(people);
}
}
<file_sep>/a_Zadania/a_Dzien_1/a_Klasy_abstrakcyjne/Train.java
package a_Zadania.a_Dzien_1.a_Klasy_abstrakcyjne;
public class Train extends Vehicle {
public int trackWidth;
}
<file_sep>/b_Zadania_Domowe/a_Dzien_1/README.md
<img alt="Logo" src="http://coderslab.pl/svg/logo-coderslab.svg" width="400">
#### Zadanie 1
1. W pliku `Main1` umieszczony został kod, który umieszcza w tablicy obiekty. Następnie wykonuje sortowanie tablicy.
2. Po uruchomieniu programu zauważysz że zwracany jest wyjątek, popraw kod dodając instrukcję `implements`
w następujący sposób:
````java
public class Person implements Comparable<Person>
````
3. Dodaj implementację wymaganej metody, ma ona porównywać osoby względem pierwszej litery nazwiska.
4. Możesz w tym celu wykorzystać metodę klasy `String` - `compareTo`;
5. Po wprowadzeniu zmian uruchom ponownie program i zweryfikuj czy działa poprawnie.
Zapoznaj się z interfejsem - [*Comparable*][comparable]
Pamiętaj że jeżeli operujesz na danych pobieranych z bazy danych możesz je odpowiednio sortować przy pomocy zapytania SQL.
Takiej możliwości może nie być w przypadku korzystania z API od zewnętrznego dostawcy.
#### Zadanie 2
1. W pliku `Main2` w metodzie `main` utwórz listę obiektów klasy `Person` następnie uzupełnij ją przynajmniej trzema obiektami tej klasy.
2. Wykonaj metodę `Collections.sort(lista obiektow)`.
3. Wyświetl elementy listy.
#### Zadanie 3
1. Stwórz klasę abstrakcyjną `Shape` zawierającą pola:
* area - double (pole)
* circuit - double (obwód)
* color - String
2. Dodaj metody abstrakcyjne:
* calculateArea - do obliczania powierzchni
* calculateCircuit - do obliczania obwodu
3. Utwórz klasy pochodne `Rectangle`, `Square`, `Circle`, uzupełnij je o pola wymagane do obliczenia pola/obwodu oraz dodaj konstruktory ustawiające wszystkie pola.
4. Dodaj implementację metod w klasach pochodnych.
5. W pliku `Main3` w metodzie main utwórz listę `List<Shape> list = new ArrayList<>();`, następnie dodaj do niej po jednym obiekcie każdego pochodnego typu.
6. Wyświetl dane w postaci:
````html
`Prostokąt o bokach 2 i 4 - pole = 8, obwód = 12`
`Kwadrat o boku 2 - pole = 4, obwód = 8`
`Koło o promieniu 3- pole = 28,27, obwód = 18,85`
````
**Zadania dodatkowe - są to przykładowe zadania z egzaminu OCJP - dawniej SCJP**
Spróbuj odpowiedzieć na zadane pytania - następnie uruchom kod i przeanalizuj swoją odpowiedź.
#### Zadanie 1
Given:
public interface Word {boolean isSpelled(String w); }
And three files:
1. abstract class Verb1 implements Word{boolean isSpelled(){}}
2. abstract class Verb2 implements Word{boolean isSpelled(){return true;}}
3. abstract class Verb3 implements Word{boolean isSpelled(String w){return true;}}
Which is true:
* A. Only the first file will compile
* B. Only the first and second files will compile.
* C. Only the first and third will compile.
* D. Only the second file will compile.
* E. All three files will compile.
#### Zadanie 2
What is the output for the below code ?
```java
interface A {
public void printValue();
}
```
```java
public class Test {
public static void main(String[] args) {
A a1 = new A() {
public void printValue() {
System.out.println("A");
}
};
a1.printValue();
}
}
```
Options are:
1. Compilation fails due to an error on line 3
1. A
1. Compilation fails due to an error on line 8
1. null
#### Zadanie 3
What is the output for the below code ?
```java
public interface InfA {
protected String getName();
}
public class Test implements InfA{
public String getName(){
return "test-name";
}
public static void main (String[] args){
Test t = new Test();
System.out.println(t.getName());
}
}
```
Options are:
1. test-name
1. Compilation fails due to an error on lines 2
1. Compilation fails due to an error on lines 1
1. Compilation succeed but Runtime Exception
<!-- Links -->
[comparable]: https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html
**Repozytorium z ćwiczeniami zostanie usunięte 2 tygodnie po zakończeniu kursu. Spowoduje to też usunięcie wszystkich forków, które są zrobione z tego repozytorium.**
<file_sep>/a_Zadania/b_Dzien_2/a_Interfejsy_funkcyjne/README.md
<img alt="Logo" src="http://coderslab.pl/svg/logo-coderslab.svg" width="400">
# Interfejsy funkcyjne – zadania
#### Zadanie 1 - rozwiązywane z wykładowcą
1. Utwórz interfejs funkcyjny:
````
@FunctionalInterface
public interface Filter<V> {
boolean check(V v);
}
````
2. Utwórz klasę `Main1` a w niej statyczną metodę:
````
static <T> void printList(List<T> src, Filter<T> f) {
for (T s : src) {
if (f.check(s)) {
System.out.println(s);
}
}
}
````
3. Utwórz klasę `NumberFilter` implementującą interfejs `Filter `
wraz z implementacją metody `check` w następujący sposób:
````
public boolean check(Integer v) {
return v < 20;
}
````
4. W metodzie main klasy `Main1` wywołaj metodę `printList` wykorzystując:
- obiekt klasy `NumberFilter`
- klasę anonimową
- wyrażenie lambda (szczegółowo wyrażenia zostaną omówione w następnym module,
istotne jest zobrazowanie uproszczenia kodu)
#### Zadanie 2
1. Utwórz interfejs funkcyjny:
````
@FunctionalInterface
public interface Transform<T, S> {
T transform(S s);
}
````
2. Utwórz klasę `Main2` a w niej statyczną metodę:
````
static <T, S> void printList(List<S> src, Filter<S> f, Transform<T, S> t) {
for (S s : src) {
if (f.check(s)) {
System.out.println(t.change(s));
}
}
}
````
3. Utwórz klasę `NumberTransform` implementującą interfejs `Transform` wraz z implementacją metody `transform`, zwróci wartość pomniejszoną o 1.
4. W metodzie main klasy `Main2` wywołaj metodę `printList` wykorzystując:
- obiekt klasy `NumberFilter`
- klasę anonimową
#### Zadanie 3
1. Korzystając z utworzonych interfejsów utwórz klasę `Main3` a w niej statyczną metodę o sygnaturze:
````
static <T, S> List<T> create(List<S> src, Filter<S> f, Transform<T, S> t)
````
2. Metoda ma zwracać elementy listy `src`, spełniające warunek określony w implementacji interfejsu `Filter` i przekształcone przez metodę implementującą interfejs `Transform`.
**Repozytorium z ćwiczeniami zostanie usunięte 2 tygodnie po zakończeniu kursu. Spowoduje to też usunięcie wszystkich forków, które są zrobione z tego repozytorium.**
<file_sep>/a_Zadania/a_Dzien_1/c_Wzorce_projektowe/ObserverMain.java
package a_Zadania.a_Dzien_1.c_Wzorce_projektowe;
public class ObserverMain {
public static void main(String[] args) {
Post post = new Post();
post.setTitle("Some title");
post.setContent("Some content");
post.attach(new FacebookObserver());
post.attach(new SubscriberObserver());
post.share();
}
}
<file_sep>/pl/coderslab/Animal.java
package pl.coderslab;
public abstract class Animal {
public void getSound(){
System.out.println("wrrrrrrrrrr");
}
public int noOfLegs;
public int getNoOfLegs() {
return noOfLegs;
}
public abstract void walk();
}
<file_sep>/a_Zadania/a_Dzien_1/b_Interfejsy/README.md
<img alt="Logo" src="http://coderslab.pl/svg/logo-coderslab.svg" width="400">
# Interfejsy – zadania
Pamiętaj, aby rozwiązania do zadań umieszczać w odpowiednich plikach `java`, przygotowanych do zadań.
### Zadania rozwiązywane z wykładowcą:
#### Zadanie 1
1. Stwórz interfejs o nazwie `Url` (służący do parsowania adresu URL) w celu uzyskania parametrów przekazanych metodą `GET`.
2. Interfejs powinien zawierać metodę `String getParam(String name, String url)`, gdzie `url` to adres do sparsowania.
Metoda ma zwrócić wartość parametru o nazwie `name`, wyciągniętą z `url`.
3. Następnie stwórz klasę `StandardUrl`, w której zaimplementujesz interfejs.
Jej zadaniem będzie sparsowanie standardowego adresu url, np.: `url_example?param1=99¶m2=string` w taki sposób, żeby za pomocą metody
`getParam("param1", "url_example?param1=99¶m2=string")` uzyskać `99`.
4. W momencie, gdy klasa będzie działała prawidłowo, utwórz klasę `UrlMain`, w której:
* stworzysz instancję obiektu `StandardUrl`, a następnie wyświetlisz wartość dowolnego parametru adresu URL (może być jak w przykładzie).
Możesz skorzystać z gotowego kodu:
````java
@Override
public String getParam(String name, String url) {
String param = "";
Pattern pattern = Pattern.compile(name + "=([^&]+)");
Matcher m = pattern.matcher(url);
if (m.find()) {
param = m.group(1);
}
return param;
}
````
#### Zadanie 2
1. Dopisz nową klasę `ExtendedUrl`. Klasa ta ma zaimplementować interfejs oraz prawidłowo sparsować
niestandardowy adres url, wg poniższego wzoru np.: `url_example/param1.99/param2.string`.
2. Dla przykładu: z powyższym adresem przekazanie do metody argumentu `param1` ma zwrócić `99`, a `param2` ma zwrócić `string`.
3. Przetestuj działanie wykorzystując wcześniej utworzoną klasą `UrlMain`.
Możesz wykorzystać poniższy kod:
````java
@Override
public String getParam(String name, String url) {
String param = "";
Pattern pattern = Pattern.compile(name + "\\.([^\\/]+)");
Matcher m = pattern.matcher(url);
if (m.find()) {
param = m.group(1);
}
return param;
}
````
-----------------------------------------------------------------------------
### Zadania rozwiązywane samodzielnie:
#### Zadanie 3
1. Stwórz interfejs o nazwie `Moveable`, zawierający dwie metody `void start()` oraz `void stop()`.
2. Utwórz trzy klasy: `Cat`, `Car` oraz `Person` – każda ma implementować interfejs `Moveable`.
3. Dla poszczególnych typów zaimplementowana metoda `start()` ma wyświetlać:
* Car – samochód jedzie
* Cat – kot skacze
* Person – człowiek idzie
3. Utwórz klasę `Main1`, a w niej metodę `main`.
4. Utwórz tablicę w następujący sposób:
````java
Moveable[] moveableTab = new Moveable[3];
````
W ten sposób traktujemy interfejs jako typ danych. W tablicy możemy przechowywać elementy, które implementują (określony typem) interfejs.
5. Umieść w tablicy jeden element każdego z utworzonych typów (`Cat`, `Car`, `Person`).
6. Wyświetl elementy tablicy wywołując metodę `start()`.
**Repozytorium z ćwiczeniami zostanie usunięte 2 tygodnie po zakończeniu kursu.
Spowoduje to też usunięcie wszystkich forków, które są zrobione z tego repozytorium.**
|
6a90a77db0b87a6418e12d434b3afe403bbc9250
|
[
"Markdown",
"Java",
"SQL"
] | 30
|
Java
|
arek-jozwiak-coderslab/katjees04m4
|
09aad5b200fdb66406dbda01e0bcd73ff8f5a2d4
|
7a2937fc095a695b55a4d45b2fac42ad1c1da9f0
|
refs/heads/master
|
<file_sep>#pragma strict
function Start () {
}
function OnGUI()
{
GUI.Label(Rect(0,0,100,50),"X: "+Input.mousePosition.x + " " + Input.mousePosition.y);
}
function Update () {
var leftmostonscreen:float;
var rightmostonscreen:float;
//get the x value of the leftmost on the screen
leftmostonscreen = Camera.main.ScreenToWorldPoint(Vector3(0,0,0)).x;
//get the x value of the rightmost on the screen
rightmostonscreen = Camera.main.ScreenToWorldPoint(Vector3(Screen.width,0,0)).x;
Debug.Log(leftmostonscreen + " " + rightmostonscreen);
if ( transform.position.x < leftmostonscreen )
{
transform.position.x = rightmostonscreen;
}
if ( transform.position.x > rightmostonscreen)
{
transform.position.x = leftmostonscreen;
}
transform.Translate(Vector3.right * 5 * Input.GetAxis("Horizontal") * Time.deltaTime);
//mouse control.
transform.position.x = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
}<file_sep>#pragma strict
//RED SPHERE
var redsphere:Rigidbody;
//GREEN SPHERE
var greensphere:Rigidbody;
//yellow sphere
var yellowsphere:Rigidbody;
//blue sphere
var bluesphere:Rigidbody;
function generatesphere () {
//create a random number from 1 to 5
var colornumber:int;
colornumber = Random.Range(1,5);
Debug.Log(colornumber);
//create a random number for the position
var xposition:float;
xposition = Random.Range(-2.5f,2.5f);
Debug.Log(xposition);
switch(colornumber)
{
case 1:
Instantiate(redsphere,Vector3(xposition,5,0),Quaternion.identity);
break;
case 2:
Instantiate(bluesphere,Vector3(xposition,5,0),Quaternion.identity);
break;
case 3:
Instantiate(greensphere,Vector3(xposition,5,0),Quaternion.identity);
break;
case 4:
Instantiate(yellowsphere,Vector3(xposition,5,0),Quaternion.identity);
break;
}
}
function Start () {
//run the generate sphere method. first parameter is the startup delay, and the
//second parameter is how often it will run.
InvokeRepeating("generatesphere",1.0,1.0);
}
function Update () {
}<file_sep>KingPong2HND2
=============
King Pong
A simple game to learn Unity
|
408cd445864d4d3f21f5d904d562455e41cefe56
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
TheGer/KingPong2HND2
|
0ddaeb6f7b5661c080db7f3211c7b6e66f143fec
|
38eae29bd8626eda5170d1b70eeb792a9b7311be
|
refs/heads/main
|
<repo_name>dsperax/PhishingGame-Fullstack<file_sep>/README.md
# Projeto Fullstack (MVP)
### Tecnologias utilizadas:
- HTML/CSS;
- JavaScript;
- C#;
- Ajax;
- MySQL (v2.0);
### Temática: CyberSegurança
### How to use:
- Crie as tabelas do banco (pasta DB-MySQL);
- Na pasta DATA, arquivo Bd_Conexao.cs, insira os dados da conexão na linha 13.
- Execute o projeto e fim =)
<file_sep>/Projeto Phishing - Finalizado/phishing/Models/ViewModels/Resposta.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace phishing.Models.ViewModels
{
public class Resposta
{
public int NumPergunta { get; set; }
public string RespostaPergunta { get; set; }
}
}
<file_sep>/Projeto Phishing - Finalizado/phishing/Models/Pergunta.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace phishing.Models
{
public class Pergunta
{
public int Id { get; set; }
public int Num_Pergunta { get; set; }
public string Titulo { get; set; }
public string Descricao { get; set; }
public string Resposta { get; set; }
public string ConteudoDiv { get; set; }
public string DescricaoResposta { get; set; }
}
}
<file_sep>/Projeto Phishing - Finalizado/phishing/Models/ViewModels/ResultadoViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace phishing.Models.ViewModels
{
public class ResultadoViewModel
{
public int Acertos { get; set; }
public Usuario Usuario { get; set; }
}
}
<file_sep>/Projeto Phishing - Finalizado/phishing/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using phishing.Models;
namespace phishing.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Autenticacao()
{
return View();
}
[HttpPost]
public IActionResult SalvaUsuario([FromBody] Usuario usuario)
{
TempData["nome"] = usuario.Nome;
TempData["email"] = usuario.Email;
TempData["pontuacao"] = 0;
return Json("Salvo com sucesso!");
}
}
}
<file_sep>/Projeto Phishing - Finalizado/DB-MySQL/CRIACAO-DO-BANCO.sql
CREATE TABLE `appphishingdb`.`phsg_pergunta` (
`COD_PERGUNTA` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'CHAVE PRIMARIA DA TABELA',
`DSCTITULOPERGUNTA` VARCHAR(255) NOT NULL COMMENT 'TITULO DA PERGUNTA',
`DSCPERGUNTA` VARCHAR(500) NOT NULL COMMENT 'DESCRIÇÃO DO ENUNCIADO DA PERGUNTA',
`NUMPERGUNTA` INT NOT NULL COMMENT 'NUMERO DA PERGUNTA NA SEQUENCIA DE APRESENTAÇÃO NA TELA',
`IDTRESPOSTA` VARCHAR(1) NOT NULL COMMENT 'RESPOSTA PHISHING(P) OU VERDADEIRO(V)\n',
`DSCRESPOSTA` VARCHAR(500) NOT NULL COMMENT 'DESCRIÇÃO DA EXPLICAÇÃO DA RESPOSTA',
`DSCCATEGORIA` VARCHAR(255) NOT NULL COMMENT 'CATEGORIZAÇÃO POR ÁREA DE ATUAÇÃO NA EMPRESA QUE A PERGUNTA É INTERESSANTE DE SER APLICADA',
`DSCHTMLIMG` VARCHAR(500) NOT NULL COMMENT 'DESCRIÇÃO DO CONTEUDO VISUAL DO HTML',
`DATCADASTRO` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'DATA EM QUE A PERGUNTA FOI CADASTRADA',
`IDTSTATUS` VARCHAR(1) NOT NULL COMMENT 'PERGUNTA ATIVA(A) OU INATIVA(I)?',
PRIMARY KEY (`COD_PERGUNTA`));
CREATE TABLE `appphishingdb`.`phsg_usuario` (
`CODUSUARIO` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'CHAVE PRIMARIA DA TABELA',
`NOMUSUARIO` VARCHAR(255) NOT NULL COMMENT 'NOME DO USUÁRIO',
`DSCEMAIL` VARCHAR(255) NOT NULL COMMENT 'EMAIL DO USUARIO',
`NUMPONTUACAO` INT NOT NULL COMMENT 'QUANTIDADE DE QUESTÕES QUE O USUÁRIO ACERTOU',
`DATRESPOSTA` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'DATA EM QUE O QUESTIONÁRIO FOI RESPONDIDO',
`IDTSTATUS` VARCHAR(1) NOT NULL COMMENT 'USUÁRIO JÁ RESPONDEU O QUESTIONÁRIO(V) OU (F)',
PRIMARY KEY (`CODUSUARIO`));
<file_sep>/Projeto Phishing - Finalizado/phishing/System/Web/SessionState.cs
namespace System.Web
{
public class SessionState
{
public class HttpSessionState
{
}
}
}<file_sep>/Projeto Phishing - Finalizado/phishing/Data/Bd_Conexao.cs
using MySqlConnector;
using phishing.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
namespace phishing.Data
{
public class Bd_Conexao
{
//private string caminho = @"server=NOME DO SERVIDOR.br;uid=USUARIO;pwd=<PASSWORD>;database=NOME DO SCHEMA/DB;";
private MySqlConnection conexao;
public MySqlConnection Conexao()
{
return this.conexao;
}
public Bd_Conexao()
{
try
{
conexao = new MySqlConnection(caminho);
conexao.Open();
}
catch (Exception)
{
throw new Exception("Falha na Conexão!");
}
finally
{
conexao.Close();
}
}
public void gravarPontuacao(string nome, string email, int pontuacao)
{
try
{
this.conexao.Open();
string query = "INSERT INTO phsg_usuario (NOMUSUARIO, DSCEMAIL, NUMPONTUACAO, IDTSTATUS) VALUES ('"+nome+"', '"+email+"', "+pontuacao+", '"+'V'+"')";
MySqlCommand cmd = new MySqlCommand(query, this.conexao);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw new Exception("Falha ao gravar pontuação!");
}
finally
{
this.conexao.Close();
}
}
public void updateStatusPergunta(int id, string status)
{
string query = "UPDATE phsg_pergunta SET (IDTSTATUS)" + 'I' + "WHERE ID" + id;
try
{
this.conexao.Open();
DataTable dados = new DataTable();
MySqlCommand cmd = new MySqlCommand(query, this.conexao);
dados.Load(cmd.ExecuteReader());
}
catch (Exception)
{
throw new Exception("Falha ao modificar o status da pergunta!");
}
finally
{
this.conexao.Close();
}
}
public void updateStatusUsuarioParaF(int id, string status)
{
string query = "UPDATE phsg_usuario SET (IDTSTATUS)" + 'F' + "WHERE ID" + id;
try
{
this.conexao.Open();
DataTable dados = new DataTable();
MySqlCommand cmd = new MySqlCommand(query, this.conexao);
dados.Load(cmd.ExecuteReader());
}
catch (Exception)
{
throw new Exception("Falha ao zerar status do usuario");
}
finally
{
this.conexao.Close();
}
}
public void deleteRegistro(int id)
{
string query = "DELETE FROM phsg_usuario WHERE id =" + id;
try
{
this.conexao.Open();
MySqlCommand cmd = new MySqlCommand(query, this.conexao);
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw new Exception("Falha ao deletar o registro!");
}
finally
{
this.conexao.Close();
}
}
public Pergunta getPerguntaByNumber(int numPergunta)
{
var query = "SELECT * FROM phsg_pergunta WHERE NUMPERGUNTA =" + numPergunta;
Pergunta pergunta = new Pergunta();
try
{
this.conexao.Open();
MySqlCommand cmd = new MySqlCommand(query, this.conexao);
cmd.ExecuteNonQuery();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
pergunta.Titulo = reader["DSCTITULOPERGUNTA"].ToString();
pergunta.Descricao = reader["DSCPERGUNTA"].ToString();
pergunta.Resposta = reader["IDTRESPOSTA"].ToString();
pergunta.DescricaoResposta = reader["DSCRESPOSTA"].ToString();
pergunta.ConteudoDiv = reader["DSCHTMLIMG"].ToString();
pergunta.Num_Pergunta = Convert.ToInt32(reader["NUMPERGUNTA"]);
}
}
catch (Exception)
{
throw new Exception("Falha ao recuperar a pergunta!");
}
finally
{
this.conexao.Close();
}
return pergunta;
}
}
}
<file_sep>/Projeto Phishing - Finalizado/phishing/Controllers/PerguntaController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using phishing.Data;
using phishing.Models;
using phishing.Models.ViewModels;
namespace phishing.Controllers
{
public class PerguntaController : Controller
{
public int acertos = 0;
public IActionResult Pergunta()
{
Pergunta pergunta = GetPerguntaByNumber(1);
if (TempData.Count == 0) return RedirectToAction("Index", "Home");
else return View(pergunta);
}
public Pergunta GetPerguntaByNumber(int numeroPergunta)
{
Bd_Conexao bd_Conexao = new Bd_Conexao();
return bd_Conexao.getPerguntaByNumber(numeroPergunta);
}
[HttpPost]
public IActionResult SalvaResposta([FromBody] Resposta resposta)
{
bool acertou = false;
Pergunta pergunta = GetPerguntaByNumber(resposta.NumPergunta);
if (resposta.RespostaPergunta == pergunta.Resposta)
{
acertou = true;
TempData["pontuacao"] = Convert.ToInt32(TempData["pontuacao"]) + 1;
}
return Json(new { acertou = acertou});
}
[HttpGet]
public IActionResult GetNextQuestion(int id)
{
Pergunta proxPergunta = GetPerguntaByNumber(id + 1);
return Json(new { titulo = proxPergunta.Titulo, descricao = proxPergunta.Descricao, numPerguntaAtual = id + 1, srcImagem = proxPergunta.ConteudoDiv });
}
[HttpPost]
public IActionResult RespostaPergunta([FromBody] Resposta resposta)
{
Pergunta pergunta = GetPerguntaByNumber(resposta.NumPergunta);
return Json(new { descricaoResposta = pergunta.DescricaoResposta });
}
}
}<file_sep>/Projeto Phishing - Finalizado/phishing/Controllers/ResultadoController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using phishing.Data;
using Microsoft.AspNetCore.Mvc;
using phishing.Models.ViewModels;
namespace phishing.Controllers
{
public class ResultadoController : Controller
{
public IActionResult Resultado()
{
ResultadoViewModel resultado = new ResultadoViewModel()
{
Acertos = Convert.ToInt32(TempData["pontuacao"]),
Usuario = new Models.Usuario() { Nome = TempData["nome"].ToString(), Email = TempData["email"].ToString() }
};
Bd_Conexao bd_Conexao = new Bd_Conexao();
bd_Conexao.gravarPontuacao(resultado.Usuario.Nome, resultado.Usuario.Email, resultado.Acertos);
return View(resultado);
}
}
}
|
9ae77035b43a45fe0622a16ec15e7066f3ea479a
|
[
"Markdown",
"C#",
"SQL"
] | 10
|
Markdown
|
dsperax/PhishingGame-Fullstack
|
a10934831a68fa23850539078d2a9988b21b8b4b
|
82028ac9dd23b1bdf5d19bdc722e88e344da1221
|
refs/heads/main
|
<repo_name>liam-fletcher1/ICS3U-Unit3-04-CPP-Integer_Game<file_sep>/README.md
# ICS3U-Unit3-04-CPP-Integer_Game
[](https://github.com/liam-fletcher1/ICS3U-Unit3-04-CPP-Integer_Game/actions)
<file_sep>/integer_game.cpp
// Copyright (c) 2021 <NAME> All rights reserved
//
// Created by: <NAME>
// Created on: Sep 2021
// This program asks the user to input a integer and
// the program with tell them if its positive, negative or zero
#include <iostream>
int main() {
// this function checks if the user picked the correct number
int integer_input;
// input
std::cout << "Enter an integer: ";
std::cin >> integer_input;
std::cout << "" << std::endl;
// process
if (integer_input > 0) {
std::cout << "This is a positive number!";
} else if (integer_input < 0) {
std::cout << "This is a negative number!";
} else if (integer_input == 0) {
std::cout << "This number is just zero!";
} else {
std::cout << "No idea!";
}
std::cout << std::endl;
std::cout << "\nDone.";
}
|
72c449a418cc688e297fb859ce856a1640d47405
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
liam-fletcher1/ICS3U-Unit3-04-CPP-Integer_Game
|
46a692bb7301aaa6682239aa73f91405185f944b
|
a443ee75faa15c1bef495e38f0244562b85f2c00
|
refs/heads/master
|
<file_sep>#include "Collision.h"
#include <sstream>
/* AABB Collision */
Vector3 Collision::startingPos;
Vector3 Collision::currentStart; //current collide bound
Vector3 Collision::currentEnd;
Vector3 Collision::previousStart; //current collide bound @ previous frame
Vector3 Collision::previousEnd;
Vector3 Collision::checkStart, Collision::checkEnd; //start and end for box
Vector3 Collision::normal;
vector<Collision*> Collision::slideList;
vector<Collision*>::iterator Collision::it;
Vector3 Collision::currentPos; //current position
float Collision::offset = 0.001f; //cannot be 0 (or will considered collision even if touching)
Vector3 Collision::startZone, Collision::endZone;
Vector3 Collision::slideDist;
Collision* Collision::collided_Box = NULL;
float Collision::remainingTime;
bool Collision::xc, Collision::yc, Collision::zc;
Vector3 originalVel;
int counter;
Vector3 originalPos;
Collision::Collision()
{
vel.SetZero();
normal.SetZero();
}
/* Init */
void Collision::Set(Vector3 pos, Vector3 scale, TYPE type)
{
position = pos;
this->scale = scale;
this->type = type;
}
void Collision::SetForTile(int xPos, int yPos, float tileScale)
{
this->position.Set( static_cast<float>(xPos) * tileScale, static_cast<float>(yPos) * tileScale, position.z);
this->scale.Set(tileScale, tileScale, tileScale);
}
/* Update */
void Collision::Start(const Vector3& objectPos, const Vector3& velocity)
{
if(type == BOX)
{
counter = 0;
normal.SetZero();
slideList.clear();
collided_Box = NULL;
remainingTime = 1.f;
/* set velocity */
vel = velocity;
originalVel = vel; //store original velocity
slideDist.SetZero();
/* set pos */
startingPos = objectPos;
position = startingPos + vel;
originalPos = position;
/* Not moving */
if(velocity.IsZero())
{
return;
}
}
}
Collision* a;
Collision* b;
bool Collision::CheckCollision(Collision& current, Collision& check)
{
/************ Standardise ************/
//BOX/SLANTED_BOX must always be current, unless current and check are both SPHERE
a = ¤t;
b = ✓
/************ Reject ************/
if(a->type == SLANTED_BOX && b->type == SLANTED_BOX)
return false;
else if( (a->type == BOX && b->type == SLANTED_BOX) ||
(a->type == SLANTED_BOX && b->type == BOX) )
return false;
/************ Swap ************/
//current type: sphere --- check tye: box ===> Swap
//current type: sphere --- check tye: slanted_box ===> Swap
if(a->type == BOX || a->type == SLANTED_BOX)
{
if(b->type == SPHERE)
{
a = ✓
b = ¤t;
}
}
/************ Check collide ************/
//possible combinations:
//1) current type: Sphere --- Check type: Sphere
//3) current type: Sphere --- Check type: Slanted Box
//4) current type: Sphere --- Check type: Box
//2) current type: Box --- Check type: Box
//see current type is what type of collide bound
//1)
if(a->type == SPHERE && b->type == SPHERE)
{
return SphereToSphere(a, b);
}
else if(a->type == SPHERE && b->type == SLANTED_BOX)
{
return SphereToSlantedBox(a, b);
}
else if(a->type == SPHERE && b->type == BOX)
{
return SphereToBox(a, b);
}
else if(a->type == BOX && b->type == BOX)
{
return SlideResponse(a, b);
}
return false;
}
Collision::~Collision()
{
}
/* Sphere (current) to Sphere (check) */
bool Collision::SphereToSphere(Collision* current, Collision* check)
{
return false;
}
/* Sphere (current) to Slanted Box (check) */
bool Collision::SphereToSlantedBox(Collision* current, Collision* check)
{
return false;
}
/* Sphere (current) to Box (check) */
bool Collision::SphereToBox(Collision* current, Collision* check)
{
return false;
}
float Collision::SweptAABB(Collision& current, Collision& check)
{
/** Get start and end point **/
currentStart = current.startingPos - current.scale * 0.5f;
currentEnd = current.startingPos + current.scale * 0.5f;
checkStart = check.position - check.scale * 0.5f;
checkEnd = check.position + check.scale * 0.5f;
bool checkX = false, checkY = false, checkZ = false;
/* Check eligibility: not 0 vel */
if(originalVel.x)
checkX = true;
if(originalVel.y)
checkY = true;
if(originalVel.z)
checkZ = true;
/** Get entry and exit length **/
float xInvEntry = 0.f, xInvExit = 0.f;
float yInvEntry = 0.f, yInvExit = 0.f;
float zInvEntry = 0.f, zInvExit = 0.f;
float xEntry, xExit, yEntry, yExit, zEntry, zExit;
xEntry = yEntry = zEntry = -std::numeric_limits<float>::max(); //max: assume not collide
xExit = yExit = zExit = std::numeric_limits<float>::max(); //min: assume not collide
//x
if( checkX )
{
if(originalVel.x > 0)
{
xInvEntry = checkStart.x - currentEnd.x;
xInvExit = checkEnd.x - currentStart.x;
}
else
{
xInvEntry = checkEnd.x - currentStart.x;
xInvExit = checkStart.x - currentEnd.x;
}
//entry/exit time
xEntry = xInvEntry * (1.f / originalVel.x);
xExit = xInvExit * (1.f / originalVel.x);
}
//y
if( checkY )
{
if( originalVel.y > 0)
{
yInvEntry = checkStart.y - currentEnd.y;
yInvExit = checkEnd.y - currentStart.y;
}
else
{
yInvEntry = checkEnd.y - currentStart.y;
yInvExit = checkStart.y - currentEnd.y;
}
//entry/exit time
yEntry = yInvEntry * (1.f / originalVel.y);
yExit = yInvExit * (1.f / originalVel.y);
}
//z
if( checkZ )
{
if( originalVel.z > 0)
{
zInvEntry = checkStart.z - currentEnd.z;
zInvExit = checkEnd.z - currentStart.z;
}
else
{
zInvEntry = checkEnd.z - currentStart.z;
zInvExit = checkStart.z - currentEnd.z;
}
//entry/exit time
zEntry = zInvEntry * (1.f / originalVel.z);
zExit = zInvExit * (1.f / originalVel.z);
}
//max
float entryTime = (xEntry > yEntry) ? xEntry : yEntry; //compare x, y first
entryTime = (zEntry > entryTime) ? zEntry : entryTime; //compare current result with z
//min
float exitTime = (xExit < yExit) ? xExit : yExit; //compare x, y first
exitTime = (zExit < exitTime) ? zExit : exitTime; //compare current result with z
/** Check if collision occurs **/
if(exitTime < entryTime)
return 1.0;
/** set normal **/
current.normal.SetZero();
if( xEntry > yEntry && xEntry > zEntry )
{
current.normal.x = 1.f;
}
//collided Y side
else if( yEntry > xEntry && yEntry > zEntry )
{
current.normal.y = 1.f;
}
//collided Z side
else if( zEntry > xEntry && zEntry > yEntry )
{
current.normal.z = 1.f;
}
return entryTime;
}
bool Collision::SlideResponse(Collision* current, Collision* check)
{
/***** If inside original broad phrase zone, is potential slide collision *****/
if( originalVel.IsZero() )
return false;
/* push back possible obstacles */
if( broadPhrase(current->startingPos, originalPos, check->position, current->scale, check->scale) )
{
slideList.push_back(check);
/************************************ Check if box needs collision check (BroadPhrase test) ************************************/
if( !broadPhrase(current->startingPos, current->position, check->position, current->scale, check->scale) )
{
return false;
}
/************************************ Get velocity ************************************/
float CollisionTime = SweptAABB(*current, *check);
/* No collision at all */
if(CollisionTime >= 1.f)
{
return false;
}
/* collided set to true */
/* Theres collision */
/* Velocity multiply with collisionTime */
current->vel = originalVel; //set it to original velocity
current->vel *= CollisionTime;
current->position = current->startingPos;
current->position += current->vel;
collided_Box = check;
return true;
}
return false;
}
bool Collision::broadPhrase(Vector3 originalPos, Vector3 finalPos, Vector3 checkPos, Vector3 currentScale, Vector3 checkScale)
{
/************************************ Check if box needs collision check ************************************/
/* Check if checkBox collides with start-end zone */
/* length and height of zone */
float length = finalPos.x - originalPos.x; //x
float height = finalPos.y - originalPos.y; //y
float width = finalPos.z - originalPos.z; //z
//x
if(length > 0)
{
startZone.x = originalPos.x - currentScale.x * 0.5f;
endZone.x = finalPos.x + currentScale.x * 0.5f;
}
else
{
startZone.x = finalPos.x - currentScale.x * 0.5f;
endZone.x = originalPos.x + currentScale.x * 0.5f;
}
//y
if(height > 0)
{
startZone.y = originalPos.y - currentScale.y * 0.5f;
endZone.y = finalPos.y + currentScale.y * 0.5f;
}
else
{
startZone.y = finalPos.y - currentScale.y * 0.5f;
endZone.y = originalPos.y + currentScale.y * 0.5f;
}
//z
if(width > 0)
{
startZone.z = originalPos.z - currentScale.z * 0.5f;
endZone.z = finalPos.z + currentScale.z * 0.5f;
}
else
{
startZone.z = finalPos.z - currentScale.z * 0.5f;
endZone.z = originalPos.z + currentScale.z * 0.5f;
}
checkStart = checkPos - checkScale * 0.5f;
checkEnd = checkPos + checkScale * 0.5f;
/** Check if in X-Y of broad phrase **/
if(!checkAABBCollide(startZone, endZone, checkStart, checkEnd)) //if checkBox not in start-end zone
{
return false;
}
return true;
}
void Collision::Reset()
{
/** Offset **/
if(originalVel.x != 0.f)
(originalVel.x > 0.f) ? position.x -= offset : position.x += offset;
if(originalVel.y != 0.f)
(originalVel.y > 0.f) ? position.y -= offset : position.y += offset;
if(originalVel.z != 0.f)
(originalVel.z > 0.f) ? position.z -= offset : position.z += offset;
/* Check for 2 other axis after the first one is collided */
if( !normal.IsZero() && collided_Box != NULL )
{
CheckAndResponse(!normal.x, !normal.y, !normal.z, *this, slideList); //axis #2
/** Offset **/
if(originalVel.x != 0.f)
(originalVel.x > 0.f) ? position.x -= offset : position.x += offset;
if(originalVel.y != 0.f)
(originalVel.y > 0.f) ? position.y -= offset : position.y += offset;
if(originalVel.z != 0.f)
(originalVel.z > 0.f) ? position.z -= offset : position.z += offset;
CheckAndResponse(!normal.x, !normal.y, !normal.z, *this, slideList); //axis #3
}
/** Offset **/
if(originalVel.x != 0.f)
(originalVel.x > 0.f) ? position.x -= offset : position.x += offset;
if(originalVel.y != 0.f)
(originalVel.y > 0.f) ? position.y -= offset : position.y += offset;
if(originalVel.z != 0.f)
(originalVel.z > 0.f) ? position.z -= offset : position.z += offset;
}
bool Collision::CheckAndResponse(bool x, bool y, bool z, Collision& current, vector<Collision*>& checkList)
{
/* remaining vel to travel */
originalVel -= current.vel; //remaining vel
/* See which side collide */
if( !x )
originalVel.x = 0.f;
if( !y )
originalVel.y = 0.f;
if( !z )
originalVel.z = 0.f;
/** Box that is being collided previous axis **/
Collision* ptr = NULL;
/* set starting pos */
startingPos = current.position; //set startPos to currentPos so sweptAABB can function
current.vel = originalVel;
current.position += originalVel;
for(it = checkList.begin(); it != checkList.end(); ++it)
{
ptr = *it;
/* BroadPhrase test */
if( collided_Box == ptr || !broadPhrase(startingPos, current.position, ptr->position, current.scale, ptr->scale) )
{
continue;
}
/************************************ Get velocity ************************************/
float CollisionTime = SweptAABB(current, *ptr);
/* No collision at all */
if(CollisionTime >= 1.f)
{
continue;
}
/* Velocity multiply with collisionTime */
current.vel = originalVel; //set it to remaining velocity
current.vel *= CollisionTime;
/* Set position to new vel */
current.position = startingPos;
current.position += current.vel;
}
return false;
}
bool Collision::checkSlide(Vector3& normall){return true;}
bool Collision::inZone(float start, float end, float checkStart, float checkEnd)
{
//check x and y only
return (end > checkStart && start < checkEnd);
}
bool Collision::checkAABBCollide(Vector3& currentStart, Vector3& currentEnd, Vector3& checkStart, Vector3& checkEnd)
{
return (currentEnd.x > checkStart.x && currentStart.x < checkEnd.x) &&
(currentEnd.y > checkStart.y && currentStart.y < checkEnd.y) &&
(currentEnd.z > checkStart.z && currentStart.z < checkEnd.z);
}
bool Collision::QuickAABBDetection2D(Vector3& currentStart, Vector3& currentEnd, Vector3& checkStart, Vector3& checkEnd)
{
return (currentEnd.x > checkStart.x && currentStart.x < checkEnd.x) &&
(currentEnd.y > checkStart.y && currentStart.y < checkEnd.y);
}
bool Collision::checkSideCollide(Vector3& currentStart, Vector3& currentEnd, Vector3& checkStart, Vector3& checkEnd, bool x, bool y, bool z)
{
return false;
}
void Collision::setStartEnd2D(const Vector3& pos, const Vector3& scale, Vector3& start, Vector3& end)
{
start.Set(pos.x - scale.x * 0.5f, pos.y - scale.y * 0.5f, 0);
end.Set(pos.x + scale.x * 0.5f, pos.y + scale.y * 0.5f, 0);
}
void Collision::ResetAABB()
{
//startingPos = position;
}
<file_sep>#ifndef READFROM_H
#define READFROM_H
/* stream classes */
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
/* utilities */
#include "utilities.h"
#include <string>
#include <vector>
using namespace std;
/* stream classes */
/*
ofstream: stream class to write to files (OUTPUT)
ifstream: stream class to read from files (INPUT)
fstream: stream class to both read and write to files
cin is an object of class istream and cout is an object of class ostream, we can use file stream the same way
we are using them for cin and cout, only difference is to associate these streams with physical files
*/
/** TIPS **/
//use const char* if this function is called alot of times/multiple times
//C-Style string to match and print the line containing it, caller can use pointer/hardcode the text
//prints out content of text file
bool readFromFile(string& name);
//prints out selected line in text file
const char* readFromFile(string& name, int line);
//prints out matched text
bool readFromFile(string& name, string& text);
#endif<file_sep>#include "Controller.h"
//Include the standard C++ headers
#include <stdio.h>
#include <stdlib.h>
const unsigned char Controller::FPS = 60; // FPS of this game (ONLY RELEASE MODE CAN RUN SMOOTHLY AT 170FPS MAX)
const unsigned int Controller::frameTime = 1000 / FPS; // time for each frame
double Controller::scrollxPos = 0.f;
double Controller::scrollyPos = 0.f;
bool Controller::myKeys[TOTAL_CONTROLS] = {false};
char Controller::inputChar[OPEN] = {0};
vector<char> Controller::typableCharacters;
/********************** mouse **********************/
Vector2 Controller::cursorPos;
int Controller::mouseRightButton;
int Controller::mouseLeftButton;
/********************* constructor / destructor *********************/
Controller::Controller() : currentModel(NULL), currentView(NULL)
{
}
Controller::~Controller()
{
currentModel = NULL;
currentView = NULL;
}
/******************** core functions **********************/
void Controller::Init()
{
/** Timers: set both timers to 0 **/
m_dElapsedTime = 0.0;
m_dAccumulatedTime_thread1 = 0.0;
m_dAccumulatedTime_thread2 = 0.0;
//mouse button
mouseLeftButton = glfwGetMouseButton(glfwGetCurrentContext(), GLFW_MOUSE_BUTTON_LEFT);
mouseRightButton = glfwGetMouseButton(glfwGetCurrentContext(), GLFW_MOUSE_BUTTON_RIGHT);
//hide the cursor
glfwSetInputMode(currentView->getWindow(), GLFW_CURSOR, GLFW_CURSOR_NORMAL);
//controls
InitControls();
/*** Create views and models ***/
/********************** Models **********************/
Gameplay = new Model_Gameplay;
Level_Editor = new Model_Level_Editor;
mainMenu = new Model_MainMenu;
/********************** Views **********************/
view_MainMenu = new View_Main_Menu(mainMenu, 975, 650, View::TWO_D);
view_LevelEditor = new View_Level_Editor(Level_Editor, 975, 650, View::TWO_D);
view_3D_Game = new View_3D_Game(Gameplay, 975, 650, View::TWO_D);
/********************** Initialize **********************/
//init view
currentView = view_3D_Game;
InitCurrentView();
//set model
currentModel = Gameplay;
InitCurrentModel();
}
void Controller::InitControls()
{
//keys
for(int i = 0; i <= OPEN; ++i) //all 256 chars
myKeys[i] = false;
inputChar[FORWARD] = 'W';
inputChar[LEFT] = 'A';
inputChar[BACKWARD] = 'S';
inputChar[RIGHT] = 'D';
inputChar[CROUCH] = 'C';
inputChar[PAUSE] = 'P';
inputChar[OPEN] = 'O';
inputChar[JUMP] = ' ';
inputChar[RELOAD] = 'R';
inputChar[FLY_UP] = 'K';
inputChar[FLY_DOWN] = 'L';
/* Typable characters */
for(char a = 'A'; a <= 'Z'; ++a)
{
typableCharacters.push_back(a);
}
typableCharacters.push_back(' ');
}
void Controller::InitCurrentModel()
{
/* Init model and other related stuff */
currentModel->Init();
}
void Controller::InitCurrentView()
{
/* Init view and other related stuff */
currentView->Init();
}
void Controller::Run()
{
//Main Loop
m_timer.startTimer(); // Start timer to calculate how long it takes to render this frame
while (!glfwWindowShouldClose(currentView->getWindow()) && !IsKeyPressed(VK_ESCAPE))
{
//get the elapsed time
m_dElapsedTime = m_timer.getElapsedTime();
m_dAccumulatedTime_thread1 += m_dElapsedTime;
m_dAccumulatedTime_thread2 += m_dElapsedTime;
/* fps */
fps = (float)(1.f / m_dElapsedTime);
/* twin threaded approach */
if(m_dAccumulatedTime_thread1 > 0.01) //update: update fps is _dAccumulatedTime_thread1 > fps
{
/* Init new model etc... */
SwitchModels();
/* controls */
UpdateMouse();
UpdateKeys();
/** model update **/
currentModel->Update(m_dElapsedTime, myKeys);
m_dAccumulatedTime_thread1 = 0.0;
}
if(m_dAccumulatedTime_thread2 > 0.003) //render: render fps is _dAccumulatedTime_thread1 > fps
{
/** View update(rendering) **/
currentView->Render(fps); //or switch to pause screen
m_dAccumulatedTime_thread2 = 0.0;
}
//Swap buffers
glfwSwapBuffers(currentView->getWindow());
//Get and organize events, like keyboard and mouse input, window resizing, etc...
glfwPollEvents();
m_timer.waitUntil(frameTime); // Frame rate limiter. Limits each frame to a specified time in ms.
} //Check if the ESC key had been pressed or if the window had been closed
}
void Controller::Exit()
{
currentView->Exit();
currentModel->Exit();
}
void Controller::SwitchModels()
{
/** Switch models based on states **/
if( !Model::getSwitchState() ) //if switch model flag is false, no need to switch
return;
switch( Model::getCurrentState() )
{
case Model::IN_GAME:
currentModel = Gameplay;
currentModel->Init();
currentView = view_3D_Game;
//currentView->SetModel(currentModel); //need set model since edit and game use same view update 2: no need already
break;
case Model::EDIT_LEVEL:
currentModel = Level_Editor;
currentModel->Init();
currentView = view_LevelEditor;
break;
case Model::MAIN_MENU:
currentModel = mainMenu;
currentModel->Init();
currentView = view_MainMenu;
break;
}
/* Set switch state flag to false */
Model::SetSwitchState(false);
}
void scroll(GLFWwindow* window,double x,double y)
{
Controller::setScrollX(x);
Controller::setScrollY(y);
}
void Controller::setScrollX(double p)
{
scrollxPos = p;
}
void Controller::setScrollY(double p)
{
scrollyPos = p;
}
void Controller::UpdateKeys()
{
/** Set all keys to false **/
for(unsigned i = 0; i < TOTAL_CONTROLS; ++i)
myKeys[i] = false;
/**** See which keys are pressed ****/
/** Keyboard **/
for(int i = 0; i <= OPEN; ++i)
{
if(IsKeyPressed(inputChar[i]))
myKeys[i] = true;
}
/** non-keyboard(mouse) **/
mouseLeftButton = glfwGetMouseButton(glfwGetCurrentContext(), GLFW_MOUSE_BUTTON_LEFT);
mouseRightButton = glfwGetMouseButton(glfwGetCurrentContext(), GLFW_MOUSE_BUTTON_RIGHT);
if(mouseLeftButton == GLFW_PRESS)
myKeys[SHOOT] = true;
if(mouseRightButton == GLFW_PRESS)
myKeys[AIM] = true;
/** Arrow key **/
if( IsKeyPressed(VK_UP) )
myKeys[ARROW_UP] = true;
if( IsKeyPressed(VK_DOWN) )
myKeys[ARROW_DOWN] = true;
if( IsKeyPressed(VK_LEFT) )
myKeys[ARROW_LEFT] = true;
if( IsKeyPressed(VK_RIGHT) )
myKeys[ARROW_RIGHT] = true;
/** Scrolling **/
GLFWwindow* glfwGetCurrentContext(void);
glfwSetScrollCallback(glfwGetCurrentContext(), scroll);
if(scrollyPos > 0.0)
{
myKeys[SCROLL_UP] = true;
}
else if(scrollyPos < 0.0)
{
myKeys[SCROLL_DOWN] = true;
}
if(scrollyPos != 0.0)
{
scrollyPos = 0.0;
}
}
void Controller::UpdateKeyPressed()
{
/* If a key is pressed, do stuff */
}
void Controller::UpdateMouse()
{
cursorPos = GetCursor(View::getWindow());
}
Vector2 Controller::GetCursorPos()
{
return cursorPos;
}
Vector2 Controller::GetCursor(GLFWwindow* const window)
{
double x;
double y;
glfwGetCursorPos(window, &x, &y);
return Vector2(x, y);
}
/********************** controller functions **********************/
bool Controller::IsKeyPressed(unsigned short key)
{
return ((GetAsyncKeyState(key) & 0x8001) != 0);
}
char Controller::characterPressed()
{
for(int i = 0; i < typableCharacters.size(); ++i)
{
if( IsKeyPressed(typableCharacters[i]) )
{
return typableCharacters[i];
}
}
return '/'; //return backslash for nothing pressed
}
bool* Controller::getKeyPressed()
{
return myKeys;
}
/********************** getter setter **********************/
float Controller::getFPS(){return fps;}
<file_sep>#include "Tile.h"
Collision Tile::collisionBox;
/*************************** Tile Class ***************************/
/* Constructor/destructor */
Tile::Tile()
{
}
Tile::~Tile()
{
}
/* Core */
void Tile::Init(int xPos, int yPos)
{
this->xPos = xPos;
this->yPos = yPos;
}
bool Tile::CheckCollision(Collision& checkbox, float tileScale)
{
/* Set shared collision box to current tile pos */
collisionBox.SetForTile(xPos, yPos, tileScale);
/* Check collision with this tile */
return Collision::CheckCollision(checkbox, collisionBox);
}
/* Utilities*/
bool Tile::operator== (Tile& rhs)
{
return this->xPos == rhs.xPos && this->yPos == rhs.yPos;
}<file_sep>#ifndef TILE_OBJECT_H
#define TILE_OBJECT_H
#include "GameObject.h"
class TileObject : public GameObject
{
public:
enum TILE_TYPE
{
NONE,
NONCOLLIDABLE,
COLLIDABLE,
};
/* constructor/destructor */
TileObject();
~TileObject();
/* Core */
void Set(Mesh* tileMap, Vector3 Pos, float tileScale, TILE_TYPE tile_type);
/* getter/setter */
int getTileNum();
void setTileNum(int t);
TILE_TYPE getTileType();
/* collision check */
virtual bool CollisionCheck(GameObject* checkWithMe); //collision check
private:
TILE_TYPE tile_type;
int tileNum; //tile number
};
#endif<file_sep>#include "readFrom.h"
/**/
/*
Heads up: to change <bool readFromFile(string& name, string& text)> from
match whole string to match semi to whole part of string, instruction inside function
*/
/**/
bool readFromFile(char* name)
{
/**
to open file:
use open function; open(filename, mode);
eg. myfile.open("dfsdf.txt", ios::in | ios::trunc)
modes:
second parameter of open function/overloaded constructor
ios::in - open for input operations (READ from file)
ios::out - open for output operations (WRITE to file)
ios::binary - open in binary mode
ios::ate - set initial position at end of file
ios::app - All output operations are performed at the end of the file, appending the content to the current content of the file.
ios::trunc - if file opened for output and already exists, previous content deleted and replaced by new one
combine modes:
use bitwise OR (|); ios::in | ios::out | ios::trunc
**/
ifstream myfile(name); //overloaded constructor to open a text file imm. after declaration
string sentence = "";
if( myfile.is_open())
{
int counter = 1;
//no need to convert C-Style string to string if input uses C string
//string can be assigned C-Style string, in this case, its just characters
//on the text file, so C-Style string or string can take in stuff from it
while(getline(myfile, sentence, '\n')) //can also use !myfile.eof()
{
cout << counter << ": " << sentence << endl;
++counter;
}
myfile.close();
}
else
{
cout << "wtf whr the file" << endl;
return false;
}
return true;
}
const char* readFromFile(char* name, int line)
{
ifstream myfile(name); //overloaded constructor to open a text file imm. after declaration
/** static so that sentence will always be in mem. and char pointer
to it will not be invalid **/
static string sentence = "";
const char* ptr = NULL;
if( myfile.is_open())
{
for(int i = 0; !myfile.eof() && i < line; ++i, getline(myfile, sentence)){}
ptr = sentence.c_str();
myfile.close();
if(ptr == NULL)
sentence = "Error 999: line not found u blind";
return sentence.c_str();
}
else
{
sentence = "wtf whr the file";
return sentence.c_str();
}
myfile.close();
sentence = ""; //safeguard in case all tests fails...
return sentence.c_str();
}
bool readFromFile(string& name, string& text)
{
int line = 0;
ifstream myfile(name);
string sentence = "";
if(myfile.is_open())
{
bool c = false;
while(getline(myfile, sentence))
{
++line;
//change to searchTerm(sentence, text) for matching both semi/whole of string
if(sentence == text)
{
//cout << "Matched sentence: " << sentence << " --- Line: " << line << endl;
c = true;
}
}
myfile.close();
if(c == false)
{
//cout << "error 998: cannot match word/no words to be searched" << endl;
return false;
}
else
return true;
}
else
{
//cout << "wtf whr the file" << endl;
return false;
}
}<file_sep>#include "View_3D_Game.h"
View_3D_Game::View_3D_Game(){}
View_3D_Game::View_3D_Game(Model_Gameplay* model, unsigned short console_width, unsigned short console_height, MODE mode) :
View(model, console_width, console_height, mode)
{
this->model = model;
}
View_3D_Game::~View_3D_Game()
{
}
/********************** Core functions *****************************/
void View_3D_Game::Init()
{
/* Set up basic stuff */
View::StartInit();
}
void View_3D_Game::Render(const float fps)
{
/* Set up basic stuff */
View::StartRendering(fps);
RenderCollideBox();
/* Objects */
for(int i = 0; i < model->elementObject.size(); ++i)
RenderObject(model->elementObject[i]);
RenderHUD();
}
void View_3D_Game::RenderCollideBox()
{
for(vector<Object*>::iterator it = model->getObject()->begin(); it != model->getObject()->end(); ++it)
{
Object* o = (Object*)*it;
if( !o->getActive() )
continue;
modelStack.PushMatrix();
Vector3 pos = o->getBbox()->position;
modelStack.Translate(pos.x, pos.y, pos.z);
modelStack.Scale(o->getBbox()->scale.x, o->getBbox()->scale.y, o->getBbox()->scale.z);
RenderMesh(Geometry::meshList[Geometry::GEO_DEBUG_CUBE], false);
modelStack.PopMatrix();
}
}
void View_3D_Game::RenderHUD()
{
//On screen text
if(Geometry::meshList[Geometry::GEO_AR_CHRISTY] != NULL)
{
std::ostringstream ss; //universal
/* FPS */
ss.precision(3);
ss << "FPS: " << fps;
RenderTextOnScreen(Geometry::meshList[Geometry::GEO_AR_CHRISTY], ss.str(), Color(1, 1, 0), 6, 18, 8);
ss.str("");
/* Pos */
ss << "Pos: " << model->getCamera()->position;
RenderTextOnScreen(Geometry::meshList[Geometry::GEO_AR_CHRISTY], ss.str(), Color(1, 0, 1), 6, 28, 4);
}
}
void View_3D_Game::SetModel(Model_Gameplay* model)
{
this->model = model;
}
void View_3D_Game::Exit()
{
View::Exit();
}
<file_sep>#ifndef ENTITY_H
#define ENTITY_H
#include "Mesh.h"
#include "MatrixStack.h"
#include "Collision.h"
#include <vector>
#include <string>
using namespace std;
class Entity
{
protected:
/*** modifyable data ***/
Mesh* mesh; //mesh to render (need?)
Vector3 scale; //scale
Vector3 position; //pos
Vector3 angle; //angle for X, Y, Z
bool active; //active?
public:
/*** constructor / destructor ***/
Entity();
virtual ~Entity();
/*** core ***/
void Set(Mesh* mesh, Vector3 scale, Vector3 position, bool active); //set basic info
virtual void Draw(); //render the object
void TranslateObject(float x, float y, float z);
void TranslateObject(Vector3 pos);
void ScaleObject(float x, float y, float z);
void ScaleObject(Vector3 scale);
void RotateObject(float x, float y, float z);
void Translate(float x, float y, float z);
void Translate(Vector3 pos);
void Scale(float x, float y, float z);
void Scale(Vector3 scale);
void Rotate(float x, float y, float z);
/*** getters setter ***/
Vector3 getScale();
Vector3 getPosition();
void setActive(bool b);
bool getActive();
};
#endif<file_sep>#include "Layer.h"
Collision Layer::collisionBox;
/* Constructor/destructor */
Layer::Layer()
{
edited = false;
}
Layer::~Layer()
{
}
void Layer::Set(Geometry::TILE_MAP tileMap, int layer, bool collidable, float tileScale)
{
this->tileMap;
this->layer = layer;
this->collidable = collidable;
this->tileScale = tileScale;
}
bool Layer::LoadTileLayer(string& txt)
{
TileMap.clear();
int xSize, ySize;
int yCounter = 0; //at which y tile
/* Find header */
string header0 = "Layer: ";
string header1 = "TileMap: ";
string header2 = "TileScale: ";
string header3 = "TilesX: ";
string header4 = "TilesY: ";
/* Utilities */
//0: get layer
//1: get tilemap
//2: get tilescale
//3: get tiles X
//4: get tiles Y
//5: load X and Y tiles
int steps = 0;
/* Open file */
ifstream myfile(txt); //overloaded constructor to open a text file imm. after declaration
string sentence = "";
if( myfile.is_open())
{
while( getline(myfile, sentence, '\n') )
{
switch ( steps )
{
case 0:
if( searchTerm(sentence, header0) )
{
/* Get layer number */
if( layer == getNumberFromRange(sentence) )
steps++;
}
break;
case 1:
/* Get tilemap */
if( searchTerm(sentence, header1) )
{
tileMap = static_cast<Geometry::TILE_MAP>(getNumberFromRange(sentence));
steps++;
}
else
return false; //file corrupted
break;
case 2:
/* Get tile scale */
if( searchTerm(sentence, header2) )
{
tileScale = getNumberFromRange(sentence);
steps++;
}
else
return false; //file corrupted
break;
case 3:
/* Get tiles X */
if( searchTerm(sentence, header3) )
{
xSize = getNumberFromRange(sentence);
steps++;
}
else
return false; //file corrupted
break;
case 4:
/* Get tiles Y */
if( searchTerm(sentence, header4) )
{
ySize = getNumberFromRange(sentence);
/* Resize tilemap */
TileMap.resize(xSize);
for(int i = 0; i < xSize; ++i)
TileMap[i].resize(ySize);
steps++;
}
else
return false; //file corrupted
break;
case 5:
/** Read from x and y **/
int counter = 0; //count how many tiles taken (X)
for(int i = 0; i < sentence.length(); ++i) //x
{
int tileNum = getNumberFromRange(sentence, counter);
TileMap[counter][yCounter] = tileNum;
}
yCounter++; //go next row
break;
}
}
//reach end
myfile.close();
}
else
{
return false;
}
return true;
}
void Layer::RecreateLayer(Geometry::TILE_MAP tileMap, int totalX, int totalY)
{
TileMap.clear();
this->tileMap = tileMap;
TileMap.resize(totalX);
for(int i = 0; i < totalX; ++i)
{
TileMap[i].resize(totalY);
}
}
bool Layer::WriteToTxt(string& txt)
{
return true;
}
void Layer::editTile(int& x, int& y, int TileType)
{
if( TileType < 0 || TileType > Geometry::tileMap_List[tileMap].totalTiles )
return;
TileMap[x][y] = TileType;
}
void Layer::Clear()
{
TileMap.clear();
}
bool Layer::checkCollision(Character* character)
{
/* If is non-collision layer */
if( !collidable )
return false;
bool b = false;
for(int i = 0; i < TileMap.size(); ++i) //X
{
for(int j = 0; j < TileMap[i].size(); ++j) //Y
{
if( TileMap[i][j] == 0 )
continue;
/* Set shared collision box to current tile pos */
collisionBox.SetForTile(i, j, tileScale);
/* Check collision with this tile */
b = Collision::CheckCollision(character->getObject()->collideBox, collisionBox);
}
}
return b;
}
/* Getter/setter */
Geometry::TILE_MAP Layer::getTileMap(){return tileMap;}
void Layer::setLayer(int layer){this->layer = layer;}
int Layer::getLayer(){return layer;}
void Layer::SetCollidable(bool c){this->collidable = c;}
bool Layer::getCollidable(){return collidable;}
void Layer::SetTileScale(float s){this->tileScale = s;}
float Layer::getTileScale(){return tileScale;}<file_sep>#ifndef MODEL_H
#define MODEL_H
#include "Player.h"
#include "MeshList.h"
#include "MatrixStack.h"
#include "Mtx44.h"
#include "Mesh.h"
#include "Light.h"
#include "MiniMap.h"
#include "UI_Object.h"
#include "Camera3.h"
#include "readFrom.h"
#include "writeTo.h"
#include "Physics.h"
#include <sstream>
#include <vector>
using namespace std;
/*************************************************************/
/*
Controller for models.
Contains:
vectors of various game objects.
individual game objects.
other info.
Function:
Manipulates the active state of game objects based on key inputs, events etc.
*/
/*************************************************************/
class Model
{
public:
/********************** states **********************/
//each state is 1 model
enum STATES
{
MAIN_MENU,
IN_GAME,
EDIT_LEVEL,
TOTAL_STATES,
};
/*********** vectors ***********/
vector<UI_Object*> UI_Object_List;
vector<Object*> elementObject;
static UI_Object* cursor;
/*********** constructor/destructor ***************/
Model();
virtual ~Model();
/*********** Set-up ***************/
virtual void Init();
/*********** Runtime ***************/
virtual void Update(double dt, bool* myKeys);
/*********** Quit ***************/
virtual void Exit();
/*********** getter / setters ***************/
Vector3 getCursorPos(Vector2 posOnScreen);
bool getbLightEnabled();
float getFOV();
static Camera* getCamera();
float getFPS();
Position getLightPos(int index);
vector<Object*>* getObject();
Object* getObject(int index);
static unsigned short getViewWidth();
static unsigned short getViewHeight();
static unsigned short getViewWidth2D();
static unsigned short getViewHeight2D();
static bool getSwitchState();
bool getInitLocal();
static STATES getCurrentState();
static void SetSwitchState(bool b);
Vector3 getWorldDimension();
protected:
/********************** View size *****************************/
static unsigned short m_view_width; //camera view size X
static unsigned short m_view_height; //camera view size Y
/* For UI */
static unsigned short m_2D_view_width; //camera view size X 2D
static unsigned short m_2D_view_height; //camera view size Y 2D
/************* Camera *****************/
static Camera camera; //2D camera
/************* Light *****************/
bool bLightEnabled;
float fps;
/************ lights ************/
const static unsigned TOTAL_LIGHTS = 2;
Position lightPos[TOTAL_LIGHTS];
/************ Flags ************/
static bool InitAlready; //have we init all global stuff already?
bool initLocalAlready; //have we init these local stuff already?
/*** Switch state? ***/
static bool switchState; //do we switch to another model?
static STATES currentState;
/*********** Text files ************/
static string map_list; //store all existing maps name
/*********** Utilities ************/
void InitMesh();
/* Use only if this model will be having enum */
virtual void NewStateSetup() = 0; //if changing LOCAL state, call this function so new state can init stuff
virtual void OldStateExit() = 0; //if changing LOCAL state, call this function so previous state can exit
};
#endif<file_sep>#pragma once
#include "Mesh.h"
class MiniMap
{
private:
// Rotation from first angle
int angle;
// Offset in the minimap
int x;
int y;
// Minimap size
int size_x;
int size_y;
public:
MiniMap(void);
virtual ~MiniMap(void);
Mesh* m_Minimap_Background;
Mesh* m_Minimap_Border;
Mesh* m_Minimap_Avatar;
// Set the background mesh to this class
bool SetBackground(Mesh* aBackground);
// Get the background mesh to this class
Mesh* GetBackground(void);
// Set the border mesh to this class
bool SetBorder(Mesh* aBorder);
// Get the border mesh to this class
Mesh* GetBorder(void);
// Set the Avatar mesh to this class
bool SetAvatar(Mesh* anAvatar);
// Get the Avatar mesh to this class
Mesh* GetAvatar(void);
// Set the angle of avatar
bool SetAngle(const int angle);
// Get the angle of avatar
int GetAngle(void);
// Set the position of avatar in minimap
bool SetPosition(const int x, const int y);
// Get position x of avatar in minimap
int GetPosition_x(void);
// Get position y of avatar in minimap
int GetPosition_y(void);
// Set the size of minimap(calculation of avatar in minimap)
bool SetSize(const int size_x, const int size_y);
// Get the size of minimap(x)
int GetSize_x(void);
// Get the size of minimap(y)
int GetSize_y(void);
};
<file_sep>#include "Collision2.h"
/* AABB Collision2 */
Vector3 currentStart; //current collide bound
Vector3 currentEnd;
Vector3 previousStart; //current collide bound @ previous frame
Vector3 previousEnd;
Vector3 checkStart, checkEnd; //start and end for box
Vector3 currentPos; //current position
float offset = 0.00001f; //cannot be 0 (or will considered collision even if touching)
float opposite = 0; //Y
float ajacent = 0; //X
float tangent = 0;
/* Utility variables */
vector<Collision2*> Collision2::slideList;
Vector3 Collision2::originalPos; //original initial pos
Vector3 Collision2::noCollisionPos; //final pos if no collision
Collision2* lastCollided;
Vector3 Collision2::originalVel;
bool gg = false;
bool y = false;
Vector3 Collision2::noSlidePos;
bool b = false;
Collision2::Collision2()
{
}
/* Init */
void Collision2::Set(Vector3 pos, Vector3 scale, TYPE type)
{
position = pos;
previousPos = pos;
this->scale = scale;
this->type = type;
collideX = collideY = false;
}
/* Update */
void Collision2::Start(const Vector3& objectPos, const Vector3& velocity)
{
if(type == BOX)
{
/* Reset variables */
slideList.clear();
lastCollided = NULL;
originalVel = velocity;
originalPos = previousPos = objectPos;
noCollisionPos = position = objectPos + velocity;
/* set all collide flags to false */
collideX = collideY = false;
/* Set tangent and direction */
SetTangentAndDir(velocity);
b = false;
}
}
void Collision2::SetTangentAndDir(const Vector3& velocity)
{
/* Not moving */
originalVel = velocity;
if(originalVel.IsZero())
{
return;
}
/** Calculate opp, ajacent and tangent **/
if(velocity.y > 0.f)
{
opposite = previousPos.y - position.y; //Y
ajacent = position.x - previousPos.x; //X
}
else
{
opposite = previousPos.y - position.y; //Y
ajacent = position.x - previousPos.x; //X
}
tangent = opposite * (1.f / ajacent);
/** Is ajacent 0 ? **/
//Yes: opp / 0 == opp
//No: normal tangent calculation
gg = false;
(ajacent >= -Math::EPSILON && ajacent <= Math::EPSILON ) ? gg = true : gg = false; //Going Full Y
(opposite >= -Math::EPSILON && opposite <= Math::EPSILON ) ? y = true : y = false; //going Full X
}
Collision2* a;
Collision2* c;
bool Collision2::CheckCollision(Collision2& current, Collision2& check)
{
/************ Standardise ************/
//BOX/SLANTED_BOX must always be current, unless current and check are both SPHERE
a = ¤t;
c = ✓
/************ Reject ************/
if(a->type == SLANTED_BOX && c->type == SLANTED_BOX)
return false;
else if( (a->type == BOX && c->type == SLANTED_BOX) ||
(a->type == SLANTED_BOX && c->type == BOX) )
return false;
/************ Swap ************/
//current type: sphere --- check tye: box ===> Swap
//current type: sphere --- check tye: slanted_box ===> Swap
if(a->type == BOX || a->type == SLANTED_BOX)
{
if(c->type == SPHERE)
{
a = ✓
c = ¤t;
}
}
/************ Check collide ************/
//possible combinations:
//1) current type: Sphere --- Check type: Sphere
//3) current type: Sphere --- Check type: Slanted Box
//4) current type: Sphere --- Check type: Box
//2) current type: Box --- Check type: Box
//see current type is what type of collide bound
//1)
if(a->type == SPHERE && c->type == SPHERE)
{
return SphereToSphere(a, c);
}
else if(a->type == SPHERE && c->type == SLANTED_BOX)
{
return SphereToSlantedBox(a, c);
}
else if(a->type == SPHERE && c->type == BOX)
{
return SphereToBox(a, c);
}
else if(a->type == BOX && c->type == BOX)
{
return BoxToBox(a, c);
}
return false;
}
Collision2::~Collision2()
{
}
/* Sphere (current) to Sphere (check) */
bool Collision2::SphereToSphere(Collision2* current, Collision2* check)
{
return false;
}
/* Sphere (current) to Slanted Box (check) */
bool Collision2::SphereToSlantedBox(Collision2* current, Collision2* check)
{
return false;
}
/* Sphere (current) to Box (check) */
bool Collision2::SphereToBox(Collision2* current, Collision2* check)
{
return false;
}
/** Function Assume Direction is Bottom Right (BR) **/
void Collision2::SetToXPos(const float& tangent, const float& xPos, Vector3& currentPos)
{
/* get the Y */
//only ajacent and tangent can be deduced currently
float ajacent = xPos - currentPos.x; //X
float opposite = tangent * ajacent; //Y
currentPos.y -= opposite;
currentPos.x = xPos;
}
void Collision2::SetToYPos(const float& tangent, const float& yPos, Vector3& currentPos)
{
/* get the X */
//only ajacent and tangent can be deduced currently
float opposite = currentPos.y - yPos; //Y
float ajacent = opposite * (1.f / tangent); //X
currentPos.x += ajacent;
currentPos.y = yPos;
}
/* Box (current) to Box (check) */
bool Collision2::BoxToBox(Collision2* current, Collision2* check)
{
/* if not moving, not colliding with anything else */
if( originalVel.IsZero() )
{
return false;
}
/** Test eligibility for sliding check **/
if( broadPhrase(originalPos, noCollisionPos, check->position, current->scale, check->scale) )
{
slideList.push_back(check);
/** Test eligibility for collision **/
if( !broadPhrase(current->previousPos, current->position, check->position, current->scale, check->scale) )
{
return false;
}
if( CheckAndResponse(current, check) )
{
lastCollided = check; //no need check slide with current
return true;
}
}
return false;
}
float contactX = 0;
float contactY = 0;
float yOffset = 0;
void Collision2::Reset()
{
//cout <<"X: " << collideX << " Y: " << collideY << endl;
previousPos = position; //set starting pos to current pos
//if( isEqual(previousPos, noCollisionPos) )
//{
// return;
//}
/* Slide check */
if( !collideX ) //if not collided X, can go all the way
{
position.x = noCollisionPos.x;
}
else if( !collideY ) //if not collided Y, can go all the way
{
position.y = noCollisionPos.y;
}
noSlidePos = previousPos;
originalVel = position - previousPos; //remaining vel to travel
/* RESET tangent and direction */
SetTangentAndDir(originalVel); //only do this after previousPos and position done properly
//b = true;
//if( direction == STATIONARY)
//{
// return;
//}
//
/* check through if collide with any other boxes in original broadphrase */
for(int i = 0; i < slideList.size(); ++i)
{
if(slideList[i] != lastCollided)
{
/** Test eligibility for collision **/
if( !broadPhrase(previousPos, position, slideList[i]->position, this->scale, slideList[i]->scale) )
{
continue;
}
CheckAndResponse(this, slideList[i]);
}
}
}
bool Collision2::isEqual(Vector3& a, Vector3 & b)
{
return (a.x >= b.x - Math::EPSILON && a.x <= b.x + Math::EPSILON) &&
(a.y >= b.y - Math::EPSILON && a.y <= b.y + Math::EPSILON) &&
(a.z >= b.z - Math::EPSILON && a.z <= b.z + Math::EPSILON);
}
Vector3 checkScale_Half;
Vector3 currentScale_Half;
bool Collision2::CheckAndResponse(Collision2* current, Collision2* check)
{
/* holding variable to store current position (So actual position not modified during checking) */
currentPos = current->position;
/* Half scale */
checkScale_Half = check->scale * 0.5f;
currentScale_Half = current->scale * 0.5f;
/* update start and end */
currentStart = currentPos - currentScale_Half;
currentEnd = currentPos + currentScale_Half;
previousStart = current->previousPos - currentScale_Half;
previousEnd = current->previousPos + currentScale_Half;
/** checkBox start and end **/
checkStart = check->position - checkScale_Half; //set start for box1
checkEnd = check->position + checkScale_Half; //set end for box1
/************************************ Check Collision2 ************************************/
/** Test 1: check if collide at X side **/
/** Test 2: check if collide at Y side **/
//pos just touching X side
if( gg == false ) //TANGENT == 1: NEVER CONTACT X SIDE
{
if(originalVel.x > 0.f) //if right side
{
contactX = check->position.x - (checkScale_Half.x + currentScale_Half.x) - offset;
}
else
{
contactX = check->position.x + (checkScale_Half.x + currentScale_Half.x) + offset;
}
SetToXPos(tangent, contactX, currentPos); //translate to touch X side
currentStart = currentPos - currentScale_Half; //set start for current
currentEnd = currentPos + currentScale_Half; //set end for current
/** once X side is touched, check if y range intersects (current.y intersects check.y) **/
if(currentEnd.y > checkStart.y && currentStart.y < checkEnd.y)
{
current->collideX = current->collideY = false;
current->position = currentPos;
current->collideX = true;
return true;
}
}
/** else, check if can contact at Y start **/
if( y == false )
{
/* translate to just touching top of check box */
if(originalVel.y > 0.f) //if right side
{
yOffset = -(checkScale_Half.y + currentScale_Half.y + offset);
}
else
{
yOffset = (checkScale_Half.y + currentScale_Half.y + offset);
}
/* contact point Y */
contactY = check->position.y + yOffset;
SetToYPos(tangent, contactY, currentPos);
currentStart = currentPos - currentScale_Half; //set start for current
currentEnd = currentPos + currentScale_Half; //set end for current
/* translate start and end Y in opp dir of Contact Point Y to see if they intersect */
currentStart.y -= yOffset;
currentEnd.y -= yOffset;
/* check if collide (X and Y) */
if(checkAABBCollide(currentStart, currentEnd, checkStart, checkEnd))
{
current->collideX = current->collideY = false;
current->position = currentPos;
current->collideY = true;
return true;
}
}
/* if no contact, return false */
return false;
}
bool Collision2::broadPhrase(Vector3& originalPos, Vector3& finalPos, Vector3& checkPos, Vector3& currentScale, Vector3& checkScale)
{
/************************************ Check if box needs collision check ************************************/
/* Check if checkBox collides with start-end zone */
/* length and height of zone */
float length = finalPos.x - originalPos.x; //x
float height = finalPos.y - originalPos.y; //y
float width = finalPos.z - originalPos.z; //z
Vector3 startZone, endZone;
//x
if(length > 0)
{
startZone.x = originalPos.x - currentScale.x * 0.5f;
endZone.x = finalPos.x + currentScale.x * 0.5f;
}
else
{
startZone.x = finalPos.x - currentScale.x * 0.5f;
endZone.x = originalPos.x + currentScale.x * 0.5f;
}
//y
if(height > 0)
{
startZone.y = originalPos.y - currentScale.y * 0.5f;
endZone.y = finalPos.y + currentScale.y * 0.5f;
}
else
{
startZone.y = finalPos.y - currentScale.y * 0.5f;
endZone.y = originalPos.y + currentScale.y * 0.5f;
}
//z
if(width > 0)
{
startZone.z = originalPos.z - currentScale.z * 0.5f;
endZone.z = finalPos.z + currentScale.z * 0.5f;
}
else
{
startZone.z = finalPos.z - currentScale.z * 0.5f;
endZone.z = originalPos.z + currentScale.z * 0.5f;
}
checkStart = checkPos - checkScale * 0.5f;
checkEnd = checkPos + checkScale * 0.5f;
/** Check if in X-Y of broad phrase **/
if(!checkAABBCollide(startZone, endZone, checkStart, checkEnd)) //if checkBox not in start-end zone
{
return false;
}
return true;
}
bool Collision2::inZone(float& start, float& end, float& checkStart, float& checkEnd)
{
//check x and y only
return (end > checkStart && start < checkEnd);
}
bool Collision2::checkAABBCollide(Vector3& currentStart, Vector3& currentEnd, Vector3& checkStart, Vector3& checkEnd)
{
//check x and y only
return (currentEnd.x > checkStart.x && currentStart.x < checkEnd.x) &&
(currentEnd.y > checkStart.y && currentStart.y < checkEnd.y);
}
<file_sep>#pragma once
#include <ostream>
#include "Vector3.h"
#include <vector>
using namespace std;
/**
STRICTLY FOR AABB ONLY
store bool for all 6 sides of a cuboid collision box for AABB only
**/
struct Movement_3d
{
/* For Bound Box */
enum COLLIDE
{
start_X,
end_X,
start_Y,
end_Y,
start_Z,
end_Z,
UNDEFINED,
};
/* constructor destructor */
COLLIDE collideSide; //which side collide
Movement_3d(){collideSide = UNDEFINED;}
Movement_3d(const Movement_3d& copy){collideSide = copy.collideSide;}
~Movement_3d(){}
/* utilities */
void Reset(){collideSide = UNDEFINED;}
Movement_3d& operator= (Movement_3d& copy){collideSide = copy.collideSide;return *this;}
bool operator== (Movement_3d::COLLIDE& check){return collideSide == check;}
};
class Collision2
{
public:
enum TYPE
{
BOX,
SPHERE,
SLANTED_BOX,
};
/* Core */
//initialize
void Set(Vector3 pos, Vector3 scale, TYPE type);
//runtime
void Start(const Vector3& objectPos, const Vector3& velocity); //before checking must set up
void Reset();
/* Check if collide: */
//pass in current object's collide box and collide box of object being compared
static bool CheckCollision(Collision2& current, Collision2& check);
//1) current type: Sphere --- Check type: Sphere
//3) current type: Sphere --- Check type: Slanted Box
//4) current type: Sphere --- Check type: Box
//2) current type: Box --- Check type: Box
/* Sphere (current) to Sphere (check) */
static bool SphereToSphere(Collision2* current, Collision2* check);
/* Sphere (current) to Slanted Box (check) */
static bool SphereToSlantedBox(Collision2* current, Collision2* check);
/* Sphere (current) to Box (check) */
static bool SphereToBox(Collision2* current, Collision2* check);
/* Box (current) to Box (check) */
static bool BoxToBox(Collision2* current, Collision2* check);
/* Collision2 response */
//for respone, set object pos to collision pos
Collision2();
~Collision2();
TYPE type;
/* Variables for all collision type */
Vector3 position;
Vector3 scale; //if is Sphere, scale.set(radius, radius, radius);
/* aabb variables */
Vector3 previousPos;
bool collideX, collideY;
static Vector3 noSlidePos;
static Vector3 originalVel;
private:
/* Tangent and Direction */
void SetTangentAndDir(const Vector3& velocity); //set tangent and direction
static void SetToXPos(const float& tangent, const float& xPos, Vector3& currentPos);
static void SetToYPos(const float& tangent, const float& xPos, Vector3& currentPos);
/* sliding */
static vector<Collision2*> slideList;
static Vector3 originalPos; //original initial pos
static Vector3 noCollisionPos; //final pos if no collision
/* AABB Detection */
static bool broadPhrase(Vector3& originalPos, Vector3& finalPos, Vector3& checkPos, Vector3& currentScale, Vector3& checkScale);
static bool inZone(float& start, float& end, float& checkStart, float& checkEnd);
static bool checkAABBCollide(Vector3& currentStart, Vector3& currentEnd, Vector3& checkStart, Vector3& checkEnd);
/* AABB Response */
static bool CheckAndResponse(Collision2* current, Collision2* check);
bool isEqual(Vector3& a, Vector3 & b);
};<file_sep>#include "SpriteAnimation.h"
#include "MyMath.h"
#include "GL\glew.h"
#include "Vertex.h"
SpriteAnimation::SpriteAnimation(const std::string &meshName, int row, int col)
: Mesh(meshName)
, m_row(row)
, m_col(col)
, m_totalFrame(0)
, m_currentRow(0)
, m_currentCol(0)
, m_currentTime(0)
,m_frameTime(0)
{
}
void SpriteAnimation::init(float time, int startCol, int startRow, int endCol, int endRow, bool oppDir)
{
/* set total frame and frame time */
//total rows
this->oppDir = oppDir;
this->startRow = startRow;
this->endRow = endRow;
this->startCol = startCol;
this->endCol = endCol;
int totalRow = endRow - (startRow - 1);
int totalCol = m_col - startCol; //first row
totalCol += m_col * ((endRow) - (startRow + 1));
totalCol += endCol;
m_totalFrame = totalCol + totalRow;
m_frameTime = time;
/* set current row and column */
if(!this->oppDir) //if normal dir: start from start
{
m_currentRow = startRow;
m_currentCol = startCol;
}
else //if !normal dir: start from end
{
m_currentRow = endRow;
m_currentCol = endCol;
}
/* error check */
if(m_currentRow < 0 || m_currentRow >= m_row)
m_currentRow = m_row - 1;
if(m_currentCol < 0 || m_currentCol >= m_col)
m_currentCol = 0;
}
SpriteAnimation::~SpriteAnimation()
{
}
void SpriteAnimation::Update(double dt)
{
/* time keeps updating */
m_currentTime += dt;
/* if past frame time, go on to next frame */
if(m_currentTime > m_frameTime)
{
/* timer reset */
m_currentTime = 0.f;
/* increase column */
if(!oppDir)
++m_currentCol;
else
--m_currentCol;
}
if(!oppDir)
{
/* if not reach last row */
if(m_currentRow < endRow)
{
/* if col exceed */
if(m_currentCol >= m_col)
{
m_currentCol = 0;
++m_currentRow;
}
}
/* reach last row */
else if(m_currentRow == endRow)
{
/* if col exceed */
if(m_currentCol > endCol)
{
m_currentCol = startCol;
m_currentRow = startRow;
}
}
}
/* opp. Direction: flip everything */
else if(oppDir)
{
/* if not reach last row */
if(m_currentRow > startRow)
{
/* if col exceed */
if(m_currentCol < 0)
{
m_currentCol = m_col - 1;
--m_currentRow;
}
}
/* reach last row */
else if(m_currentRow == startRow)
{
/* if col exceed */
if(m_currentCol < startCol)
{
m_currentCol = endCol;
m_currentRow = endRow;
}
}
}
}
void SpriteAnimation::Render()
{
unsigned count = 6; //a quad has 6 sides
unsigned offset = 0;
offset = (m_currentCol + (m_currentRow * m_col)) * count;
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)sizeof(Position));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(Position) + sizeof(Color)));
//if(textureID > 0)
//{
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(Position) + sizeof(Color) + sizeof(Vector3)));
//}
//glDrawArrays(GL_TRIANGLES, offset, count);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
if(mode == DRAW_LINES)
glDrawElements(GL_LINES, count, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint)));
else if(mode == DRAW_TRIANGLE_STRIP)
glDrawElements(GL_TRIANGLE_STRIP, count, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint)));
else
glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, (void*)(offset * sizeof(GLuint)));
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
//if(textureID > 0)
//{
glDisableVertexAttribArray(3);
//}
}<file_sep>#ifndef FONTDATA_H
#define FONTDATA_H
#include "readFrom.h"
#include "writeTo.h"
void getFontData(char* name, float* fontData);
#endif<file_sep>#include "UI_Object.h"
#include "Controller.h"
#include "View.h"
Vector3 UI_Object::start, UI_Object::end, UI_Object::checkStart, UI_Object::checkEnd;
/*** constructor / destructor ***/
UI_Object::UI_Object()
{
}
UI_Object::~UI_Object()
{
}
/*** core ***/
void UI_Object::Set(string word, Mesh* mesh, float scaleX, float scaleY, float posX, float posY, float zHeight, bool active)
{
this->word = word;
Entity::Set(mesh, Vector3(scaleX, scaleY, 1), Vector3(posX, posY, zHeight), active);
}
bool UI_Object::CollisionDetection(UI_Object* checkMe, bool clicked)
{
/* Start and end */
start = position - scale * 0.5f;
end = position + scale * 0.5f;
checkStart = checkMe->position - checkMe->scale * 0.5f;
checkEnd = checkMe->position + checkMe->scale * 0.5f;
return Collision::QuickAABBDetection2D(start, end, checkStart, checkEnd);
}
/* Getter setter */
void UI_Object::SetPosition(Vector3& pos)
{
this->position.SetXY(pos.x, pos.y);
}
Vector3 UI_Object::getPosition()
{
return position;
}
void UI_Object::SetScale(Vector3 scale)
{
this->scale = scale;
}
Vector3 UI_Object::getScale()
{
return scale;
}
Mesh* UI_Object::getMesh()
{
return mesh;
}
bool UI_Object::getActive()
{
return active;
}
void UI_Object::SetActive(bool active)
{
this->active = active;
}
string UI_Object::getWord()
{
return word;
}
float UI_Object::getWordScale()
{
return wordScale * scale.y;
}
void UI_Object::Update(double dt)
{
}
void UI_Object::Draw()
{
if( getActive() )
{
View::RenderMeshIn2D(mesh, false, scale.x, scale.y, position.x, position.y, position.z, 0);
/** word **/
if( word.length() > 0 )
{
View::RenderTextOnScreen(Geometry::meshList[Geometry::GEO_AR_CHRISTY], word, Color(1, 0, 1), getWordScale(),
position.x, position.y, position.z);
}
}
}
/** Button **/
float Button::wordScale = 0.4f;
double Button::depressionTime = 0.2f;
/*** constructor / destructor ***/
Button::Button()
{
depressionTimer = 0.0;
clicked = false;
}
Button::~Button()
{
}
/*** core ***/
void Button::Set(string word, Mesh* mesh, float scaleX, float scaleY, float posX, float posY, float zHeight, bool active, float depression)
{
UI_Object::Set(word, mesh, scaleX, scaleY, posX, posY, zHeight, active);
this->depression = depression;
}
bool Button::CollisionDetection(UI_Object* checkMe, bool activate)
{
/* If clicked before already, not considerd collide */
if( clicked )
{
return false;
}
/* Start and end */
bool b = false;
if( activate )
{
b = UI_Object::CollisionDetection(checkMe, activate);
if( b && !clicked )
{
clicked = true;
position -= scale * depression;
}
}
return b;
}
void Button::Update(double dt)
{
if( clicked )
{
depressionTimer += dt;
if( depressionTimer >= depressionTime )
{
depressionTimer = 0.f;
position += scale * depression;
clicked = false;
}
}
}
void Button::Draw()
{
UI_Object::Draw();
}
bool Button::getClicked()
{
return clicked;
}
/** Popup **/
/*** constructor / destructor ***/
Popup::Popup()
{
}
Popup::~Popup()
{
}
/*** core ***/
void Popup::Set(string word, Mesh* mesh, float scaleX, float scaleY, float posX, float posY, float zHeight, bool active)
{
UI_Object::Set("", mesh, scaleX, scaleY, posX, posY, zHeight, active);
/* Button */
quitButton = new UI_Object;
quitButton->Set(word, Geometry::meshList[Geometry::GEO_CUBE_RED], scaleY * 0.05f, scaleY * 0.05f, posX + scaleX * 0.47f, posY + scaleY * 0.46f , zHeight + 0.01f, active);
}
bool Popup::CollisionDetection(UI_Object* checkMe, bool clicked)
{
if( !clicked ) //if not clicked
return false;
bool b = quitButton->CollisionDetection(checkMe, clicked);
if( b )
active = !active;
return b;
}
void Popup::Update(double dt)
{
}
void Popup::Draw()
{
if( getActive() )
{
View::RenderMeshIn2D(mesh, false, scale.x, scale.y, position.x, position.y, position.z, 0);
/* Button */
Vector3 pos11 = quitButton->getPosition();
Vector3 scale11 = quitButton->getScale();
View::RenderMeshIn2D(quitButton->getMesh(), false, scale11.x, scale11.y, pos11.x, pos11.y, pos11.z, 0);
}
}
/* Getter/setter */
UI_Object* Popup::getButton()
{
return quitButton;
}
/** Selection menu **/
Vector3 Selection_Menu::s;
/*** constructor / destructor ***/
Selection_Menu::Selection_Menu()
{
currentItem = totalItem = itemScale = 0;
currentPos.SetZero();
}
Selection_Menu::~Selection_Menu()
{
}
/*** core ***/
void Selection_Menu::Set(float sc, float itemScale, float posX, float posY, float zHeight, bool active)
{
UI_Object::Set("", mesh, sc, sc, posX, posY, zHeight, active);
this->itemScale = itemScale;
}
void Selection_Menu::Init()
{
/** Fit items into perfect square grid **/
itemPos.resize( totalItem );
float sq = static_cast<float>(itemPos.size());
sq = sqrt( sq );
int len = static_cast<int>(sq); //to test 0
if( sq - len >= 0.f ) //if is not zero
sq = ++len;
itemScale *= (1.f / sq);
float scaleVal = scale.x * ( 1.f / sq ); //scale val per
float posX = (position.x - scale.x * 0.5f) + (scaleVal * 0.5f);
float posY = (position.y + scale.y * 0.5f) - (scaleVal * 0.5f);
float posZ = position.z + 0.05f;
int counter = 0;
for(int i = 0; i < itemPos.size(); ++i, ++counter)
{
itemPos[i].Set( posX, posY, posZ);
posX += scaleVal;
if( counter >= len )
{
counter = 0;
posX = (position.x - scale.x * 0.5f) + (scaleVal * 0.5f);
posY -= scaleVal;
}
}
}
void Selection_Menu::AddItem(Mesh* mesh)
{
itemList.push_back(mesh);
++totalItem;
}
bool Selection_Menu::CollisionDetection(UI_Object* checkMe, bool clicked)
{
/* Start and end */
checkStart = checkMe->getPosition() - checkMe->getScale() * 0.5f;
checkEnd = checkMe->getPosition() + checkMe->getScale() * 0.5f;
s.Set(itemScale, itemScale, 1);
for(int i = 0; i < totalItem; ++i)
{
start = itemPos[i] - s * 0.5f;
end = itemPos[i] + s * 0.5f;
if( Collision::QuickAABBDetection2D(start, end, checkStart, checkEnd) )
{
if( clicked )
currentItem = i;
return true;
}
}
return false;
}
void Selection_Menu::Draw()
{
/** selection menu **/
if( getActive() )
{
/** Popup mesh */
/* Quit button */
Vector3 pos11;
for(int i = 0; i < totalItem; ++i)
{
/* So that tile sets final scale will match given scale */
//float t_scale = model->tileSelectionMenu->getItemScale();
pos11 = getItemPos(i);
View::RenderMeshIn2D(getItemMesh(i), false, itemScale, itemScale, pos11.x, pos11.y, pos11.z, 0);
/* Selected */
if( currentItem == i ) //selected this block
{
View::RenderMeshIn2D(Geometry::meshList[Geometry::GEO_SELECTOR], false, itemScale * 1.1f, itemScale * 1.1f, pos11.x, pos11.y, pos11.z, 0);
}
}
}
}
Vector3 Selection_Menu::getItemPos(int index)
{
if( index < 0 || index >= totalItem )
return Vector3(0, 0, 0);
return itemPos[index];
}
Mesh* Selection_Menu::getItemMesh(int index)
{
if( index < 0 || index >= totalItem )
return NULL;
return itemList[index];
}
int Selection_Menu::getTotalItem()
{
return totalItem;
}
float Selection_Menu::getItemScale()
{
return itemScale;
}
void Selection_Menu::Update(double dt)
{
}
int Selection_Menu::getCurrentItem()
{
return currentItem;
}
/** Textbox **/
float TextBox::max_wordWidth = 0.9f;
/*** constructor / destructor ***/
TextBox::TextBox()
{
typed = false;
word = returnText = "";
}
TextBox::~TextBox()
{
}
/*** core ***/
void TextBox::Set(Mesh* mesh, float scaleX, float scaleY, float posX, float posY, float zHeight, bool active)
{
UI_Object::Set("", mesh, scaleX, scaleY, posX, posY, zHeight, active);
}
bool TextBox::CollisionDetection(UI_Object* checkMe, bool clicked)
{
bool b = UI_Object::CollisionDetection(checkMe, clicked);
if( b && clicked)
{
activated = !activated;
}
/* click anywhere else will deactivate textbox */
if( clicked && activated && !b )
{
activated = false;
}
/* Backspace clears all */
return b;
}
void TextBox::Update(double dt)
{
if( !activated )
return;
/* Type */
char a = Controller::characterPressed();
if( a != '/' )
{
word += a;
typed = true;
}
/* Backspace */
/*else if( Controller::IsKeyPressed(VK_BACK) )
{
if(word.length() > 0)
word.pop_back();
}*/
}
void TextBox::Draw()
{
/* Type */
if( getActive() )
{
/* Box */
View::RenderMeshIn2D(mesh, false, scale.x, scale.y, position.x, position.y, position.z, 0);
/* Text */
View::RenderTextOnScreenStart0(Geometry::meshList[Geometry::GEO_AR_CHRISTY],
getWord(), Color(1, 0, 1), getWordScale(), getStartPosX(), position.y, position.z);
}
}
string TextBox::getWord()
{
if( typed )
{
returnText = word;
int stopAt = 0;
float len = 0.f;
float sc = wordScale * scale.y;
/* Total text length */
for(int i = word.length() - 1; i >= 0; --i)
{
len += View::FontData[word[i]] * sc;
++stopAt;
/* Exceed length */
if( len > scale.x * max_wordWidth )
{
--stopAt;
returnText = word.substr(word.length() - stopAt); //get from stopAt till end
}
}
typed = false;
return returnText;
}
return
returnText;
}
float TextBox::getStartPosX()
{
return position.x - ( (scale.x * max_wordWidth) * 0.5f);
}<file_sep>#ifndef VIEW_3D_GAME_H
#define VIEW_3D_GAME_H
#include "View.h"
//Include GLEW
#include <GL/glew.h>
//Include GLFW
#include <GLFW/glfw3.h>
/**
Everything in view class will be using Objects class for TRS and other info
**/
class View_3D_Game : public View
{
/********************** model and view ptr **********************/
Model_Gameplay* model;
public:
/********************** constructor/destructor *****************************/
View_3D_Game();
View_3D_Game(Model_Gameplay* model, unsigned short console_width, unsigned short console_height, MODE mode);
~View_3D_Game();
/********************** Core functions *****************************/
virtual void Init();
virtual void Render(const float fps);
virtual void Exit();
/**************** render ****************/
void RenderCollideBox();
void RenderHUD();
/**************** Utilites ******************/
void SetModel(Model_Gameplay* model);
};
#endif<file_sep>#ifndef MODEL_LEVEL_EDITOR_H
#define MODEL_LEVEL_EDITOR_H
#include "Model_Gameplay.h"
class Model_Level_Editor : public Model
{
public:
/** vectors **/
/** UI List **/
enum UI_LIST
{
/* UIs */
UI_BLOCK_SELECTION_BAR,
UI_SIDE_BAR,
TOTAL_UI,
};
enum BUTTON_LIST
{
/* EDIT_LAYER */
BUTTON_PREVIOUS_BLOCK, //left
BUTTON_NEXT_BLOCK, //right
/* CHOOSE_TILE_MAP */
BUTTON_CHANGE_TILE_MAP,
/* ADD_NEW_MAP */
BUTTON_ADD_NEW_MAP, //also choose map
/* ADD_NEW_LAYER */
BUTTON_ADD_NEW_LAYER, //also choose layer
TOTAL_BUTTON,
};
/* Button list */
vector<Button*> buttonList;
/** States **/
enum STATE
{
ADD_NEW_MAP,
//add new map to list of maps
ADD_NEW_LAYER,
//add new layer to current map
EDIT_MAP,
//open current map in edit mode
EDIT_LAYER,
//open current layer of current map in edit mode
CHOOSE_TILE_MAP,
//choose tile map to load, once map and layer selected
DEFAULT,
};
/* If doing action, certain other stuff need to stop */
enum ACTIONS
{
SELECTING_TILES,
NONE,
TOTAL_ACTIONS,
};
ACTIONS currentAction;
/* Map stuff */
TextBox* new_map_textbox;
/* TileMap stuff */
Popup* tileMap_Menu;
Selection_Menu* tileSelectionMenu;
Geometry::TILE_MAP current_TileMap; //current tilemap to use
int currentBlock; //current block to add
Vector3 tile_startPos; //starting pos of tiles
float tileSpacing; //spacing for displaying tiles in editor
float tileScale; //scale of tiles
/* Path for map file and tile map */
int currentLayer; //current layer index of current map
int currentMap; //current map
string currentMapName; //curent map
vector<Map*> mapList;
char* tileMapPath;
/* blocks */
Physics moveBlock; //physics to move blocks
bool shiftBlock_Left, shiftBlock_Right;
Vector3 newPos; //new pos to reach
/* Internal */
STATE state, previousState;
/* Utilities */
UI_Object useMe; //for general usage
static string name;
Vector3 start, end, checkStart, checkEnd; //for collision
Vector3 pos, scale;
float z;
/*********** constructor/destructor ***************/
Model_Level_Editor();
~Model_Level_Editor();
/*********** core functions ***************/
virtual void Init();
void InitUtilities();
void InitAddNewMap();
void InitAddNewLayer();
void InitEditMap();
void InitEditLayer();
void InitChooseTileMap();
void PopulateMapsFromTxt();
virtual void NewStateSetup();
virtual void OldStateExit();
virtual void Update(double dt, bool* myKeys);
void UpdateAddNewMap(double dt, bool* myKeys);
void UpdateAddNewLayer(double dt, bool* myKeys);
void UpdateEditLayer(double dt, bool* myKeys);
void UpdateEditMap(double dt, bool* myKeys);
void UpdateChooseTileMap(double dt, bool* myKeys);
virtual void Exit();
/*********** Utilities ***************/
};
#endif<file_sep>#include "Character.h"
/* Constructor/destructor */
Character::Character()
{
}
Character::~Character()
{
delete sprite;
}
/* Core */
void Character::Init(Vector3 pos, Vector3 scale, DIRECTION facingDir)
{
}
void Character::Update(double dt)
{
/* Mesh */
sprite->Update(dt);
}
/* Getter/Setter */
Vector3 Character::getPosition()
{
return object.getPosition();
}
Vector3 Character::getScale()
{
return object.getScale();
}
Mesh* Character::getMesh()
{
return sprite;
}
Object* Character::getObject()
{
return &object;
}<file_sep>#ifndef MODEL_MAINMENU_H
#define MODEL_MAINMENU_H
#include "Model.h"
class Model_MainMenu : public Model
{
public:
/*********** constructor/destructor ***************/
Model_MainMenu();
~Model_MainMenu();
/*********** core functions ***************/
virtual void Init();
void InitObject();
virtual void NewStateSetup();
virtual void OldStateExit();
virtual void Update(double dt, bool* myKeys);
virtual void Exit();
};
#endif<file_sep>#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#ifdef _DEBUG
#define DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif
#ifndef CONTROLLER_H
#define CONTROLLER_H
/* View */
#include "View_3D_Game.h"
#include "View_MainMenu.h"
#include "View_LevelEditor.h"
#include "timer.h"
/*************************************************************/
/*
Contains:
Pointer to current view and current model.
A set of pointers of all models and views.
Function:
*/
/*************************************************************/
class Controller
{
public:
/********************** enums **********************/
enum MODE
{
TWO_D,
THREE_D,
};
/******************** core functions **********************/
void Init();
void Run();
void Exit();
/********************** controller functions **********************/
static bool IsKeyPressed(unsigned short key);
static char characterPressed();
/********************** getter setter **********************/
float getFPS();
bool* getKeyPressed();
static Vector2 GetCursorPos();
/********************* constructor / destructor *********************/
Controller();
~Controller();
/*********************** For scrolling **********************/
static void setScrollX(double p);
static void setScrollY(double p);
protected:
const static unsigned char Controller::FPS; // FPS of this game (ONLY RELEASE MODE CAN RUN SMOOTHLY AT 170FPS MAX)
const static unsigned int Controller::frameTime; // time for each frame
/********************* Core *********************/
/** Init **/
void InitCurrentView();
void InitCurrentModel();
void InitControls();
/** Switching models **/
void SwitchModels(); //for update changing models, like main menu to game
/* Call only when needed: if your program needs key and mouse press */
void UpdateKeys();
void UpdateMouse();
void UpdateKeyPressed(); //if a key is pressed, update this function
static Vector2 GetCursor(GLFWwindow* const window); //call to get cursor pos
/********************** Input **********************/
MODE type; //mode
/********************** model and view ptr **********************/
Model* currentModel; //points to the current model to run
View* currentView; //points to the current vuew to run
/********************** Models **********************/
Model_Gameplay* Gameplay;
Model_Level_Editor* Level_Editor;
Model_MainMenu* mainMenu;
/********************** Views **********************/
View_Main_Menu* view_MainMenu;
View_Level_Editor* view_LevelEditor;
View_3D_Game* view_3D_Game;
/********************** Declare a window object **********************/
StopWatch m_timer;
double m_dElapsedTime;
double m_dAccumulatedTime_thread1;
double m_dAccumulatedTime_thread2;
/********************** FPS **********************/
float fps;
/********************** Keyboard **********************/
static bool myKeys[TOTAL_CONTROLS]; //all keys
static char inputChar[OPEN]; //for char keys
static vector<char> typableCharacters; //char keys that are valid text inputs
/********************** mouse **********************/
static int mouseRightButton;
static int mouseLeftButton;
/********************** mouse scroll **********************/
static double scrollxPos;
static double scrollyPos;
/********************** cursor **********************/
static Vector2 cursorPos;
};
#endif<file_sep>#ifndef VIEW_MAIN_MENU_H
#define VIEW_MAIN_MENU_H
#include "View.h"
//Include GLEW
#include <GL/glew.h>
//Include GLFW
#include <GLFW/glfw3.h>
/**
Everything in view class will be using Objects class for TRS and other info
**/
class View_Main_Menu : public View
{
/********************** model and view ptr **********************/
Model_MainMenu* model;
public:
/********************** constructor/destructor *****************************/
View_Main_Menu();
View_Main_Menu(Model_MainMenu* model, unsigned short console_width, unsigned short console_height, MODE mode);
~View_Main_Menu();
/********************** Core functions *****************************/
virtual void Init();
virtual void Render(const float fps);
virtual void Exit();
/**************** render ****************/
void RenderObject();
void RenderCollideBox();
void RenderHUD();
/**************** Utilites ******************/
void SetModel(Model_MainMenu* model);
};
#endif<file_sep>#include "Object.h"
#include "View.h"
/***** constructor / destructor *****/
Object::Object()
{
}
Object::~Object()
{
}
/****** core ******/
void Object::Set(string name, Mesh* mesh, Object* parent)
{
entity.Set(mesh, parent->getEntity());
collided = false;
this->parent = parent;
}
void Object::Init()
{
if(parent != NULL)
{
entity.transformWithParent(); //TRS transform with parent
}
/* OP bound box */
collideBox.Set(entity.getPosition(), entity.getScale(), Collision::BOX);
}
void Object::Draw()
{
if( entity.getActive() )
{
View::RenderMesh(*entity.getTRS(), entity.getMesh(), false);
}
}
/***** transformation *****/
void Object::scaleObject(float x, float y, float z)
{
entity.scaleObject(x, y, z);
}
void Object::scaleObject(float all)
{
entity.scaleObject(all);
}
void Object::translateObject(float x, float y, float z)
{
entity.translateObject(x, y, z);
}
void Object::translateObject(Vector3 pos)
{
entity.translateObject(pos);
}
void Object::rotateObject(float angle, float xAxis, float yAxis, float zAxis)
{
entity.rotateObject(angle, xAxis, yAxis, zAxis);
}
void Object::translate(const Vector3& pos)
{
entity.translate(pos);
}
void Object::translate(float x, float y, float z)
{
entity.translate(x, y, z);
}
/******** OP Collision ********/
void Object::StartChecking(const Vector3& velocity)
{
/* Set up collision checking */
collideBox.Start(entity.getPosition(), velocity);
collided = false; //set as no collision yet
}
bool Object::checkCollision(Object& checkMe)
{
bool b = false;
//THIS object's collideBox, check object collideBox
b = Collision::CheckCollision(this->collideBox, checkMe.collideBox);
if(!collided)
collided = b;
return b;
}
void Object::Response(const Vector3& vel)
{
/* 2D response: nvr check for Z */
//this->collideBox.position = this->collideBox.previousPos + finalVel;
entity.translate(this->collideBox.position);
}
/*** getters ***/
Mesh* Object::getMesh(){return entity.getMesh();}
Vector3 Object::getScale(){return entity.getScale();}
Collision* Object::getBbox(){return &collideBox;}
Vector3 Object::getPosition(){return entity.getPosition();}
Mtx44* Object::getTRS(){return entity.getTRS();}
void Object::setActive(bool b){entity.setActive(b);}
bool Object::getActive(){return entity.getActive();}
AdvancedEntity* Object::getEntity(){return &entity;}<file_sep>#ifndef SUPER_OBJECT_H
#define SUPER_OBJECT_H
#include "Object.h"
#include <vector>
#include <string>
using namespace std;
/***********************************************************
Class Super Object: contains multiple objects
param:
objectList: vector of objects
mainPos: main position
***********************************************************/
class SuperObject
{
public:
/*** modifyable data ***/
vector<Object*> objectList;
Vector3 mainPos;
public:
/*** constructor / destructor ***/
SuperObject();
virtual ~SuperObject();
/*** core ***/
void Set(string name);
virtual void Init();
virtual void Draw();
/*** getters setter ***/
Vector3 getMainPos();
};
#endif<file_sep>#include "FontData.h"
void getFontData(char* name, float* fontData)
{
ifstream myfile(name);
string sentence;
int multiplier = 1; //for conversion from string to numerical
float data = 0; //width data
float ImageWidth = 64;
/* error check */
try
{
if(!myfile.is_open())
throw "Font File cannot be found: good luck noobshit";
if(fontData == NULL)
throw "What kind of shit you passing in??";
}
catch(string n)
{
cout << n << endl;
}
/* search for string begining with: Char */
int counter = 0; //counts to 255
while(getline(myfile, sentence) && counter < 256)
{
if(searchTerm(sentence, "Base Width"))
{
/* get the width */
//.......Base Width,26
for(int i = sentence.length() - 1; i > 0; --i)
{
/* convert to numerical data */
if(sentence[i] != ',')
{
data += (sentence[i] - 48) * multiplier;
multiplier *= 10;
}
else
{
fontData[counter] = data / ImageWidth;
break; //reach comma, go on to find next char width
}
}
multiplier = 1;
data = 0;
++counter;
}
}
}<file_sep>#ifndef LAYER_H
#define LAYER_H
#include "Character.h"
#include "MeshList.h"
#include "readFrom.h"
#include "writeTo.h"
/*****************************************************************/
/*
Layer class. Contains map of tiles. Each tile contains just X and Y pos in map.
To be translated into actual pos in render. X * tileSize and Y * tilesize.
Position NOT determined by index in vector.
*/
/*****************************************************************/
class Layer
{
public:
/* Constructor/destructor */
Layer();
~Layer();
/* Re-Create */
void Set(Geometry::TILE_MAP tileMap, int layer, bool collidable, float tileScale);
void RecreateLayer(Geometry::TILE_MAP tileMap, int totalX, int totalY); //clears all tiles and reset again, only way to change tileMap
bool LoadTileLayer(string& txt); //update from txt
/* Editing */
//if is existing tile, will edit that existing tile instead
void editTile(int& x, int& y, int TileType);
bool WriteToTxt(string& txt); //update to txt
void Clear(); //free memory
/* Collision */
bool checkCollision(Character* character);
/* Getter/setter */
Geometry::TILE_MAP getTileMap();
void setLayer(int layer);
int getLayer();
void SetCollidable(bool c);
bool getCollidable();
void SetTileScale(float s);
float getTileScale();
private:
/* Info for map */
int layer; //what layer is it
float tileScale; //tile scale for this layer
bool collidable; //this layer can collide or not
bool edited; //is it edited?
/* Tile stuff */
vector< vector<int> > TileMap;
/* tileMap */
Geometry::TILE_MAP tileMap; //what tilemap
static Collision collisionBox; //Shared collision box
};
#endif<file_sep>#include "Model_MainMenu.h"
#include "Model_MainMenu.h"
#include "GL\glew.h"
#include "shader.hpp"
#include "MeshBuilder.h"
#include "Controller.h"
#include "Utility.h"
#include "LoadTGA.h"
#include "LoadHmap.h"
#include "SpriteAnimation.h"
#include <sstream>
/*********** constructor/destructor ***************/
Model_MainMenu::Model_MainMenu()
{
}
Model_MainMenu::~Model_MainMenu()
{
}
/*********** core functions ***************/
void Model_MainMenu::Init()
{
Model::Init();
/* Init local already? */
if( initLocalAlready ) //yes, init alr
return;
initLocalAlready = true; //no, then first time init
}
void Model_MainMenu::InitObject()
{
}
void Model_MainMenu::Update(double dt, bool* myKeys)
{
/* model update */
Model::Update(dt, myKeys);
}
void Model_MainMenu::NewStateSetup()
{
}
void Model_MainMenu::OldStateExit()
{
}
void Model_MainMenu::Exit()
{
Model::Exit();
}<file_sep>#ifndef CHARACTER_H
#define CHARACTER_H
#include "Object.h"
#include "Weapon.h"
#include "SpriteAnimation.h"
/*******************************************************/
/*
Character class for all living things. Only for 2D.
*/
/*******************************************************/
class Character
{
public:
/* Character can only go 8 diff. directions */
enum DIRECTION
{
N, //north
S, //south
E, //east (RIGHT)
W, //west (LEFT)
N_E,
N_W,
s_E,
S_W,
TOTAL_DIRECTIONS,
};
/* Constructor/destructor */
Character();
~Character();
/* Core */
void Init(Vector3 pos, Vector3 scale, DIRECTION facingDir);
void Update(double dt);
/* Getter/Setter */
Vector3 getPosition();
Vector3 getScale();
Mesh* getMesh();
Object* getObject();
protected:
/* Physical */
Object object;
/* Directions */
DIRECTION facingDir;
/* Sprite */
SpriteAnimation* sprite;
SpriteData directionSprites[TOTAL_DIRECTIONS];
/* Physics */
Vector3 vel;
};
#endif<file_sep>#include "GameObject.h"
#include "Controller.h"
#include "MeshList.h"
#include "LoadTGA.h"
int GameObject::objCount = 0;
/*********************************** constructor/destructor ***********************************/
GameObject::GameObject(void)
{
objCount++;
SpriteName = "";
SpriteCol = NULL;
SpriteRow = NULL;
Sprite_texture_file_path = "";
invisible = false;
}
GameObject::GameObject(Mesh* mesh, Vector3 Pos, Vector3 scale, bool active)
{
/* set object */
Set("", mesh, NULL, false, false);
translateObject(Pos.x, Pos.y, Pos.z);
scaleObject(scale.x, scale.y, scale.z);
this->active = active; //render
/* set boundbox */
collideBound.Set(Pos, scale, Collision::BOX);
}
/*********************************** core ***********************************/
void GameObject::Update()
{
}
/*********************************** getter/setter ***********************************/
//active
void GameObject::setIsActive(bool isActive)
{
Object::setActive(isActive);
}
bool GameObject::getisActive()
{
return Object::getActive();
}
//type
void GameObject::setType(GO_TYPE Type)
{
this->Type = Type;
}
int GameObject::getType()
{
return Type;
}
//object count (static)
int GameObject::getObjCount()
{
return objCount;
}
//return physics variables
Physics GameObject::getInfo()
{
return info;
}
//dir
Vector3 GameObject::getDir()
{
return Vector3(1, 0, 0);
}
//angle
void GameObject::setAngle(float angle)
{
angleZ = angle;
Object::rotateObject(angle, 0, 0, 1);
}
float GameObject::getAngle()
{
return angleZ;
}
//mesh
void GameObject::setMesh(Mesh* mesh)
{
Object::setMesh(mesh);
}
Mesh* GameObject::getMesh()
{
return Object::getMesh();
}
//scale
Vector3 GameObject::getScale()
{
return Object::getScale();
}
//pos
Vector3 GameObject::getPosition()
{
return Object::getPosition();
}
float GameObject::getSpeed()
{
return info.getSpeed();
}
void GameObject::setSpeed(float speed)
{
info.setSpeed(speed);
}
Collision* GameObject::getCollideBound()
{
return &collideBound;
}
/*********************************** utilities ***********************************/
void GameObject::StartCollisionCheck()
{
collided = false;
collideBound.Start(position);
}
bool GameObject::CollisionCheck(GameObject* checkWithMe)
{
bool b = false;
b = Collision::CheckCollision(this->collideBound, checkWithMe->collideBound);
if(!collided)
collided = b;
return b;
}
void GameObject::CollisionResponse()
{
if(collided)
{
translate(collideBound.position);
}
}
void GameObject::storeSpriteAnimation(std::string name, unsigned int numRow, unsigned int numCol, const char * texture_file_path)
{
this->SpriteName = name;
this->SpriteRow = numRow;
this->SpriteCol = numCol;
this->Sprite_texture_file_path = texture_file_path;
}
SpriteAnimation* GameObject::generateSpriteMesh()
{
SpriteAnimation *sa;
sa = dynamic_cast<SpriteAnimation*>(MeshBuilder::GenerateSpriteAnimation(SpriteName, SpriteRow, SpriteCol, 1.f));
sa->textureID[0] = LoadTGA(Sprite_texture_file_path);
return sa;
}
void GameObject::processSpriteAnimation(int state, float time, int startCol, int startRow, int endCol, int endRow, int repeatCount, bool oppDir)
{
//SpriteAnimation *sa;
//sa = dynamic_cast<SpriteAnimation*>(MeshBuilder::GenerateSpriteAnimation(name, numRow, numCol, 1.f));
//sa->textureID[0] = LoadTGA(texture_path);
SpriteAnimation *temp;
temp = generateSpriteMesh();
if(temp->name == "" || temp->textureID[0] == 0)
{
cout << "Sprite empty" << endl;
delete temp;
return;
}
temp->init(time, startCol, startRow, endCol, endRow, repeatCount, oppDir);
animationList[state] = temp;
}
void GameObject::Translate(Vector3 pos)
{
translate(pos);
}
void GameObject::TranslateOffset(Vector3 offset)
{
translateObject(offset);
}
GameObject::~GameObject(void)
{
objCount--;
for(int i = 0; i < animationList.size(); ++i)
{
delete animationList[i];
}
}
<file_sep>#ifndef LOAD_HMAP_H
#define LOAD_HMAP_H
#include "Vector3.h"
#include <vector>
bool LoadHeightMap(const char *file_path, std::vector<unsigned char> &heightMap);
float ReadHeightMap(std::vector<unsigned char> &heightMap, float x, float z);
float GetYFromHeightMap(std::vector<unsigned char> &heightMap, Vector3& mapScale, float x, float z, float objectScaleY);
#endif<file_sep>#ifndef VIEW_H
#define VIEW_H
/* Model */
#include "Model_Gameplay.h"
#include "Model_Level_Editor.h"
#include "Model_MainMenu.h"
//Include GLEW
#include <GL/glew.h>
//Include GLFW
#include <GLFW/glfw3.h>
/*************************************************************/
/*
Contains:
Model pointer to point to current model to render
Function:
Render and object if active.
Custom render specific stuff dictated by the model
*/
/*************************************************************/
class View
{
private:
/********************** openGL *********************************/
static GLFWwindow* m_window_view;
/********************** Window screen size *****************************/
//dimension on computer screen
static unsigned short m_screen_width;
static unsigned short m_screen_height;
/********************** model and view ptr **********************/
Model* model;
public:
/********************** Light *****************************/
const static unsigned short m_total_lights = 2;
/********************* Uniform parameters ***********************/
enum UNIFORM_TYPE
{
U_MVP = 0,
U_MODELVIEW,
U_MODELVIEW_INVERSE_TRANSPOSE,
/* material */
U_MATERIAL_AMBIENT,
U_MATERIAL_DIFFUSE,
U_MATERIAL_SPECULAR,
U_MATERIAL_SHININESS,
/* light */
U_LIGHTENABLED,
U_NUMLIGHTS,
U_LIGHT0_TYPE,
U_LIGHT0_POSITION,
U_LIGHT0_COLOR,
U_LIGHT0_POWER,
U_LIGHT0_KC,
U_LIGHT0_KL,
U_LIGHT0_KQ,
U_LIGHT0_SPOTDIRECTION,
U_LIGHT0_COSCUTOFF,
U_LIGHT0_COSINNER,
U_LIGHT0_EXPONENT,
U_LIGHT1_TYPE,
U_LIGHT1_POSITION,
U_LIGHT1_COLOR,
U_LIGHT1_POWER,
U_LIGHT1_KC,
U_LIGHT1_KL,
U_LIGHT1_KQ,
U_LIGHT1_SPOTDIRECTION,
U_LIGHT1_COSCUTOFF,
U_LIGHT1_COSINNER,
U_LIGHT1_EXPONENT,
/* texture */
U_COLOR_TEXTURE_ENABLED, //multitexture: texture enabled
U_COLOR_TEXTURE_ENABLED_1,
U_COLOR_TEXTURE, //multitexture: color enabled
U_COLOR_TEXTURE_1,
/* TEXT */
U_TEXT_ENABLED,
U_TEXT_COLOR,
/* FOG */
U_FOG_COLOR,
U_FOG_START,
U_FOG_END,
U_FOG_DENSITY,
U_FOG_TYPE,
U_FOG_ENABLED,
U_TOTAL,
};
enum MODE
{
TWO_D,
THREE_D,
};
enum FONT_DATA
{
TOTAL_FONT_TYPE,
};
/********************** constructor/destructor *****************************/
View();
View(Model* model, unsigned short console_width, unsigned short console_height, MODE mode);
~View();
/********************** Core functions *****************************/
virtual void Init() = 0;
void InitLight();
void InitFontData();
virtual void InitProjection();
virtual void Render(const float fps) = 0;
virtual void Exit();
/**************** render utilities ****************/
/* Light */
void RenderLight();
/* 3D */
static void RenderMesh(Mesh *mesh, bool enableLight);
static void RenderMeshInLines(Mesh* mesh, const Vector3& position, const Vector3& scale);
/* External loading of matrix */
static void RenderMesh(Mtx44& TRS, Mesh* mesh, bool light); //includes push and pop and render
/* 2D */
static void RenderMeshIn2D(Mesh *mesh, bool enableLight, float sizex=1.0f, float sizey = 1.0f, float x=0.0f, float y=0.0f, float z = 0.f, float angle = 0.f);
static void Render2DTile(Mesh *mesh, bool enableLight, float size, float x, float y, float z, int tileType);
static void RenderMeshIn2D(Mesh *mesh, bool enableLight, Mtx44& TRS);
/* Text */
//3D
static void RenderText(Mesh* mesh, std::string text, Color color);
//2D
//render text with cutoff: add slash to part where supposed to go to next line
static void RenderTextOnScreenCutOff(Mesh* mesh, std::string text, Color color, float size, float x, float y, float z = 1.f);
static void RenderTextOnScreenStart0(Mesh* mesh, std::string text, Color color, float size, float x, float y, float z = 1.f);
static void RenderTextOnScreen(Mesh* mesh, std::string text, Color color, float size, float x, float y, float z = 1.f);
/* General */
void RenderObject(Object* o);
void RenderUI(UI_Object* u);
/********************** Getter/setter *****************************/
static unsigned short getScreenHeight();
static unsigned short getScreenWidth();
Model* getModel();
void SetModel(Model* model);
static GLFWwindow* getWindow_view();
/********************** openGL *********************************/
static GLFWwindow* getWindow();
/********************** text **********************/
static float FontData[256];
protected:
/**************** set up initstuff, call this FIRST at Init(); ****************/
void StartInit();
/**************** set up projection, Call this FIRST at Render(); ****************/
void StartRendering(const float fps);
/************* mode *****************/
MODE mode;
/************* matrix *****************/
static MS modelStack;
static MS viewStack;
static MS projectionStack;
/************* lights *****************/
static Light lights[m_total_lights]; //for model, use the lights provided in view
/********************** openGL *********************************/
static unsigned m_vertexArrayID;
static unsigned m_programID;
static unsigned m_parameters[U_TOTAL];
static float fps;
/********************** Flags **********************/
static bool InitAlready;
};
#endif<file_sep>#pragma once
#include <ostream>
#include "Vector3.h"
#include <vector>
using namespace std;
class Collision
{
public:
enum TYPE
{
BOX,
SPHERE,
SLANTED_BOX,
};
/* Core */
//initialize
void Set(Vector3 pos, Vector3 scale, TYPE type);
void SetForTile(int xPos, int yPos, float tileScale);
//runtime
void Start(const Vector3& objectPos, const Vector3& velocity); //before checking must set up
void Reset();
/* Check if collide: */
//pass in current object's collide box and collide box of object being compared
static bool CheckCollision(Collision& current, Collision& check);
//1) current type: Sphere --- Check type: Sphere
//3) current type: Sphere --- Check type: Slanted Box
//4) current type: Sphere --- Check type: Box
//2) current type: Box --- Check type: Box
/* Sphere (current) to Sphere (check) */
static bool SphereToSphere(Collision* current, Collision* check);
/* Sphere (current) to Slanted Box (check) */
static bool SphereToSlantedBox(Collision* current, Collision* check);
/* Sphere (current) to Box (check) */
static bool SphereToBox(Collision* current, Collision* check);
/* Box To Box Swept AABB method */
static bool SlideResponse(Collision* current, Collision* check);
static float SweptAABB(Collision& current, Collision& check);
/* Collision response */
//for respone, set object pos to collision pos
Collision();
~Collision();
TYPE type;
/* Variables for all collision type */
Vector3 position; //bottom left
Vector3 scale; //if is Sphere, scale.set(radius, radius, radius);
static Vector3 normal; //swept AABB (If not using, remove)
//!! optimise so not using vel and normal, just one variable (or better, none)
Vector3 vel;
/** Free Use **/
static bool QuickAABBDetection2D(Vector3& currentStart, Vector3& currentEnd, Vector3& checkStart, Vector3& checkEnd);
static void setStartEnd2D(const Vector3& pos, const Vector3& scale, Vector3& start, Vector3& end);
private:
/*** Temporary storage variables ***/
/* AABB Collision */
static Vector3 startingPos; //startingPos
static Vector3 currentStart; //current collide bound
static Vector3 currentEnd;
static Vector3 previousStart; //current collide bound @ previous frame
static Vector3 previousEnd;
static Vector3 currentPos; //current position
/* Broad phrasing */
static Vector3 startZone, endZone; //for broad phrasing (or whatever its called)
static Vector3 checkStart, checkEnd; //start and end for box
static float offset; //cannot be 0 (or will considered collision even if touching)
static Vector3 slideDist; //slide dist for sliding AABB
static float remainingTime;
static vector<Collision*> slideList;
static vector<Collision*>::iterator it;
static Collision* collided_Box;
static bool xc, yc, zc;
/** internal functions please ignore (DO NOT CALL FROM OUTSIDE CLASS) **/
/* AABB Collision */
static bool broadPhrase(Vector3 originalPos, Vector3 finalPos, Vector3 checkPos, Vector3 currentScale, Vector3 checkScale);
static bool inZone(float start, float end, float checkStart, float checkEnd);
static bool checkAABBCollide(Vector3& currentStart, Vector3& currentEnd, Vector3& checkStart, Vector3& checkEnd);
static bool checkSideCollide(Vector3& currentStart, Vector3& currentEnd, Vector3& checkStart, Vector3& checkEnd, bool x, bool y, bool z);
bool checkSlide(Vector3& normal);
void ResetAABB();
static bool CheckAndResponse(bool x, bool y, bool z, Collision& current, vector<Collision*>& checkList);
};<file_sep>#include "ComplexObject.h"
#include "View.h"
/*** constructor / destructor ***/
ComplexObject::ComplexObject()
{
}
ComplexObject::~ComplexObject()
{
}
/*** core ***/
void ComplexObject::Set(string name)
{
}
void ComplexObject::Init()
{
}
void ComplexObject::Draw()
{
}
/*** getters setter ***/
Vector3 ComplexObject::getMainPos()
{
return mainPos;
}<file_sep>#ifndef AMMO_H
#define AMMO_H
#include "Object.h"
#include "MeshList.h"
class Ammo : public Object
{
public:
enum AMMO_TYPE
{
PISTOL,
UZI,
SHOTGUN,
GRENADE,
TOTAL,
};
/* Fixed vel */
const static float PISTOL_SPEED;
const static float UZI_SPEED;
const static float SHOTGUN_SPEED;
const static float GRENADE_SPEED;
/* physics */
const static float GRENADE_DECELERATION;
/* constructor/destructor */
Ammo();
~Ammo();
/* core */
void Init(AMMO_TYPE type);
//pass in the relavant info variables and they will be updated
void Update(vector<Object*>& objectList);
void Activate(const Vector3& pos, const Vector3& dir);
private:
AMMO_TYPE type;
Vector3 vel;
/* Utilities */
static bool collide;
static Object* collidedObject;
};
#endif<file_sep>#ifndef GAME_OBJECT_H
#define GAME_OBJECT_H
#include "Object.h"
#include "Physics.h"
#include "MeshList.h"
#include "SpriteAnimation.h"
#include <map>
#include "MyMath.h"
class GameObject : public Object
{
protected:
std::string SpriteName;
unsigned int SpriteCol;
unsigned int SpriteRow;
const char * Sprite_texture_file_path;
public:
/* object type */
enum GO_TYPE
{
GO_START,
GO_FURNITURE,
GO_ITEM,
GO_TILE,
GO_PLAYER,
GO_ENEMY,
GO_CAMERA,
GO_LASER,
GO_DOOR,
GO_COIN,
GO_TOTAL,
};
/* constructor/destructor */
GameObject(void);
GameObject(Mesh* mesh, Vector3 Pos, Vector3 scale, bool active); //set everything in general
virtual ~GameObject(void);
/* Core */
virtual void Update();
void setInfo(float Speed); //Set physics info only
Physics getInfo();
/* getter/setter */
void setIsActive(bool isActive);
bool getisActive();
Vector3 getPosition();
Vector3 getScale();
void setType(GO_TYPE Type);
int getType();
void setMesh(Mesh* mesh);
Mesh* getMesh();
/* !! angle is only rotating along z axis */
void setAngle(float angle);
float getAngle();
float getSpeed();
void setSpeed(float speed);
Vector3 getDir();
Collision* getCollideBound();
/* utilities */
void Translate(Vector3 pos);
void TranslateOffset(Vector3 offset);
virtual void StartCollisionCheck(); //set-up collision bound for checking
virtual bool CollisionCheck(GameObject* checkWithMe); //collision check
virtual void CollisionResponse();
//Stores the values for the sprite sheet so the class can use it later on
virtual void storeSpriteAnimation(std::string name, unsigned int numRow, unsigned int numCol, const char * texture_file_path);
//Creates a line of sprite and adds it to the state
virtual void processSpriteAnimation(int state, float time, int startCol, int startRow, int endCol, int endRow, int repeatCount, bool oppDir = false);
static int getObjCount();
bool getInvisible(){return invisible;} //(ONLY FOR PLAYER)
protected:
//invisible? (ONLY FOR PLAYER)
bool invisible;
GO_TYPE Type; //type
Physics info; // Physics related info
Collision collideBound; //collision box
float angleZ; //angle rotate on z axis (z faces outwards from screen)
bool collided;
static int objCount;
std::map<int, SpriteAnimation*> animationList;
virtual SpriteAnimation* generateSpriteMesh();
};
#endif
<file_sep>#ifndef MODEL_GAMEPLAY_H
#define MODEL_GAMEPLAY_H
#include "Model.h"
class Model_Gameplay : public Model
{
Player player; //set multiplayer
public:
/*********** constructor/destructor ***************/
Model_Gameplay();
~Model_Gameplay();
/*********** core functions ***************/
virtual void Init();
void InitObject();
virtual void NewStateSetup();
virtual void OldStateExit();
virtual void Update(double dt, bool* myKeys);
virtual void Exit();
};
#endif<file_sep>//#include "BoundBox.h"
//using std::cin;
//using std::cout;
//using std::endl;
//
///* constructor destructor */
//BoundBox::BoundBox()
//{
//}
//
//BoundBox::~BoundBox()
//{
//}
//
///* Core */
///* core */
//void BoundBox::Set(const Vector3& objectPos, Vector3 scale)
//{
// /* public access variables */
// scale = scale;
//
// /* internal variables */
// position = objectPos;
// previousPos = position;
// start = position - (this->scale * 0.5f);
// end = position + (this->scale * 0.5f);
// previousStart = previousPos - (this->scale * 0.5f);
// previousEnd = previousPos + (this->scale * 0.5f);
//
// /* flags */
// collideArea.Reset();
// total = 0;
//}
//
//void BoundBox::Update(const Vector3& objectPos)
//{
// position = objectPos;
// /* update start and end */
// start = position - (this->scale * 0.5f);
// end = position + (this->scale * 0.5f);
//}
//
//void BoundBox::UpdateCollide(CollideBox* check, Vector3& pos, Movement_3d& collidePart)
//{
// /* check collide */
// /* check collision first */
//
// if(collidePart.collideSide == Movement_3d::start_X)
// {
// pos.x = previousPos.x;
// }
// else if(collidePart.collideSide == Movement_3d::end_X)
// {
// pos.x = previousPos.x;
// }
//
// //y
// else if(collidePart.collideSide == Movement_3d::start_Y)
// {
// pos.y = previousPos.y;
// }
// else if(collidePart.collideSide == Movement_3d::end_Y)
// {
// pos.y = previousPos.y;
// }
//
// //z
// else if(collidePart.collideSide == Movement_3d::start_Z)
// {
// pos.z = previousPos.z;
// }
// else if(collidePart.collideSide == Movement_3d::end_Z)
// {
// pos.z = previousPos.z;
// }
//}
//
///** check if bound box <start to end> is in another BoundBox_3D's zone **/
//bool inZone(float& start, float& end, float& checkStart, float& checkEnd)
//{
// return (end > checkStart && start < checkEnd);
//}
//
//void getCollide(float& start, float& end, float& checkStart, float& checkEnd, Movement_3d::COLLIDE startDir, Movement_3d::COLLIDE endDir, Movement_3d::COLLIDE& collideSide)
//{
// if(start > checkEnd)
// {
// collideSide = startDir;
// }
// else if(end < checkStart)
// {
// collideSide = endDir;
// }
//}
//
//void BoundBox::CheckCollide(CollideBox* check, Vector3& position)
//{
// BoundBox* checkBox = dynamic_cast<BoundBox*>(check);
//
// ++total;
// /*********************** check direction X, Y and Z ***********************/
// inZoneY = inZone(start.y, end.y, checkBox->start.y, checkBox->end.y);
// inZoneX = inZone(start.x, end.x, checkBox->start.x, checkBox->end.x);
// inZoneZ = inZone(start.z, end.z, checkBox->start.z, checkBox->end.z);
//
// /** if collide **/
// if(inZoneY && inZoneX && inZoneZ)
// {
// inZoneY = inZone(previousStart.y, previousEnd.y, checkBox->start.y, checkBox->end.y);
// inZoneX = inZone(previousStart.x, previousEnd.x, checkBox->start.x, checkBox->end.x);
// inZoneZ = inZone(previousStart.z, previousEnd.z, checkBox->start.z, checkBox->end.z);
//
//
// ///** Y dir **/
// if(inZoneX && inZoneZ && !inZoneY)
// {
// //start/end
// getCollide(previousStart.y, previousEnd.y, checkBox->start.y, checkBox->end.y, Movement_3d::start_Y, Movement_3d::end_Y, collideArea.collideSide);
// }
//
// /** X dir **/
// else if(inZoneY && inZoneZ && !inZoneX)
// {
// //start/end
// getCollide(previousStart.x, previousEnd.x, checkBox->start.x, checkBox->end.x, Movement_3d::start_X, Movement_3d::end_X, collideArea.collideSide);
// }
//
// /** Z dir **/
// else if(inZoneY && inZoneX && !inZoneZ)
// {
// //start/end
// getCollide(previousStart.z, previousEnd.z, checkBox->start.z, checkBox->end.z, Movement_3d::start_Z, Movement_3d::end_Z, collideArea.collideSide);
// }
//
// //position = previousPos;
// UpdateCollide(checkBox, position, collideArea);
// start = position - (this->scale * 0.5f);
// end = position + (this->scale * 0.5f);
// }
//
// /** update previous **/
// if(total == 3)
// {
// previousPos = position;
// previousStart = start;
// previousEnd = end;
// }
//}
//
//void BoundBox::Reset()
//{
// total = 0;
// /*previousPos = position;
// previousStart = start;
// previousEnd = end;*/
//}
//
//
//Vector3 BoundBox::getStart(){return start;}
//Vector3 BoundBox::getEnd(){return end;}
//Vector3 BoundBox::getRadius(){return scale * 0.5;}
//Vector3 BoundBox::getScale(){return scale;}
//Movement_3d* const BoundBox::getMovement_3d(){return &collideArea;}<file_sep>#ifndef CAMERA_2D_H
#define CAMERA_2D_H
#include "Camera.h"
class Camera2D : public Camera
{
/* Deadzone size */
Vector3 DeadZone; //boundbox area
/* View screen size */
float viewWidth; //width of camera view in real world
float viewHeight; //height of camera view in real world
/* Borders of the world */
Vector3 boundStart; //boundary camera can offset
Vector3 boundEnd;
public:
Camera2D();
~Camera2D();
void Init(const Vector3& pos, const Vector3& target, const Vector3& up, float DeadZone_Width, float DeadZone_Height, float viewWidth, float viewHeight, float xMapScale, float yMapScale);
void SetBound(const Vector3& currentPos);
void Update(double dt, const Vector3& currentPos, const Vector3& scale);
virtual void Reset();
};
#endif<file_sep>#ifndef WEAPON_H
#define WEAPON_H
#include "Ammo.h"
class Weapon
{
public:
enum WEAPON_TYPE
{
PISTOL,
UZI,
SHOTGUN,
GRENADE,
TOTAL,
};
/* max ammo */
const static int MAX_PISTOL = 50;
const static int MAX_UZI = 50;
const static int MAX_SHOTGUN = 50;
const static int MAX_GRENADE = 20;
/* constructor/destructor */
Weapon();
~Weapon();
/* core */
void Init(WEAPON_TYPE type);
static void InitAmmo(vector<Object*>& objectList); //call this once in Init to update all active ammo
//pass in the relavant info variables and they will be updated
bool Update(double dt, const Vector3& currentPos, Vector3& direction, bool fireWeapon);
static void UpdateAmmos(vector<Object*>& objectList); //call this once in Update to update all active ammo
Ammo* FetchAmmo(); //get ammo: Gurantee have ammo
private:
/* Global */
static vector<Ammo*> ammoList;
/* Local */
WEAPON_TYPE type;
int ammo;
double fireRate;
double fireTimer;
};
#endif<file_sep>#include "Controller_3D_Game.h"
//Include the standard C++ headers
#include <stdio.h>
#include <stdlib.h>
/**/
/*
Controller for 2D Game. If first time come to a model, no matter in init or update function,
will always init then. So if never even went to edit function, edit model will not even be init.
*/
/**/
/********************* constructor / destructor *********************/
Controller_3D_Game::Controller_3D_Game()
{
}
Controller_3D_Game::~Controller_3D_Game()
{
}
/******************** core functions **********************/
void Controller_3D_Game::Init()
{
}
void Controller_3D_Game::Run()
{
}
void Controller_3D_Game::SwitchModels()
{
}
void Controller_3D_Game::Exit()
{
}
<file_sep>#include "Model_Gameplay.h"
#include "GL\glew.h"
#include "shader.hpp"
#include "MeshBuilder.h"
#include "Controller.h"
#include "Utility.h"
#include "LoadTGA.h"
#include "LoadHmap.h"
#include "SpriteAnimation.h"
#include <sstream>
/*********** constructor/destructor ***************/
Model_Gameplay::Model_Gameplay()
{
}
Model_Gameplay::~Model_Gameplay()
{
}
/*********** core functions ***************/
void Model_Gameplay::Init()
{
/*** Stuff that need to always re-init here ***/
/*** Only init once stuff below here ***/
Model::Init();
/* Init local already? */
if( initLocalAlready ) //yes, init alr
return;
initLocalAlready = true; //no, then first time init
//light
lightPos[0].Set(1000.f, 500.f, 0.f);
lightPos[1].Set(0.f, 800.f, 0.f);
//weapon
//Weapon::InitAmmo(elementObject);
//object
InitObject();
//player: last so will alpha all walls
player.Init(Vector3(800, 800, 1), Vector3(230, 230, 1), Character::E, 100, 100, 350);
elementObject.push_back(player.getObject());
/* Init all game objects */
for(std::vector<Object*>::iterator it = elementObject.begin(); it != elementObject.end(); ++it)
{
Object *go = (Object *)*it;
go->Init();
}
}
void Model_Gameplay::InitObject()
{
/** Default pos : 0, 0, 0
Default scale: 1, 1, 1
m_view_width = 2400.f;
m_view_height = 1600.f;
**/
Object* obj_ptr;
/* WALL 1 */
//for now Z will be 100 as z collision check not removed yet
//top
obj_ptr = new Object;
obj_ptr->Set("character", Geometry::meshList[Geometry::GEO_CUBE_BLUE], NULL);
//RIGHT
obj_ptr->translateObject(2200, 750, -1.f); //start at right side of box (going top left initially)
obj_ptr->scaleObject(12, 1600, 100);
elementObject.push_back(obj_ptr);
/* WALL 2 */
obj_ptr = new Object;
obj_ptr->Set("character", Geometry::meshList[Geometry::GEO_CUBE_BLUE], NULL);
//TOP
obj_ptr->translateObject(m_view_width * 0.5f, 1500, -1.f); //start at right side of box (going top left initially)
obj_ptr->scaleObject(2000, 12, 100);
elementObject.push_back(obj_ptr);
/* WALL 3 */
obj_ptr = new Object;
obj_ptr->Set("character", Geometry::meshList[Geometry::GEO_CUBE_BLUE], NULL);
//LEFT
obj_ptr->translateObject(200, 750, -1.f); //start at right side of box (going top left initially)
obj_ptr->scaleObject(12, 1600, 100);
elementObject.push_back(obj_ptr);
/* WALL 4 */
obj_ptr = new Object;
obj_ptr->Set("character", Geometry::meshList[Geometry::GEO_CUBE_BLUE], NULL);
//BOTTOM
obj_ptr->translateObject(m_view_width * 0.5f, 50, -1.f); //start at right side of box (going top left initially)
obj_ptr->scaleObject(2000, 12, 100);
elementObject.push_back(obj_ptr);
/* WALL 5 */
obj_ptr = new Object;
obj_ptr->Set("character", Geometry::meshList[Geometry::GEO_CUBE_GREEN], NULL);
//BOTTOM
obj_ptr->translateObject(696.40192, 1222.2026, -1.f); //start at right side of box (going top left initially)
obj_ptr->scaleObject(12, 250, 50);
elementObject.push_back(obj_ptr);
/* WALL 6 */
obj_ptr = new Object;
obj_ptr->Set("character", Geometry::meshList[Geometry::GEO_CUBE_GREEN], NULL);
//BOTTOM
obj_ptr->translateObject(849.0, 1222.2026, -1.f); //start at right side of box (going top left initially)
obj_ptr->scaleObject(12, 250, 50);
elementObject.push_back(obj_ptr);
}
void Model_Gameplay::Update(double dt, bool* myKeys)
{
/* Switch state */
if( myKeys[SHOOT] )
{
switchState = true;
currentState = EDIT_LEVEL;
}
/* model update */
Model::Update(dt, myKeys);
/* Update player */
player.Update(dt, myKeys, elementObject);
/* Update Ammo */
//Weapon::UpdateAmmos(elementObject);
}
void Model_Gameplay::NewStateSetup()
{
}
void Model_Gameplay::OldStateExit()
{
}
void Model_Gameplay::Exit()
{
Model::Exit();
}<file_sep>#include "utilities.h"
//client: string to be compared, matchee: string used to match
bool c, m;
bool searchTerm(string client, string matchee)
{
c = client.length();
m = matchee.length();
if( !c && !m ) return true;
if( !c || !m ) return false;
for(int j = 0; j < client.length(); ++j)
{
bool c= true;
if(matchee[0] == client[j])
{
if(matchee.length() < 2 || (matchee.length() == 1 && j == client.length() - 1))
return true;
if(client.length() - (j + 1) >= matchee.length() - 1)
{
int index = 1;
for(int i = j + 1; i < client.length(); ++i, ++index)
{
if(client[i] != matchee[index])
{
c = false;
break; //continue search
}
if(index == matchee.length() - 1)
return true;
}
if(c == true)
return true;
}
else
return false;
}
else if(j == client.length() - 1)
return false;
}
return false;
}
void deleteChar(string& word, char del)
{
int lastChar = 0;
bool c = false;
for(int i = 0; i < word.length(); ++i)
{
if(word[i] == del)
{
if(c == false)
{
c = true;
lastChar = i;
}
}
else
c = false;
}
if(c == true)
word.resize(lastChar);
}
int stringToInt(string& num)
{
int numm = 0;
int j = 1;
for(int i = num.length() - 1; i >= 0; --i, j *= 10)
{
numm += (num[i] - 48) * j;
}
return numm;
}
int getNumberFromRange(string& original)
{
bool start = false;
string returnVal = "";
for(int i = 0; i < original.length(); ++i)
{
if( original[i] >= '0' && original[i] <= '9' )
{
start = true;
returnVal += original[i];
}
else
{
if( start )
break; //reach end of number
}
}
return stringToInt(returnVal);
}
int getNumberFromRange(string& original, int skip)
{
bool start = false;
string returnVal = "";
for(int i = 0; i < original.length(); ++i)
{
if( original[i] >= '0' && original[i] <= '9' )
{
start = true;
returnVal += original[i];
}
else
{
if( start )
{
if( skip == 0 )
break;
else
{
returnVal = "";
--skip;
}
}
}
}
return stringToInt(returnVal);
}<file_sep>#ifndef MESHLIST_H
#define MESHLIST_H
#include "Mesh.h"
#include "MeshBuilder.h"
#include "DepthFBO.h"
#include "GL\glew.h"
#include "shader.hpp"
#include "Utility.h"
#include "LoadOBJ.h"
#include "LoadHmap.h"
#include "LoadTGA.h"
#include <vector>
using std::vector;
/**/
/*
Tile map class. Contains mesh as well as total tiles.
*/
/**/
struct TileMap
{
Mesh* mesh;
Mesh* previewMesh;
string name;
int totalTiles;
float tileScale;
};
class Geometry
{
public:
enum TILE_MAP
{
TILEMAP_NATURE,
TILEMAP_MARKET,
TOTAL_TILEMAP,
};
enum GEOMETRY_TYPE
{
/* basic ABC */
GEO_AXES,
GEO_DEBUG_CUBE,
GEO_LIGHTBALL,
GEO_SPHERE,
GEO_QUAD,
GEO_CUBE,
GEO_CUBE_BLUE,
GEO_CUBE_RED,
GEO_CUBE_GREEN,
GEO_RING,
GEO_CONE,
/* sky boxxxxxxxxxxx */
GEO_LEFT,
GEO_RIGHT,
GEO_TOP,
GEO_BOTTOM,
GEO_FRONT,
GEO_BACK,
/* UI */
GEO_AR_CHRISTY, //font
GEO_CROSSHAIR,
GEO_SELECTOR,
/* terrain */
GEO_SKYPLANE,
GEO_TERRAIN,
GEO_ICE_RINK,
/* animation */
GEO_GIRL,
GEO_RUNNING_CAT,
/* world objects */
GEO_BUILDING,
GEO_OBJECT,
GEO_PAVEMENT,
GEO_SIGNBOARD,
GEO_LAMPPOST,
GEO_SNOWFLAKE,
/* police car */
GEO_CAR_MAIN_PART,
GEO_CAR_GLASS,
GEO_CAR_SIREN,
/* building */
GEO_DERELICT_BUILDING_01,
NUM_GEOMETRY,
};
/************ meshlsit ************/
static Mesh* meshList[NUM_GEOMETRY]; //dynamic array for Mesh*
/************ animation ************/
static vector<SpriteAnimation*> animation;
/************ terrain ************/
static vector<unsigned char> m_heightMap;
/************ TileMap ************/
static TileMap tileMap_List[TOTAL_TILEMAP];
/* core */
static void Init(); //MUST BE CALLED ONCE: ANYWHERE
static void Exit();
};
#endif<file_sep>#ifndef PHYSICS_H
#define PHYSICS_H
#include "Vector3.h"
#include <iostream>
using namespace std;
/**/
/*
Physics stuff and associated variables.
!!Position and scale are not physics!!
DO NOT SET ACCELERATION TOO HIGH as frame movement have limitations
*/
/**/
struct Physics
{
public:
enum MOVEMENT_STATE
{
SET_DIR,
ACCELERATE,
DECELERATE,
CONSTANT,
} movement_state;
float remainingDist;
Vector3 dir;
float vel;
float acceleration;
/* Constructor/destructor */
Physics();
~Physics();
/* Core */
void Set(float acceleration);
/* Movement */
//returns true if reached
bool Move(Vector3& pos, const float& max_speed, const Vector3& destination, double dt);
bool shouldDecelerate( const Vector3& pos, const Vector3& destination);
};
#endif<file_sep>#include "Player.h"
int Player::total_players = 1;
Player::Player()
{
}
Player::~Player()
{
}
/* Core */
void Player::Init(Vector3 pos, Vector3 scale, DIRECTION facingDir, float health, float staminia, float speed)
{
/* Weapon */
weapon.Init(Weapon::PISTOL);
/* Mesh */
//sprite animation
sprite = MeshBuilder::GenerateSpriteAnimation("zombie", 8, 8, 1);
sprite->textureID[0] = LoadTGA("Image//boxhead_zombie.tga");
//start col, start row, end col, end row
sprite->init(0.1f, 0, 4, 7, 4, false);
/* Character */
object.Set("character", sprite, NULL);
object.translateObject(pos); //start at right side of box (going top left initially)
object.scaleObject(scale.x, scale.y, scale.z);
/* Stats */
this->health = health;
this->staminia = staminia;
this->speed = speed;
}
void Player::SetToNewMap(Vector3 pos, Map& currentMap)
{
object.translateObject(pos);
}
double changeRate = 0.05;
double timer = changeRate;
double changeDirRate = 0.2;
double changeDirTimer = changeDirRate;
int countchange = 0;
bool dirc = false;
void Player::Update(double dt, bool* myKeys, vector<Object*>& objectLists)
{
/* Character update */
Character::Update(dt);
/* Controls */
//dir
if( changeDirTimer < changeDirRate )
changeDirTimer += dt;
else
{
//if( myKeys[ SHOOT ] )
{
changeDirTimer = 0.0;
dirc = !dirc;
}
}
//keys
if( timer < changeRate )
timer += dt;
else
{
timer = 0.0;
( dirc ) ? ++countchange : --countchange;
if( dirc && countchange > 3 )
countchange = 0;
else if( !dirc && countchange < 0 )
countchange = 3;
}
//myKeys[FORWARD] = myKeys[BACKWARD] = myKeys[LEFT] = myKeys[RIGHT] = false;
//switch( countchange )
//{
//case 0: //top right
// myKeys[FORWARD] = myKeys[RIGHT] = true;
// break;
//case 1: //top left
// myKeys[FORWARD] = myKeys[LEFT] = true;
// break;
//case 2: //bottom left
// myKeys[BACKWARD] = myKeys[LEFT] = true;
// break;
//case 3: //bottom right
// myKeys[BACKWARD] = myKeys[RIGHT] = true;
// break;
//}
//
vel.SetZero();
if( myKeys[FORWARD] )
{
vel.y += speed;
}
if( myKeys[BACKWARD] )
{
vel.y -= speed;
}
if( myKeys[LEFT] )
{
vel.x -= speed;
}
if( myKeys[RIGHT] )
{
vel.x += speed;
}
/* Movement and collision check */
vel *= dt;
/*translate(800, 800, 1);
vel.Set(-500, 500, 0);*/
/* Set up collision */
object.StartChecking(vel);
for(int i = 0; i < objectLists.size(); ++i)
{
if(&object != objectLists[i])
{
if(objectLists[i]->getActive())
object.checkCollision(*objectLists[i]);
}
}
/* Reset */
object.collideBox.Reset();
/* collision response */
object.Response(vel);
/* Shoot weapon */
//Vector3 dir(0, 1, 0);
//Vector3 pos = object.position;
//pos.y += object.scale.y * 2;
//weapon.Update(dt, pos, dir, myKeys[RELOAD]);
}
<file_sep>#include "View.h"
//Include the standard C++ headers
#include <stdio.h>
#include <stdlib.h>
#include "GL\glew.h"
#include "shader.hpp"
#include "MeshBuilder.h"
#include "Utility.h"
#include "LoadTGA.h"
#include "LoadHmap.h"
#include "SpriteAnimation.h"
#include "Controller.h"
#include "FontData.h"
#include <sstream>
//openGL
GLFWwindow* View:: m_window_view;
unsigned short View::m_screen_width;
unsigned short View::m_screen_height;
float View::FontData[256];
bool View::InitAlready = false;
/************* matrix *****************/
MS View::modelStack;
MS View::viewStack;
MS View::projectionStack;
/************* lights *****************/
Light View::lights[m_total_lights]; //for model, use the lights provided in view
/********************** openGL *********************************/
unsigned View::m_vertexArrayID;
unsigned View::m_programID;
unsigned View::m_parameters[View::U_TOTAL];
float View::fps;
/* Utilities */
float lengthOffset = 0;
float len = 0;
float zOffset = 0;
float textLength = 0;
float textXLength = 0;
//Define an error callback
static void error_callback_view(int error, const char* description)
{
fputs(description, stderr);
_fgetchar();
}
//Define the key input callback
static void key_callback_view(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
}
void resize_callback_view(GLFWwindow* window, int w, int h)
{
glViewport(0, 0, w, h);
}
View::View() : model(NULL)
{
}
View::View(Model* model, unsigned short screen_width, unsigned short screen_height, MODE mode) : model(model), mode(mode)
{
m_screen_width = screen_width;
m_screen_height = screen_height;
}
View::~View()
{
}
/********************** Getter/setter *****************************/
unsigned short View::getScreenHeight(){return m_screen_height;}
unsigned short View::getScreenWidth(){return m_screen_width;}
Model* View::getModel()
{
return model;
}
void View::SetModel(Model* model)
{
this->model = model;
}
/********************** Core functions *****************************/
void View::StartInit()
{
/** No need init so many times */
if( InitAlready )
return;
InitAlready = true;
//Set the error callback
glfwSetErrorCallback(error_callback_view);
//Initialize GLFW
if (!glfwInit())
{
exit(EXIT_FAILURE);
}
//Set the GLFW window creation hints - these are optional
glfwWindowHint(GLFW_SAMPLES, 4); //Request 4x antialiasing
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //Request a specific OpenGL version
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //Request a specific OpenGL version
//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL
//Create a window and create its OpenGL context
m_window_view = glfwCreateWindow(m_screen_width, m_screen_height, "LALALALALLA", NULL, NULL);
//If the window couldn't be created
if (!m_window_view)
{
fprintf( stderr, "Failed to open GLFW window.\n" );
glfwTerminate();
exit(EXIT_FAILURE);
}
//This function makes the context of the specified window current on the calling thread.
glfwMakeContextCurrent(m_window_view);
//Sets the key callback
//glfwSetKeyCallback(m_window, key_callback);
glfwSetWindowSizeCallback(m_window_view, resize_callback_view);
glewExperimental = true; // Needed for core profile
//Initialize GLEW
GLenum err = glewInit();
//If GLEW hasn't initialized
if (err != GLEW_OK)
{
fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
//return -1;
}
/************* openGL stuff ****************/
// Black background
glClearColor(72.f / 255.f, 240.f / 255.f, 125.f / 255.f, 0.0f);
// Enable depth test
glEnable(GL_DEPTH_TEST);
// Accept fragment if it closer to the camera than the former one
glDepthFunc(GL_LESS);
glEnable(GL_CULL_FACE);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//alpha
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glGenVertexArrays(1, &m_vertexArrayID);
glBindVertexArray(m_vertexArrayID);
/********************************* shader and stuff *********************************/
m_programID = LoadShaders( "Shader//fog.vertexshader", "Shader//fog.fragmentshader" );
// Get a handle for our uniform
m_parameters[U_MVP] = glGetUniformLocation(m_programID, "MVP");
//m_parameters[U_MODEL] = glGetUniformLocation(m_programID, "M");
//m_parameters[U_VIEW] = glGetUniformLocation(m_programID, "V");
m_parameters[U_MODELVIEW] = glGetUniformLocation(m_programID, "MV");
m_parameters[U_MODELVIEW_INVERSE_TRANSPOSE] = glGetUniformLocation(m_programID, "MV_inverse_transpose");
m_parameters[U_MATERIAL_AMBIENT] = glGetUniformLocation(m_programID, "material.kAmbient");
m_parameters[U_MATERIAL_DIFFUSE] = glGetUniformLocation(m_programID, "material.kDiffuse");
m_parameters[U_MATERIAL_SPECULAR] = glGetUniformLocation(m_programID, "material.kSpecular");
m_parameters[U_MATERIAL_SHININESS] = glGetUniformLocation(m_programID, "material.kShininess");
m_parameters[U_LIGHTENABLED] = glGetUniformLocation(m_programID, "lightEnabled");
m_parameters[U_NUMLIGHTS] = glGetUniformLocation(m_programID, "numLights");
m_parameters[U_LIGHT0_TYPE] = glGetUniformLocation(m_programID, "lights[0].type");
m_parameters[U_LIGHT0_POSITION] = glGetUniformLocation(m_programID, "lights[0].position_cameraspace");
m_parameters[U_LIGHT0_COLOR] = glGetUniformLocation(m_programID, "lights[0].color");
m_parameters[U_LIGHT0_POWER] = glGetUniformLocation(m_programID, "lights[0].power");
m_parameters[U_LIGHT0_KC] = glGetUniformLocation(m_programID, "lights[0].kC");
m_parameters[U_LIGHT0_KL] = glGetUniformLocation(m_programID, "lights[0].kL");
m_parameters[U_LIGHT0_KQ] = glGetUniformLocation(m_programID, "lights[0].kQ");
m_parameters[U_LIGHT0_SPOTDIRECTION] = glGetUniformLocation(m_programID, "lights[0].spotDirection");
m_parameters[U_LIGHT0_COSCUTOFF] = glGetUniformLocation(m_programID, "lights[0].cosCutoff");
m_parameters[U_LIGHT0_COSINNER] = glGetUniformLocation(m_programID, "lights[0].cosInner");
m_parameters[U_LIGHT0_EXPONENT] = glGetUniformLocation(m_programID, "lights[0].exponent");
m_parameters[U_LIGHT1_TYPE] = glGetUniformLocation(m_programID, "lights[1].type");
m_parameters[U_LIGHT1_POSITION] = glGetUniformLocation(m_programID, "lights[1].position_cameraspace");
m_parameters[U_LIGHT1_COLOR] = glGetUniformLocation(m_programID, "lights[1].color");
m_parameters[U_LIGHT1_POWER] = glGetUniformLocation(m_programID, "lights[1].power");
m_parameters[U_LIGHT1_KC] = glGetUniformLocation(m_programID, "lights[1].kC");
m_parameters[U_LIGHT1_KL] = glGetUniformLocation(m_programID, "lights[1].kL");
m_parameters[U_LIGHT1_KQ] = glGetUniformLocation(m_programID, "lights[1].kQ");
m_parameters[U_LIGHT1_SPOTDIRECTION] = glGetUniformLocation(m_programID, "lights[1].spotDirection");
m_parameters[U_LIGHT1_COSCUTOFF] = glGetUniformLocation(m_programID, "lights[1].cosCutoff");
m_parameters[U_LIGHT1_COSINNER] = glGetUniformLocation(m_programID, "lights[1].cosInner");
m_parameters[U_LIGHT1_EXPONENT] = glGetUniformLocation(m_programID, "lights[1].exponent");
// Get a handle for our "colorTexture" uniform
m_parameters[U_COLOR_TEXTURE_ENABLED] = glGetUniformLocation(m_programID, "colorTextureEnabled[0]");
m_parameters[U_COLOR_TEXTURE_ENABLED_1] = glGetUniformLocation(m_programID, "colorTextureEnabled[1]");
m_parameters[U_COLOR_TEXTURE] = glGetUniformLocation(m_programID, "colorTexture[0]");
m_parameters[U_COLOR_TEXTURE_1] = glGetUniformLocation(m_programID, "colorTexture[1]");
// Get a handle for our "textColor" uniform
m_parameters[U_TEXT_ENABLED] = glGetUniformLocation(m_programID, "textEnabled");
m_parameters[U_TEXT_COLOR] = glGetUniformLocation(m_programID, "textColor");
//fog
m_parameters[U_FOG_COLOR] = glGetUniformLocation(m_programID, "fogParam.color");
m_parameters[U_FOG_START] = glGetUniformLocation(m_programID, "fogParam.start");
m_parameters[U_FOG_END] = glGetUniformLocation(m_programID, "fogParam.end");
m_parameters[U_FOG_DENSITY] = glGetUniformLocation(m_programID, "fogParam.density");
m_parameters[U_FOG_TYPE] = glGetUniformLocation(m_programID, "fogParam.type");
m_parameters[U_FOG_ENABLED] = glGetUniformLocation(m_programID, "fogParam.enabled");
glUniform1i(m_parameters[U_TEXT_ENABLED], 0);
// Use our shader
glUseProgram(m_programID);
InitFontData();
InitLight();
InitProjection();
/**************************** fog ****************************/
Color color = Color(196.f / 255.f, 196.f / 255.f, 196.f / 255.f);
int fogStart = 200;
int fogEnd = 1000;
float fogDensity = 0.0005f;
int fogType = 2;
bool fogEnable = false;
glUniform3fv(m_parameters[U_FOG_COLOR], 1, &color.r);
glUniform1f(m_parameters[U_FOG_START], fogStart);
glUniform1f(m_parameters[U_FOG_END], fogEnd);
glUniform1f(m_parameters[U_FOG_DENSITY], fogDensity);
glUniform1f(m_parameters[U_FOG_ENABLED], fogEnable);
glUniform1i(m_parameters[U_FOG_TYPE], fogType);
glUniform1i(m_parameters[U_FOG_ENABLED], 1);
}
void View::InitProjection()
{
// Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 1000 unit
Mtx44 perspective;
perspective.SetToPerspective(45.0f, m_screen_width * (1 / m_screen_height), 1.f, 12000.0f);
//perspective.SetToOrtho(-80, 80, -60, 60, -1000, 1000);
projectionStack.LoadMatrix(perspective);
}
void View::InitFontData()
{
getFontData("Image//ar_christy.csv", FontData);
}
void View::InitLight()
{
/** SET POS IN MODEL **/
lights[0].type = Light::LIGHT_DIRECTIONAL;
//lights[0].position.Set(0.f, 1008.f, 0.f);
lights[0].color.Set(1, 1, 1);
lights[0].power = 1.f;
//lights[0].kC = 1.f;
//lights[0].kL = 0.01f;
//lights[0].kQ = 0.001f;
//lights[0].cosCutoff = cos(Math::DegreeToRadian(45)); //cut off the lights spot after this degree
//lights[0].cosInner = cos(Math::DegreeToRadian(30));
//lights[0].exponent = 3.f;
////lights[0].spotDirection.Set(0.f, -1.f, 0.f);
lights[1].type = Light::LIGHT_POINT;
//lights[1].position.Set(0.f, 1008.f, 0.f);
lights[1].color.Set(1, 1, 1);
lights[1].power = 100.f;
lights[1].kC = 1.f;
lights[1].kL = 0.01f;
lights[1].kQ = 0.001f;
lights[1].cosCutoff = cos(Math::DegreeToRadian(45)); //cut off the lights spot after this degree
lights[1].cosInner = cos(Math::DegreeToRadian(30));
lights[1].exponent = 3.f;
lights[1].spotDirection.Set(0.f, -1.f, 0.f);
glUniform1i(m_parameters[U_NUMLIGHTS], m_total_lights); //2 lights
/* pass in uniform parameters for lightsource */
glUniform3fv(m_parameters[U_LIGHT0_COLOR], 1, &lights[0].color.r);
glUniform1f(m_parameters[U_LIGHT0_POWER], lights[0].power);
glUniform1f(m_parameters[U_LIGHT0_KC], lights[0].kC);
glUniform1f(m_parameters[U_LIGHT0_KL], lights[0].kL);
glUniform1f(m_parameters[U_LIGHT0_KQ], lights[0].kQ);
glUniform1f(m_parameters[U_LIGHT0_COSCUTOFF], lights[0].cosCutoff);
glUniform1f(m_parameters[U_LIGHT0_COSINNER], lights[0].cosInner);
glUniform1f(m_parameters[U_LIGHT0_EXPONENT], lights[0].exponent);
glUniform3fv(m_parameters[U_LIGHT1_COLOR], 1, &lights[1].color.r);
glUniform1f(m_parameters[U_LIGHT1_POWER], lights[1].power);
glUniform1f(m_parameters[U_LIGHT1_KC], lights[1].kC);
glUniform1f(m_parameters[U_LIGHT1_KL], lights[1].kL);
glUniform1f(m_parameters[U_LIGHT1_KQ], lights[1].kQ);
glUniform1f(m_parameters[U_LIGHT1_COSCUTOFF], lights[1].cosCutoff);
glUniform1f(m_parameters[U_LIGHT1_COSINNER], lights[1].cosInner);
glUniform1f(m_parameters[U_LIGHT1_EXPONENT], lights[1].exponent);
}
void View::StartRendering(const float fps)
{
/* initialize render */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
Mtx44 perspective;
/** 3D **/
if(mode == THREE_D)
perspective.SetToPerspective(45, m_screen_width * (1.f / m_screen_height), 0.1f, 14000.0f);
/** 2D **/
else
perspective.SetToOrtho(0, Model::getViewWidth(), 0, Model::getViewHeight(), -100, 100);
projectionStack.LoadMatrix(perspective);
viewStack.LoadIdentity();
viewStack.LookAt(
model->getCamera()->position.x, model->getCamera()->position.y, model->getCamera()->position.z,
model->getCamera()->target.x, model->getCamera()->target.y, model->getCamera()->target.z,
model->getCamera()->up.x, model->getCamera()->up.y, model->getCamera()->up.z
);
// Model matrix : an identity matrix (model will be at the origin)
modelStack.LoadIdentity();
this->fps = fps;
}
/* Utilities */
void View::RenderObject(Object* o)
{
o->Draw();
}
void View::RenderUI(UI_Object* u)
{
u->Draw();
}
void View::Exit()
{
// Cleanup VBO
glDeleteProgram(m_programID);
glDeleteVertexArrays(1, &m_vertexArrayID);
//Close OpenGL window and terminate GLFW
glfwDestroyWindow(m_window_view);
//Finalize and clean up GLFW
glfwTerminate();
}
/********************** openGL *********************************/
GLFWwindow* View::getWindow()
{
return m_window_view;
}
/**************** render ****************/
void View::RenderText(Mesh* mesh, std::string text, Color color)
{
if(!mesh || mesh->textureID <= 0)
return;
glUniform1i(m_parameters[U_TEXT_ENABLED], 1);
glUniform3fv(m_parameters[U_TEXT_COLOR], 1, &color.r);
glUniform1i(m_parameters[U_LIGHTENABLED], 0);
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED], 1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh->textureID[0]);
glUniform1i(m_parameters[U_COLOR_TEXTURE], 0);
for(unsigned i = 0; i < text.length(); ++i)
{
Mtx44 characterSpacing;
characterSpacing.SetToTranslation(i * 1.0f, 0, 0); //1.0f is the spacing of each character, you may change this value
Mtx44 MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top() * characterSpacing;
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE, &MVP.a[0]);
mesh->Render((unsigned)text[i] * 6, 6);
}
glBindTexture(GL_TEXTURE_2D, 0);
glUniform1i(m_parameters[U_TEXT_ENABLED], 0);
}
void View::RenderTextOnScreenStart0(Mesh* mesh, std::string text, Color color, float size, float x, float y, float z)
{
textLength = text.length();
if(!mesh || mesh->textureID[0] <= 0 || textLength == 0)
return;
glDisable(GL_DEPTH_TEST);
Mtx44 ortho;
ortho.SetToOrtho(0, Model::getViewWidth2D(), 0, Model::getViewHeight2D(), -10, 10);
projectionStack.PushMatrix();
projectionStack.LoadMatrix(ortho);
viewStack.PushMatrix();
viewStack.LoadIdentity();
modelStack.PushMatrix();
modelStack.LoadIdentity();
modelStack.Translate(x, y, z);
modelStack.Scale(size, size, size);
glUniform1i(m_parameters[U_TEXT_ENABLED], 1);
glUniform3fv(m_parameters[U_TEXT_COLOR], 1, &color.r);
glUniform1i(m_parameters[U_LIGHTENABLED], 0);
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED], 1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh->textureID[0]);
glUniform1i(m_parameters[U_COLOR_TEXTURE], 0);
/* get total scale.x of string */
lengthOffset = FontData[text[0]] * 0.5f;
for(unsigned i = 0; i < textLength; ++i)
{
Mtx44 characterSpacing;
characterSpacing.SetToTranslation(lengthOffset, 0.f, 0); //1.0f is the spacing of each character, you may change this value
Mtx44 MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top() * characterSpacing;
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE, &MVP.a[0]);
lengthOffset += FontData[text[i]];
mesh->Render((unsigned)text[i] * 6, 6);
}
lengthOffset = 0.f; //reset length
textXLength = 0.f;
glBindTexture(GL_TEXTURE_2D, 0);
glUniform1i(m_parameters[U_TEXT_ENABLED], 0);
projectionStack.PopMatrix();
viewStack.PopMatrix();
modelStack.PopMatrix();
glEnable(GL_DEPTH_TEST);
}
void View::RenderTextOnScreen(Mesh* mesh, std::string text, Color color, float size, float x, float y, float z)
{
if(!mesh || mesh->textureID[0] <= 0 || text.length() == 0)
return;
glDisable(GL_DEPTH_TEST);
Mtx44 ortho;
ortho.SetToOrtho(0, Model::getViewWidth2D(), 0, Model::getViewHeight2D(), -10, 10);
projectionStack.PushMatrix();
projectionStack.LoadMatrix(ortho);
viewStack.PushMatrix();
viewStack.LoadIdentity();
modelStack.PushMatrix();
modelStack.LoadIdentity();
modelStack.Translate(x, y, z);
modelStack.Scale(size, size, size);
glUniform1i(m_parameters[U_TEXT_ENABLED], 1);
glUniform3fv(m_parameters[U_TEXT_COLOR], 1, &color.r);
glUniform1i(m_parameters[U_LIGHTENABLED], 0);
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED], 1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh->textureID[0]);
glUniform1i(m_parameters[U_COLOR_TEXTURE], 0);
/* get total scale.x of string */
textLength = text.length();
textXLength = 0.f;
for(unsigned i = 0; i < textLength; ++i)
{
textXLength += FontData[text[i]];
}
lengthOffset = (textXLength * -0.5f) + (FontData[text[0]] * 0.5f); //make sure is start from center
for(unsigned i = 0; i < textLength; ++i)
{
Mtx44 characterSpacing;
characterSpacing.SetToTranslation(lengthOffset, 0.f, 0); //1.0f is the spacing of each character, you may change this value
Mtx44 MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top() * characterSpacing;
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE, &MVP.a[0]);
lengthOffset += FontData[text[i]];
mesh->Render((unsigned)text[i] * 6, 6);
}
lengthOffset = 0.f; //reset length
textXLength = 0.f;
glBindTexture(GL_TEXTURE_2D, 0);
glUniform1i(m_parameters[U_TEXT_ENABLED], 0);
projectionStack.PopMatrix();
viewStack.PopMatrix();
modelStack.PopMatrix();
glEnable(GL_DEPTH_TEST);
}
void View::Render2DTile(Mesh *mesh, bool enableLight, float size, float x, float y, float z, int tileType)
{
Mtx44 ortho;
ortho.SetToOrtho(0, Model::getViewWidth2D(), 0, Model::getViewHeight2D(), -10, 10);
projectionStack.PushMatrix();
projectionStack.LoadMatrix(ortho);
viewStack.PushMatrix();
viewStack.LoadIdentity();
modelStack.PushMatrix();
modelStack.LoadIdentity();
modelStack.Translate(x, y, z);
modelStack.Scale(size, size, 1);
/*if (rotate)
modelStack.Rotate(rotateAngle, 0, 0, 1);*/
Mtx44 MVP, modelView, modelView_inverse_transpose;
MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top();
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE, &MVP.a[0]);
for(int i = 0; i < 2; ++i)
{
if(mesh->textureID[i] > 0)
{
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED + i], 1);
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, mesh->textureID[i]);
glUniform1i(m_parameters[U_COLOR_TEXTURE + i], i);
}
else
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED + i], 0);
}
mesh->Render((tileType - 1) * 6, 6);
glBindTexture(GL_TEXTURE_2D, 0);
modelStack.PopMatrix();
viewStack.PopMatrix();
projectionStack.PopMatrix();
}
void View::RenderTextOnScreenCutOff(Mesh* mesh, std::string text, Color color, float size, float x, float y, float z)
{
if(!mesh || mesh->textureID[0] <= 0 || text.length() == 0)
return;
glDisable(GL_DEPTH_TEST);
Mtx44 ortho;
ortho.SetToOrtho(0, Model::getViewWidth2D(), 0, Model::getViewHeight2D(), -10, 10);
projectionStack.PushMatrix();
projectionStack.LoadMatrix(ortho);
viewStack.PushMatrix();
viewStack.LoadIdentity();
modelStack.PushMatrix();
modelStack.LoadIdentity();
modelStack.Translate(x, y, z);
modelStack.Scale(size, size, size);
glUniform1i(m_parameters[U_TEXT_ENABLED], 1);
glUniform3fv(m_parameters[U_TEXT_COLOR], 1, &color.r);
glUniform1i(m_parameters[U_LIGHTENABLED], 0);
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED], 1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh->textureID[0]);
glUniform1i(m_parameters[U_COLOR_TEXTURE], 0);
/* get total scale.x of string */
textLength = text.length();
textXLength = 0.f;
for(unsigned i = 0; i < textLength && text[i] != '/'; ++i)
{
textXLength += FontData[text[i]];
}
y = 0.f;
lengthOffset = (textXLength * -0.5f) + (FontData[text[0]] * 0.5f); //make sure is start from center
len = lengthOffset;
for(unsigned i = 0; i < textLength; ++i)
{
if(text[i] == '/' && i + 1 < textLength)
{
y -= 1.f;
len = lengthOffset;
++i;
}
Mtx44 characterSpacing;
characterSpacing.SetToTranslation(len, y, 0); //1.0f is the spacing of each character, you may change this value
Mtx44 MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top() * characterSpacing;
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE, &MVP.a[0]);
len += FontData[text[i]];
mesh->Render((unsigned)text[i] * 6, 6);
}
lengthOffset = 0.f; //reset length
textXLength = 0.f;
len = 0.f;
glBindTexture(GL_TEXTURE_2D, 0);
glUniform1i(m_parameters[U_TEXT_ENABLED], 0);
projectionStack.PopMatrix();
viewStack.PopMatrix();
modelStack.PopMatrix();
glEnable(GL_DEPTH_TEST);
}
void View::RenderLight()
{
if(lights[0].type == Light::LIGHT_DIRECTIONAL)
{
Vector3 lightDir(model->getLightPos(0).x, model->getLightPos(0).y, model->getLightPos(0).z);
Vector3 lightDirection_cameraspace = viewStack.Top() * lightDir;
glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightDirection_cameraspace.x);
}
else if(lights[0].type == Light::LIGHT_SPOT)
{
Position lightPosition_cameraspace = viewStack.Top() * model->getLightPos(0);
glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x);
Vector3 spotDirection_cameraspace = viewStack.Top() * lights[0].spotDirection;
glUniform3fv(m_parameters[U_LIGHT0_SPOTDIRECTION], 1, &spotDirection_cameraspace.x);
}
else
{
Position lightPosition_cameraspace = viewStack.Top() * model->getLightPos(0);
glUniform3fv(m_parameters[U_LIGHT0_POSITION], 1, &lightPosition_cameraspace.x);
}
if(lights[1].type == Light::LIGHT_DIRECTIONAL)
{
Vector3 lightDir(model->getLightPos(1).x, model->getLightPos(1).y, model->getLightPos(1).z);
Vector3 lightDirection_cameraspace = viewStack.Top() * lightDir;
glUniform3fv(m_parameters[U_LIGHT1_POSITION], 1, &lightDirection_cameraspace.x);
}
else if(lights[1].type == Light::LIGHT_SPOT)
{
Position lightPosition_cameraspace = viewStack.Top() * model->getLightPos(1);
glUniform3fv(m_parameters[U_LIGHT1_POSITION], 1, &lightPosition_cameraspace.x);
Vector3 spotDirection_cameraspace = viewStack.Top() * lights[1].spotDirection;
glUniform3fv(m_parameters[U_LIGHT1_SPOTDIRECTION], 1, &spotDirection_cameraspace.x);
}
else
{
Position lightPosition_cameraspace = viewStack.Top() * model->getLightPos(1);
glUniform3fv(m_parameters[U_LIGHT1_POSITION], 1, &lightPosition_cameraspace.x);
}
/** get position of lightball from model **/
modelStack.PushMatrix();
modelStack.Translate(model->getLightPos(0).x, model->getLightPos(0).y, model->getLightPos(0).z);
modelStack.Scale(9, 9, 9);
RenderMesh(Geometry::meshList[Geometry::GEO_LIGHTBALL], false);
modelStack.PopMatrix();
modelStack.PushMatrix();
modelStack.Translate(model->getLightPos(1).x, model->getLightPos(1).y, model->getLightPos(1).z);
modelStack.Scale(9, 9, 9);
RenderMesh(Geometry::meshList[Geometry::GEO_LIGHTBALL], false);
modelStack.PopMatrix();
}
void View::RenderMesh(Mesh *mesh, bool enableLight)
{
Mtx44 MVP, modelView, modelView_inverse_transpose;
MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top();
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE, &MVP.a[0]);
/* week 6 fog */
modelView = viewStack.Top() * modelStack.Top();
glUniformMatrix4fv(m_parameters[U_MODELVIEW], 1, GL_FALSE, &modelView.a[0]);
if(enableLight)
{
glUniform1i(m_parameters[U_LIGHTENABLED], 1);
modelView = viewStack.Top() * modelStack.Top();
glUniformMatrix4fv(m_parameters[U_MODELVIEW], 1, GL_FALSE, &modelView.a[0]);
modelView_inverse_transpose = modelView.GetInverse().GetTranspose();
glUniformMatrix4fv(m_parameters[U_MODELVIEW_INVERSE_TRANSPOSE], 1, GL_FALSE, &modelView.a[0]);
//load material
glUniform3fv(m_parameters[U_MATERIAL_AMBIENT], 1, &mesh->material.kAmbient.r);
glUniform3fv(m_parameters[U_MATERIAL_DIFFUSE], 1, &mesh->material.kDiffuse.r);
glUniform3fv(m_parameters[U_MATERIAL_SPECULAR], 1, &mesh->material.kSpecular.r);
glUniform1f(m_parameters[U_MATERIAL_SHININESS], mesh->material.kShininess);
}
else
{
glUniform1i(m_parameters[U_LIGHTENABLED], 0);
}
for(int i = 0; i < 2; ++i)
{
/* have more than one texture */
if(mesh->textureID[i] > 0)
{
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED + i], 1);
glActiveTexture(GL_TEXTURE0 + i);
glBindTexture(GL_TEXTURE_2D, mesh->textureID[i]);
glUniform1i(m_parameters[U_COLOR_TEXTURE + i], i);
}
else
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED + i], 0);
}
mesh->Render();
glBindTexture(GL_TEXTURE_2D, 0);
}
/* External loading of matrix */
void View::RenderMesh(Mtx44& TRS, Mesh* mesh, bool light)
{
modelStack.PushMatrix();
modelStack.LoadMatrix( TRS );
RenderMesh(mesh, light);
modelStack.PopMatrix();
}
void View::RenderMeshIn2D(Mesh *mesh, bool enableLight, float sizex, float sizey, float x, float y, float z, float angle)
{
Mtx44 ortho;
ortho.SetToOrtho(0, Model::getViewWidth2D(), 0, Model::getViewHeight2D(), -10, 10);
projectionStack.PushMatrix();
projectionStack.LoadMatrix(ortho);
viewStack.PushMatrix();
viewStack.LoadIdentity();
modelStack.PushMatrix();
modelStack.LoadIdentity();
modelStack.Translate(x, y, z);
modelStack.Rotate(angle, 0, 0, 1);
modelStack.Scale(sizex, sizey, 1);
Mtx44 MVP, modelView, modelView_inverse_transpose;
MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top();
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE,
&MVP.a[0]);
if(mesh->textureID[0] > 0)
{
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED],
1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh->textureID[0]);
glUniform1i(m_parameters[U_COLOR_TEXTURE], 0);
}
else
{
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED],
0);
}
mesh->Render();
if(mesh->textureID[0] > 0)
{
glBindTexture(GL_TEXTURE_2D, 0);
}
modelStack.PopMatrix();
viewStack.PopMatrix();
projectionStack.PopMatrix();
}
void View::RenderMeshIn2D(Mesh *mesh, bool enableLight, Mtx44& TRS)
{
Mtx44 ortho;
ortho.SetToOrtho(0, Model::getViewWidth2D(), 0, Model::getViewHeight2D(), -10, 10);
projectionStack.PushMatrix();
projectionStack.LoadMatrix(ortho);
viewStack.PushMatrix();
viewStack.LoadIdentity();
modelStack.PushMatrix();
modelStack.LoadIdentity();
modelStack.LoadMatrix(TRS);
Mtx44 MVP, modelView, modelView_inverse_transpose;
MVP = projectionStack.Top() * viewStack.Top() * modelStack.Top();
glUniformMatrix4fv(m_parameters[U_MVP], 1, GL_FALSE,
&MVP.a[0]);
if(mesh->textureID[0] > 0)
{
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED],
1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mesh->textureID[0]);
glUniform1i(m_parameters[U_COLOR_TEXTURE], 0);
}
else
{
glUniform1i(m_parameters[U_COLOR_TEXTURE_ENABLED],
0);
}
mesh->Render();
if(mesh->textureID[0] > 0)
{
glBindTexture(GL_TEXTURE_2D, 0);
}
modelStack.PopMatrix();
viewStack.PopMatrix();
projectionStack.PopMatrix();
}
GLFWwindow* View::getWindow_view()
{
return m_window_view;
}
<file_sep>#include "TileObject.h"
/* constructor/destructor */
TileObject::TileObject()
{
}
TileObject::~TileObject()
{
}
/* Core */
void TileObject::Set(Mesh* mesh, Vector3 Pos, float tileScale, TILE_TYPE tile_type)
{
/* Set object */
Object::Set("object", mesh, NULL, false, false);
translateObject(Pos); //set pos
scaleObject(tileScale, tileScale, 1); //set scale
setActive(true); //set active
/* set type */
this->tile_type = tile_type;
/* set collide box */
collideBound.Set(Pos, scale, Collision::BOX);
}
/* getter/setter */
int TileObject::getTileNum()
{
return tileNum;
}
void TileObject::setTileNum(int t)
{
tileNum = t;
}
TileObject::TILE_TYPE TileObject::getTileType()
{
return tile_type;
}
/* collision check */
bool TileObject::CollisionCheck(GameObject* checkWithMe)
{
if(this->tile_type != COLLIDABLE) //floor does not have collision
return false;
return GameObject::CollisionCheck(checkWithMe);
}
<file_sep>#ifndef PLAYER_H
#define PLAYER_H
#include "Character.h"
#include "Camera_2D.h"
#include "Map.h"
/** Put here for controller and model and character to access, got better way? **/
enum CONTROLS
{
/* using ascii table */
FORWARD, //w
BACKWARD, //s
LEFT, //a
RIGHT, //d
CROUCH, //c
RELOAD, //r
JUMP, //space bar
FLY_UP, //k
FLY_DOWN, //l
PAUSE, //p
OPEN, //o
/* using mouse/controller... */
SHOOT, //mouse left
AIM, //mouse right
TOGGLE_SPRINT, //shift
SCROLL_UP, //mouse scroll
SCROLL_DOWN, //mouse scroll
ARROW_UP,
ARROW_DOWN,
ARROW_LEFT,
ARROW_RIGHT,
TOTAL_CONTROLS,
};
class Player : public Character
{
static int total_players; //how many players
/* Basics */
float health;
float staminia;
Weapon weapon;
float speed;
Camera2D playerCam;
public:
/* constructor / destrutor */
Player();
~Player();
/* Core */
void Init(Vector3 pos, Vector3 scale, DIRECTION facingDir, float health, float staminia, float speed);
void SetToNewMap(Vector3 pos, Map& currentMap); //set player to new lvl/map
void Update(double dt, bool* myKeys, vector<Object*>& objectLists);
};
#endif<file_sep>#ifndef MAP_H
#define MAP_H
#include "Layer.h"
/*****************************************************************/
/*
Manages layers.
*/
/*****************************************************************/
class Map
{
private:
/* Layers */
vector<Layer*> layerList;
int totalLayers;
string name;
int index; //index in list
/* Utilities */
static float offset; //offset btw diff layers
static Layer* layer_ptr;
static Vector3 global_vec;
public:
/* Constructor/destructor */
Map(string name, int index);
~Map();
/* Core */
void AddLayer(bool collidable, float tileScale);
void RecreateLayer(Geometry::TILE_MAP tileMap, int layer, int totalX, int totalY); //recreate this layer
void EditLayer(int layerIndex, int tileType, int& x, int& y);
bool deleteLayer(int layerNum);
void Clear();
/* Get data */
//pass in which layer, tile index and pos variable
float getTileSize(int layerIndex);
int getLayerSize(int layerIndex); //how many tiles
int getMapSize(); //how many layers
string getName();
int getIndex();
void setIndex(int i);
};
#endif<file_sep>#ifndef TILE_H
#define TILE_H
#include "Collision.h"
/*****************************************************************/
/*
Tile object class. Contains X and Y pos
*/
/*****************************************************************/
class Tile
{
public:
/* Constructor/destructor */
Tile();
~Tile();
/* Core */
void Init(int xPos, int yPos);
bool CheckCollision(Collision& checkbox, float tileScale); //Collision box of player, NPC etc
static Collision collisionBox; //Shared collision box
int xPos, yPos; //x and y pos to
/* Utilities */
bool operator== (Tile& rhs);
};
#endif<file_sep>#include "Camera3.h"
#include "Controller.h"
#include "Mtx44.h"
/** camera pos should be based on player class **/
bool jump = false;
Vector3 velocity(0, 69, 0); //value is 0 for horizontal(X and Z) and 20 for vertical(Y ) Larger the value, further the jump
Vector3 jumpVel(velocity);
Vector3 m_gravity(0, -9.8f, 0);
float speed = 19.f;
float groundLevelY = 20.f; //store the ground level Y
static const float CAMERA_SPEED = 150.f; //use velocity from now on
static const float CAMERA_ACCELERATION = 50.f;
static const float CAMERA_MAX_VELOCITY = 200.f;
static const float CAMERA_BRAKE_OFFSET = 2.5f;
//if move mouse, acclerate till reach max speed
//if !move mouse and vel > 0, start decelerating
Camera3::Camera3()
{
}
Camera3::~Camera3()
{
}
void Camera3::Init(const Vector3& pos, const Vector3& target, const Vector3& up)
{
this->position = defaultPosition = pos;
this->target = defaultTarget = target;
Vector3 view = (target - position).Normalized();
Vector3 right = view.Cross(up);
right.y = 0;
right.Normalize();
this->up = defaultUp = right.Cross(view).Normalized();
sCameraType = LAND_CAM;
pitchMovingUp = pitchMovingDown = yawMovingLeft = yawMovingRight = false;
walkMovingForward = false; //is position still changing
walkMovingBackward = false;
straftMovingLeft = false;
straftMovingRight = false;
pitchVelocity = yawVelocity = 0.f; //used for x and z (or y if flying)
movingVelocity = false; //changing of pos
straftVelocity = 0.f;
movingVelocity = 0.f;
moveAcceleration = 600.f;
camAcceleration = 10.f;
camBrakeOffset = 2.5f;
cameraSpeed = 3.f;
yawAngle = 0.f; //facing X
croutching = false;
}
/********************************************************************************
Set Camera Type
********************************************************************************/
void Camera3::SetCameraType(CAM_TYPE sCameraType)
{
this->sCameraType = sCameraType;
}
/********************************************************************************
Get Camera Type
********************************************************************************/
Camera3::CAM_TYPE Camera3::GetCameraType(void)
{
return sCameraType;
}
/******************************************************************************
**
Walk forward or backward. You can add in a deadzone here.
*******************************************************************************
*/
void Camera3::Walk(const double dt)
{
//since -dt denotes backwards, vel is negative and -vel * -dt = positive result, so will when intent is to move back pos moves forward
//therfore dt for backward pass in -dt, to negate the (-dt) parameter
/* move forward */
if(dt > 0) //forward
{
walkMovingForward = true;
walkMovingBackward = false;
}
else
{
walkMovingBackward = true;
walkMovingForward = false;
}
/* update vel */
movingVelocity += moveAcceleration * dt;
/* cap vel */
if(movingVelocity > CAMERA_MAX_VELOCITY)
movingVelocity = CAMERA_MAX_VELOCITY;
else if(movingVelocity < -CAMERA_MAX_VELOCITY)
movingVelocity = -CAMERA_MAX_VELOCITY;
if(dt >= 0)
MoveForward(dt);
else if(dt < 0)
MoveBackward(-dt);
}
/******************************************************************************
**
Strafe left or right. You can add in a deadzone here.
*******************************************************************************
*/
void Camera3::Strafe(const double dt)
{
if(dt > 0) //right
{
straftMovingRight = true;
straftMovingLeft = false;
}
else
{
straftMovingRight = false;
straftMovingLeft = true;
}
/* update */
straftVelocity += moveAcceleration * dt;
/* cap vel */
if(straftVelocity > CAMERA_MAX_VELOCITY)
straftVelocity = CAMERA_MAX_VELOCITY;
else if(straftVelocity < -CAMERA_MAX_VELOCITY)
straftVelocity = -CAMERA_MAX_VELOCITY;
if(dt < 0)
MoveLeft(-dt);
else if(dt >= 0)
MoveRight(dt);
}
void Camera3::DecelerateBackward(const double dt) //(-dt)
{
if(movingVelocity < 0)
{
movingVelocity += -moveAcceleration * dt;
MoveBackward(-dt); //same explanation in walk()
}
else
{
movingVelocity = 0.f;
walkMovingBackward = false;
}
}
void Camera3::DecelerateForward(const double dt) //(dt)
{
if(movingVelocity > 0)
{
movingVelocity += -moveAcceleration * dt;
MoveForward(dt);
}
else
{
movingVelocity = 0.f;
walkMovingForward = false;
}
}
void Camera3::DecelerateLeft(const double dt)
{
if(straftVelocity < 0)
{
straftVelocity += -moveAcceleration * dt;
MoveLeft(-dt);
}
else
{
straftVelocity = 0.f;
straftMovingLeft = false;
}
}
void Camera3::DecelerateRight(const double dt)
{
if(straftVelocity > 0)
{
straftVelocity += -moveAcceleration * dt;
MoveRight(dt);
}
else
{
straftVelocity = 0.f;
straftMovingRight = false;
}
}
/********************************************************************************
Fly
********************************************************************************/
void Camera3::Fly(const double dt)
{
if(dt > 0)
MoveUp(dt);
else if(dt < 0)
MoveDown(dt);
}
/******************************************************************************
**
Pitch. You can add in a deadzone here. up (-) down (+)
*******************************************************************************
*/
void Camera3::Pitch(const double dt)
{
/******************** set flags *********************/
bool Up = Controller::getCameraPitch() < 0.f;
bool Down = Controller::getCameraPitch() > 0.f;
if(Up)
{
pitchMovingUp = true;
}
else if(Down)
{
pitchMovingDown = true;
}
/******************** update *************************/
if(pitchMovingUp || pitchMovingDown) //pitch < 0
pitchVelocity += -camAcceleration * Controller::getCameraPitch() * (float)dt;
/******************** cap *************************/
if(pitchVelocity > CAMERA_MAX_VELOCITY)
pitchVelocity = CAMERA_MAX_VELOCITY;
else if(pitchVelocity < -CAMERA_MAX_VELOCITY)
pitchVelocity = -CAMERA_MAX_VELOCITY;
/******************** decelerate *************************/
if(!Up && pitchMovingUp)
DecelerateUp(dt);
else if(!Down && pitchMovingDown)
DecelerateDown(dt);
if(Up)
LookUp(dt);
else if(Down)
LookDown(dt);
}
void Camera3::Yaw(const double dt)
{
/******************** set flags *********************/
bool Left = Controller::getCameraYaw() < 0.f;
bool Right = Controller::getCameraYaw() > 0.f;
if(Left)//(+vel)
{
yawMovingLeft = true;
}
else if(Right)//(-vel)
{
yawMovingRight = true;
}
/******************** update *************************/
if(yawMovingRight || yawMovingLeft)
{
yawVelocity += -camAcceleration * Controller::getCameraYaw() * (float)dt;
yawAngle += -camAcceleration * (float)dt;
}
/******************** cap *************************/
if(yawVelocity > CAMERA_MAX_VELOCITY)
yawVelocity = CAMERA_MAX_VELOCITY;
else if(yawVelocity < -CAMERA_MAX_VELOCITY)
yawVelocity = -CAMERA_MAX_VELOCITY;
/******************** decelerate *************************/
if(!Left && yawMovingLeft)
DecelerateLookLeft(dt);
else if(!Right && yawMovingRight)
DecelerateLookRight(dt);
if(Left)
LookLeft(dt);
else if(Right)
LookRight(dt);
}
void Camera3::DecelerateUp(const double dt)
{
if(pitchVelocity - (camAcceleration * camBrakeOffset * dt) > 0)
{
pitchVelocity -= camAcceleration * camBrakeOffset * dt;
LookUp(dt);
}
else
{
pitchVelocity = 0.f;
pitchMovingUp = false;
}
}
void Camera3::DecelerateDown(const double dt)
{
if(pitchVelocity + (camAcceleration * camBrakeOffset * dt) < 0)
{
pitchVelocity += camAcceleration * camBrakeOffset * dt;
LookDown(dt);
}
else
{
pitchVelocity = 0.f;
pitchMovingDown = false;
}
}
void Camera3::DecelerateLookLeft(const double dt)
{
if(yawVelocity - (camAcceleration * camBrakeOffset * dt) > 0)
{
yawVelocity -= camAcceleration * camBrakeOffset * dt;
yawAngle -= camAcceleration * camBrakeOffset * dt;
LookLeft(dt);
}
else
{
yawVelocity = 0.f;
yawMovingLeft = false;
}
}
void Camera3::DecelerateLookRight(const double dt)
{
if(yawVelocity + (camAcceleration * camBrakeOffset * dt) < 0)
{
yawVelocity += camAcceleration * camBrakeOffset * dt;
yawAngle += camAcceleration * camBrakeOffset * dt;
LookRight(dt);
}
else
{
yawVelocity = 0.f;
yawMovingRight = false;
}
}
/********************************************************************************
LookUp
********************************************************************************/
void Camera3::LookUp(const double dt)
{
float pitch = pitchVelocity;
//Controller::incrementPitchAngle(pitch);
Vector3 view = (target - position).Normalized();
Vector3 right = view.Cross(up);
right.y = 0;
right.Normalize();
up = right.Cross(view).Normalized();
Mtx44 rotation;
rotation.SetToRotation(pitch, right.x, right.y, right.z);
view = rotation * view;
target = position + view;
up = rotation * up;
}
/********************************************************************************
LookDown
********************************************************************************/
void Camera3::LookDown(const double dt)
{
float pitch = pitchVelocity;
//Controller::incrementPitchAngle(pitch);
Vector3 view = (target - position).Normalized();
Vector3 right = view.Cross(up);
right.y = 0;
right.Normalize();
up = right.Cross(view).Normalized();
Mtx44 rotation;
rotation.SetToRotation(pitch, right.x, right.y, right.z);
view = rotation * view;
target = position + view;
up = rotation * up;
}
/********************************************************************************
LookLeft
********************************************************************************/
void Camera3::LookLeft(const double dt)
{
float yaw = yawVelocity;
Vector3 view = (target - position).Normalized();
Vector3 right = view.Cross(up);
right.y = 0;
right.Normalize();
up = right.Cross(view).Normalized();
Mtx44 rotation;
rotation.SetToRotation(yaw, 0, 1, 0);
view = rotation * view;
target = position + view;
up = rotation * up;
}
/********************************************************************************
LookRight
********************************************************************************/
void Camera3::LookRight(const double dt)
{
float yaw = yawVelocity;
Vector3 view = (target - position).Normalized();
Vector3 right = view.Cross(up);
right.y = 0;
right.Normalize();
up = right.Cross(view).Normalized();
Mtx44 rotation;
rotation.SetToRotation(yaw, 0, 1, 0);
view = rotation * view;
target = position + view;
up = rotation * up;
}
void Camera3::Update(double dt, bool* myKeys)
{/*
Vector3 view = (target - position).Normalized();
Vector3 right = view.Cross(up);
right.y = 0;
Inertia: instant dir change
* strafe */
if(myKeys[LEFT] && !myKeys[RIGHT])
Strafe(-dt);
else if(straftMovingLeft)
DecelerateLeft(-dt);
if(myKeys[RIGHT] && !myKeys[LEFT])
Strafe(dt);
else if(straftMovingRight)
DecelerateRight(dt);
/* walk */
if(myKeys[FORWARD] && !myKeys[BACKWARD])
Walk(dt);
else if(walkMovingForward)
DecelerateForward(dt);
if(myKeys[BACKWARD] && !myKeys[FORWARD])
Walk(-dt);
else if(walkMovingBackward)
DecelerateBackward(-dt);
if(myKeys[CROUCH] && !croutching)
croutching = true;
croutch(dt);
/* fly */
if(myKeys[FLY_UP])
Fly(dt);
if(myKeys[FLY_DOWN])
Fly(-dt);
if(myKeys[JUMP] && !jump) //com runs too fast, spacebar 2 times
setJump(dt);
/** update jump **/
if(jump)
Jump(dt);
/** mouse **/
Yaw(dt);
Pitch(dt);
}
/******************************************************************************
Move the camera forward
******************************************************************************/
void Camera3::MoveForward(const double dt)
{
Vector3 tmp_target(target.x, 0, target.z);
Vector3 tmp_pos(position.x, 0, position.z);
Vector3 view = (tmp_target - tmp_pos).Normalized();
position += view * movingVelocity * (float)dt;
target += view * movingVelocity * (float)dt;
//reset flag
//myKeys[key] = false;
}
/******************************************************************************
Move the camera backward
******************************************************************************/
void Camera3::MoveBackward(const double dt)
{
Vector3 tmp_target(target.x, 0, target.z);
Vector3 tmp_pos(position.x, 0, position.z);
Vector3 view = (tmp_target - tmp_pos).Normalized();
position += view * movingVelocity * (float)dt;
target += view * movingVelocity * (float)dt;
//reset flag
//myKeys[key] = false;
}
/******************************************************************************
Move the camera left
******************************************************************************/
void Camera3::MoveLeft(const double dt)
{
Vector3 view = (target - position).Normalized();
Vector3 right = view.Cross(up);
right.y = 0;
right.Normalize();
position += right * straftVelocity * (float)dt;
target += right * straftVelocity * (float)dt;
//reset flag
//myKeys[key] = false;
}
/******************************************************************************
Move the camera right
******************************************************************************/
void Camera3::MoveRight(const double dt)
{
Vector3 view = (target - position).Normalized();
Vector3 right = view.Cross(up);
right.y = 0;
right.Normalize();
position += right * straftVelocity * (float)dt;
target += right * straftVelocity * (float)dt;
//reset flag
//myKeys[key] = false;
}
/******************************************************************************
Move the camera up
******************************************************************************/
void Camera3::MoveUp(const double dt)
{
Vector3 upupup(0, 1, 0);
position += upupup * CAMERA_SPEED * (float)dt;
target += upupup * CAMERA_SPEED * (float)dt;
//reset flag
//myKeys[key] = false;
}
/******************************************************************************
Move the camera down
******************************************************************************/
void Camera3::MoveDown(const double dt)
{
Vector3 upupup(0, 1, 0);
position += upupup * CAMERA_SPEED * (float)dt;
target += upupup * CAMERA_SPEED * (float)dt;
//reset flag
//myKeys[key] = false;
}
/******************************************************************************
Jump
******************************************************************************/
void Camera3::Jump(const double dt)
{
jumpVel += m_gravity * dt * speed;
position += jumpVel * dt * speed;
target += jumpVel * dt * speed;
//once reach groundw
if(position.y <= groundLevelY) //if next frame touches ground
{
target.y += groundLevelY - position.y;
position.y = groundLevelY;
jump = false;
jumpVel = velocity;
}
}
void Camera3::setJump(const double dt)
{
Vector3 view = (target - position).Normalized(); //dir of jump (if velocity X and Z are not 0)
//init velocity
jumpVel.x *= view.x;
jumpVel.z *= view.z;
jump = true;
//reset flag
//myKeys[key] = false;
}
void Camera3::TurnLeft(const double dt)
{
}
void Camera3::TurnRight(const double dt)
{
}
void Camera3::SpinClockWise(const double dt)
{
}
void Camera3::SpinCounterClockWise(const double dt)
{
}
void Camera3::Roll(const double dt)
{
}
/******************************************************************************
Update camera status
******************************************************************************/
void Camera3::UpdateStatus(const unsigned char key)
{
//myKeys[key] = true;
}
void Camera3::Reset()
{
position = defaultPosition;
target = defaultTarget;
up = defaultUp;
}
void Camera3::croutch(const double dt)
{
}
<file_sep>#include "Weapon.h"
vector<Ammo*> Weapon::ammoList;
/* constructor/destructor */
Weapon::Weapon()
{
}
Weapon::~Weapon()
{
}
/* core */
void Weapon::Init(WEAPON_TYPE type)
{
ammo = 100;
this->type = type;
fireRate = 0.1;
fireTimer = fireRate;
}
Ammo* Weapon::FetchAmmo()
{
/* get ammo */
for(int i = 0; i < ammoList.size(); ++i)
{
if( !ammoList[i]->getActive() )
{
ammoList[i]->setActive(true);
return ammoList[i];
}
}
/* create more ammo */
ammoList.resize(ammoList.size() + 10);
ammoList.back()->setActive(true); //return last one
return ammoList.back();
}
void Weapon::InitAmmo(vector<Object*>& objectList)
{
ammoList.resize(50);
for(int i = 0; i < ammoList.size(); ++i)
{
ammoList[i] = new Ammo;
ammoList[i]->Init(Ammo::PISTOL);
objectList.push_back(ammoList[i]);
}
}
bool Weapon::Update(double dt, const Vector3& currentPos, Vector3& direction, bool fireWeapon)
{
if( fireTimer < fireRate )
fireTimer += dt;
else
{
/* If fire */
if( fireWeapon )
{
if( ammo > 0 )
{
Ammo* ammo_ptr = NULL;
fireTimer = 0.0;
ammo_ptr = FetchAmmo();
ammo_ptr->Activate(currentPos, direction);
--ammo;
return true;
}
}
}
//zeo ammo
return false;
}
void Weapon::UpdateAmmos(vector<Object*>& objectList)
{
//loop thru all and update
for(int i = 0; i < ammoList.size(); ++i)
{
if( ammoList[i]->getActive() )
ammoList[i]->Update(objectList);
}
}<file_sep>#include "writeTo.h"
bool writeToFile(string& name)
{
/**
to open file:
use open function; open(filename, mode);
eg. myfile.open("dfsdf.txt", ios::in | ios::trunc)
modes:
second parameter of open function/overloaded constructor
ios::in - open for input operations (READ from file)
ios::out - open for output operations (WRITE to file)
ios::binary - open in binary mode
ios::ate - set initial position at end of file
ios::app - All output operations are performed at the end of the file, appending the content to the current content of the file.
ios::trunc - if file opened for output and already exists, previous content deleted and replaced by new one
combine modes:
use bitwise OR (|); ios::in | ios::out | ios::trunc
**/
//use C-String for address for speed: optional - convert to string
//string n(name);
ofstream myfile(name, ios::out | ios::app); //overloaded constructor to open a text file imm. after declaration
char randWords[] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '10'};
/**
everytime write to file, the original will be replaced
SO, use ios::app to set input position at endline of file, and stream adds string from there
**/
if(myfile.is_open())
{
myfile << randWords[rand() % 10] << ' ';
myfile << randWords[rand() % 10] << ' ';
myfile << randWords[rand() % 10] << "\n";
myfile.close(); //rmb to close !!
/**
close(); close file and inform OS so resources become available again.
flushes the associated buffers and close the file. Stream object (myfile) can
be reused to open another file, and the file is availble for opening by other processes
**/
}
else
return false;
return true;
}
bool writeToFile(string& name, string word)
{
ofstream myfile(name, ios::out | ios::app); //overloaded constructor to open a text file imm. after declaration
deleteChar(word, ' ');
if(myfile.is_open())
{
myfile << word + "\n";
myfile.close();
}
else
return false;
return true;
}
bool emptyFile(string& name)
{
ofstream myfile(name);
if(myfile.is_open())
{
myfile << "";
myfile.close();
}
else
return false;
return true;
}
bool deleteFromFile(string& name, int line)
{
ifstream myfile(name); //to read from txt file aka input
/** static so that sentence will always be in mem. and char pointer
to it will not be invalid **/
static string sentence = "";
const char* ptr = NULL;
if( myfile.is_open())
{
vector<string> tmp_storage; //temp. store all strings of the vector except line to be deleted
for(int i = 0; getline(myfile, sentence); ++i)
{
if(i != line - 1)
tmp_storage.push_back(sentence);
}
myfile.close();
emptyFile(name);//if line exceeds/deceeds eof, nothing is deleted
ofstream writeBack(name, ios::out | ios::app); //writeback to file aka output set cursor to end
//write back to file
if(writeBack.is_open())
{
for(int i = 0; i < tmp_storage.size(); ++i)
writeBack << tmp_storage[i] + '\n';
writeBack.close();
}
else
return false;
return true;
}
else
cout << "Error: File not found" << endl;
return false; //return true is in if(myfile.is_open()){}
}<file_sep>#include "Entity.h"
#include "View.h"
/***** constructor / destructor *****/
Entity::Entity()
{
/*** modifyable data ***/
mesh = NULL; //mesh to render (need?)
scale.SetZero(); //scale
position.SetZero(); //pos
active = false; //active?
}
Entity::~Entity()
{
}
/****** core ******/
void Entity::Set(Mesh* mesh, Vector3 scale, Vector3 position, bool active)
{
/* set individual variables */
this->mesh = mesh;
this->scale = scale;
this->position = position;
this->active = active;
}
void Entity::Draw()
{
}
/***** transformation *****/
void Entity::TranslateObject(float x, float y, float z)
{
position.x += x;
position.y += y;
position.z += z;
}
void Entity::TranslateObject(Vector3 pos)
{
TranslateObject(pos.x, pos.y, pos.z);
}
void Entity::ScaleObject(float x, float y, float z)
{
scale.x += x;
scale.y += y;
scale.z += z;
}
void Entity::ScaleObject(Vector3 scale)
{
ScaleObject(scale.x, scale.y, scale.z);
}
void Entity::RotateObject(float x, float y, float z)
{
angle.x += x;
angle.y += y;
angle.z += z;
if( angle.x < 0.f )
angle.x = 360 + angle.x;
else if( angle.x > 360.f )
angle.x -= 360.f;
if( angle.y < 0.f )
angle.y = 360 + angle.x;
else if( angle.y > 360.f )
angle.y -= 360.f;
if( angle.z < 0.f )
angle.z = 360 + angle.x;
else if( angle.z > 360.f )
angle.z -= 360.f;
}
void Entity::Translate(float x, float y, float z)
{
position.Set(x, y, z);
}
void Entity::Translate(Vector3 pos)
{
position = pos;
}
void Entity::Scale(float x, float y, float z)
{
scale.Set(x, y, z);
}
void Entity::Scale(Vector3 scale)
{
this->scale = scale;
}
void Entity::Rotate(float x, float y, float z)
{
angle.Set(x, y, z);
if( angle.x < 0.f )
angle.x = 360 + angle.x;
else if( angle.x > 360.f )
angle.x -= 360.f;
if( angle.y < 0.f )
angle.y = 360 + angle.x;
else if( angle.y > 360.f )
angle.y -= 360.f;
if( angle.z < 0.f )
angle.z = 360 + angle.x;
else if( angle.z > 360.f )
angle.z -= 360.f;
}
/*** getters ***/
Vector3 Entity::getScale(){return scale;}
Vector3 Entity::getPosition(){return position;}
void Entity::setActive(bool b){active = b;}
bool Entity::getActive(){return active;}<file_sep>#ifndef COMPLEX_OBJECT_H
#define COMPLEX_OBJECT_H
#include "Entity.h"
#include "Collision.h"
#include <vector>
#include <string>
using namespace std;
/***********************************************************
Class Complex Object: contains multiple entities and multiple collision boxes
param:
entityList: vector of entity
collisionList: vector of collision
mainPos: main position
***********************************************************/
class ComplexObject
{
public:
/*** modifyable data ***/
vector<Entity*> entityList;
vector<Collision*> collisionList;
Vector3 mainPos;
public:
/*** constructor / destructor ***/
ComplexObject();
virtual ~ComplexObject();
/*** core ***/
void Set(string name);
virtual void Init();
virtual void Draw();
/*** getters setter ***/
Vector3 getMainPos();
};
#endif<file_sep>#include "Camera_2D.h"
using namespace std;
Camera2D::Camera2D()
{
}
Camera2D::~Camera2D()
{
}
void Camera2D::Init(const Vector3& pos, const Vector3& target, const Vector3& up, float DeadZone_Width, float DeadZone_Height, float viewWidth, float viewHeight, float xMapScale, float yMapScale)
{
this->position = pos;
this->target = target;
this->target = this->target - target;
DeadZone.x = DeadZone_Width * 0.5f; //deadzone is half of the scale of the "box" area
DeadZone.y = DeadZone_Height * 0.5f;
DeadZone.z = 0;
this->viewWidth = viewWidth * 0.5f;
this->viewHeight = viewHeight * 0.5f;
Vector3 middlePos(xMapScale * 0.5f, yMapScale * 0.5f);
/* position is offset: in case not start at 0,0 */
middlePos += position * 0.5f;
if(position.y != 0)
yMapScale -= position.y;
if(position.x != 0)
xMapScale -= position.x;
/** set boundary **/
boundStart.x = middlePos.x - xMapScale * 0.5f;
boundEnd.x = middlePos.x + xMapScale * 0.5f;
boundStart.y = middlePos.y - yMapScale * 0.5f;
boundEnd.y = middlePos.y + yMapScale * 0.5f;
}
float startX, endX, startY, endY;
void Camera2D::SetBound(const Vector3& currentPos)
{
position = currentPos;
position.x -= viewWidth;
position.y -= viewHeight;
/* check if X go out of bounds at Init */
if(position.x <= boundStart.x)
{
position.x = boundStart.x;
}
else if(position.x + (viewWidth * 2.f) >= boundEnd.x)
{
position.x = boundEnd.x - (viewWidth * 2.f);
}
/* check if Y go out of bounds at Init */
if(position.y <= boundStart.y)
{
position.y = boundStart.y;
}
else if(position.y + (viewHeight * 2.f) >= boundEnd.y)
{
position.y = boundEnd.y - (viewHeight * 2.f);
}
}
void Camera2D::Update(double dt, const Vector3& currentPos, const Vector3& scale)
{
startX = position.x + (viewWidth - DeadZone.x);
endX = (position.x + viewWidth * 2.f) - (viewWidth - DeadZone.x);
startY = position.y + (viewHeight - DeadZone.y);
endY = (position.y + viewHeight * 2.f) - (viewHeight - DeadZone.y);
if( currentPos.x - scale.x * 0.5f < startX )
{
(position.x > boundStart.x) ? position.x -= startX - (currentPos.x - scale.x * 0.5f) : position.x = boundStart.x;
}
else if( currentPos.x + scale.x * 0.5f > endX )
{
(position.x + (viewWidth * 2.f) < boundEnd.x) ? position.x += (currentPos.x + scale.x * 0.5f) - endX : position.x = boundEnd.x - (viewWidth * 2.f);
}
/* check if Y go out of bounds */
if( currentPos.y - scale.y * 0.5f < startY )
{
(position.y > boundStart.y) ? position.y -= startY - (currentPos.y - scale.y * 0.5f) : position.y = boundStart.y;
}
else if( currentPos.y + scale.y * 0.5f > endY )
{
(position.y + (viewHeight * 2.f) < boundEnd.y) ? position.y += (currentPos.y + scale.y * 0.5f) - endY : position.y = boundEnd.y - (viewHeight * 2.f);
}
//target
target = position;
target.z -= 10;
}
void Camera2D::Reset()
{
}
<file_sep>#ifndef OBJECT_H
#define OBJECT_H
#include "AdvancedEntity.h"
/***********************************************************
Class Object: Physical form with collision
param:
Entity: physical form
Collision: collision box
***********************************************************/
class Object
{
public:
/*** modifyable data ***/
Object* parent;
AdvancedEntity entity;
Collision collideBox; //collision box
bool collided;
public:
/*** constructor / destructor ***/
Object();
virtual ~Object();
/*** core ***/
void Set(string name, Mesh* mesh, Object* parent);
virtual void Init();
virtual void Draw();
/*** utilities ***/
void transformWithParent(); //position recalculated after transformation
/*** transformation ***/
void scaleObject(float x, float y, float z);
void scaleObject(float all);
void translateObject(float x, float y, float z);
void translateObject(Vector3 pos);
void rotateObject(float angle, float xAxis, float yAxis, float zAxis);
void translate(const Vector3& pos);
void translate(float x, float y, float z);
/******** OP Collision ********/
void StartChecking(const Vector3& velocity);
bool checkCollision(Object& checkMe);
void Response(const Vector3& vel);
/*** getters setter ***/
Mesh* getMesh();
Vector3 getScale();
Vector3 getPosition();
Collision* getBbox();
AdvancedEntity* getEntity();
Mtx44* getTRS();
void setActive(bool b);
bool getActive();
};
#endif<file_sep>#ifndef UTILITIES_H
#define UTILITIES_H
#include <iostream>
#include <string>
using namespace std;
/* treating this as a library: utilities
for string functions like search term etc..
*/
bool searchTerm(string client, string matchee);
void deleteChar(string& word, char del);
int stringToInt(string& num);
//get the first encounter integer from this string
int getNumberFromRange(string& original);
int getNumberFromRange(string& original, int skip); //can skip over encouter how many
#endif<file_sep>#ifndef UI_OBJECT_H
#define UI_OBJECT_H
#include "Entity.h"
#include "MeshList.h"
/********************************************************/
/*
Create general UI stuff.
*/
/********************************************************/
class UI_Object : public Entity
{
protected:
string word;
static float wordScale; //percentage in regards to button scale
public:
/*** constructor / destructor ***/
UI_Object();
~UI_Object();
/*** core ***/
void Set(string word, Mesh* mesh, float scaleX, float scaleY, float posX, float posY, float zHeight, bool active);
virtual void Update(double dt);
virtual void Draw();
virtual bool CollisionDetection(UI_Object* checkMe, bool clicked);
void Init();
/* Getter setter */
void SetPosition(Vector3& pos);
Vector3 getPosition();
void SetScale(Vector3 scale);
Vector3 getScale();
bool getActive();
void SetActive(bool active);
virtual string getWord();
float getWordScale();
Mesh* getMesh();
protected:
static Vector3 start, end, checkStart, checkEnd;
};
/********************************************************/
/*
Button. Click on it will 'depress' it for a certain amount of time before
popping back up.
*/
/********************************************************/
class Button : public UI_Object
{
public:
/*** constructor / destructor ***/
Button();
~Button();
/*** core ***/
void Set(string word, Mesh* mesh, float scaleX, float scaleY, float posX, float posY, float zHeight, bool active, float depression);
virtual void Update(double dt);
virtual void Draw();
virtual bool CollisionDetection(UI_Object* checkMe, bool clicked);
/*** Getter/setter ***/
bool getClicked();
private:
static double depressionTime;
float depression;
bool clicked;
double depressionTimer;
};
/********************************************************/
/*
Button. Click on it will 'depress' it for a certain amount of time before
popping back up.
*/
/********************************************************/
class Popup : public UI_Object
{
UI_Object* quitButton;
public:
/*** constructor / destructor ***/
Popup();
~Popup();
/*** core ***/
void Set(string word, Mesh* mesh, float scaleX, float scaleY, float posX, float posY, float zHeight, bool active);
virtual void Update(double dt);
virtual void Draw();
virtual bool CollisionDetection(UI_Object* checkMe, bool clicked);
/* Getter/setter */
UI_Object* getButton();
};
/********************************************************/
/*
Selection menu. Items are displayed in square. So if you pushed in 16 meshes,
display will put them in 4 rows. Clicking on an item will select it. Hovering over it
will show a full-sized preview.
Passed in items should be part of an array.
Can only be square shape.
*/
/********************************************************/
class Selection_Menu : public UI_Object
{
vector<Mesh*> itemList;
vector<Vector3> itemPos;
int currentItem; //index of current item
Vector3 currentPos;
float itemScale;
int totalItem;
static Vector3 s; //for collision detection check
public:
/*** constructor / destructor ***/
Selection_Menu();
~Selection_Menu();
/*** core ***/
void Set(float sc, float itemScale, float posX, float posY, float zHeight, bool active);
void AddItem(Mesh* mesh);
void Init();
virtual void Update(double dt);
virtual void Draw();
virtual bool CollisionDetection(UI_Object* checkMe, bool clicked);
/*** Getter/setter ***/
int getCurrentItem();
Vector3 getItemPos(int index);
Mesh* getItemMesh(int index);
int getTotalItem();
float getItemScale();
};
/********************************************************/
/*
Textbox, type your message here.
Entering/confirming your text means that that text is registered with this textbox.
If text too long, will shift to right.
*/
/********************************************************/
class TextBox : public UI_Object
{
string returnText;
bool activated;
bool typed; //a letter has benn typed inside
static float max_wordWidth; //max word width percentage
public:
/*** constructor / destructor ***/
TextBox();
~TextBox();
/*** core ***/
void Set(Mesh* mesh, float scaleX, float scaleY, float posX, float posY, float zHeight, bool active);
virtual void Update(double dt);
virtual void Draw();
virtual bool CollisionDetection(UI_Object* checkMe, bool clicked);
/** Getter/setter **/
virtual string getWord();
float getStartPosX(); //get start pos for word X
};
#endif<file_sep>#ifndef ADVANCED_ENTITY_H
#define ADVANCED_ENTITY_H
#include "Mesh.h"
#include "MatrixStack.h"
#include "Collision.h"
#include <vector>
#include <string>
using namespace std;
/***********************************************************
Class AdvancedEntity: the physical part of a in-game object
eg. for a car type, entity is its physical form, including relevant data
param:
Mesh* mesh: mesh to render
Vector3 scale: scale factor
Vector3 position: position
BoundBox bbox: AABB box
AdvancedEntity* parent: parent object, to transform along with it like herichical modeling, NULL for no parent
Mtx44 TRS: the entire transformation matrix for this object, which is transformed along with parent if theres one
***********************************************************/
class AdvancedEntity
{
protected:
/*** modifyable data ***/
Mesh* mesh; //mesh to render (need?)
Vector3 scale; //scale
Vector3 position; //pos
AdvancedEntity* parent;
bool active; //active?
/*** NON-modifyable data ***/
Mtx44 TRS;
public:
/*** constructor / destructor ***/
AdvancedEntity();
virtual ~AdvancedEntity();
/*** core ***/
void Set(Mesh* mesh, AdvancedEntity* parent); //set basic info
void AddParent(AdvancedEntity* parent);
void FinalizeWithParent(); //finalize everything: TRS * with parent TRS
virtual void Draw(); //render the object
/*** utilities ***/
void transformWithParent(); //position recalculated after transformation
/*** transformation ***/
void scaleObject(float x, float y, float z);
void scaleObject(float all);
void translateObject(float x, float y, float z);
void translateObject(Vector3 pos);
void rotateObject(float angle, float xAxis, float yAxis, float zAxis);
void translate(const Vector3& pos);
void translate(float x, float y, float z);
/*** getters setter ***/
Mesh* getMesh();
Vector3 getScale();
Vector3 getPosition();
AdvancedEntity* getParent();
void setParent(AdvancedEntity* parent);
Mtx44* getTRS();
void setActive(bool b);
bool getActive();
};
#endif<file_sep>#ifndef CONTROLLER_3D_GAME_H
#define CONTROLLER_3D_GAME_H
#include "Controller.h"
/**************************************************
For 3D Game with mouse control
**************************************************/
class Controller_3D_Game : public Controller
{
public:
/******************** core functions **********************/
/** Init **/
void Init();
//anything special to init for view and model?
virtual void InitCurrentView();
virtual void InitCurrentModel();
void InitControls(); //all keys inputs
/** Update **/
virtual void Run();
/** Switching models **/
virtual void SwitchModels(); //for update changing models, like main menu to game
/** Exit **/
virtual void Exit();
/********************* constructor / destructor *********************/
Controller_3D_Game();
~Controller_3D_Game();
};
#endif<file_sep>#include "MeshList.h"
Mesh* Geometry::meshList[NUM_GEOMETRY];
vector<SpriteAnimation*> Geometry::animation;
vector<unsigned char> Geometry::m_heightMap;
TileMap Geometry::tileMap_List[Geometry::TOTAL_TILEMAP];
/* core */
void Geometry::Init()
{
for(int i = 0; i < NUM_GEOMETRY; ++i)
{
meshList[i] = NULL;
}
meshList[GEO_AXES] = MeshBuilder::GenerateAxes("reference", 1000, 1000, 1000);
meshList[GEO_DEBUG_CUBE] = MeshBuilder::GenerateDebugCube("Cube", Color(1, 0, 0), 1);
meshList[GEO_QUAD] = MeshBuilder::GenerateQuad("quad", Color(1, 1, 1), 1.f);
meshList[GEO_QUAD]->textureID[0] = LoadTGA("Image//calibri.tga");
meshList[GEO_AR_CHRISTY] = MeshBuilder::GenerateText("text", 16, 16);
meshList[GEO_AR_CHRISTY]->textureID[0] = LoadTGA("Image//ar_christy.tga");
meshList[GEO_RING] = MeshBuilder::GenerateRing("ring", Color(1, 0, 1), 36, 1, 1.f);
meshList[GEO_LIGHTBALL] = MeshBuilder::GenerateSphere("lightball", Color(1, 1, 1), 18, 36, 1.f);
meshList[GEO_SPHERE] = MeshBuilder::GenerateSphere("sphere", Color(1, 0, 0), 18, 36, 1.f);
meshList[GEO_CUBE] = MeshBuilder::GenerateCube("Cube", Color(179.f / 255.f, 68.f / 255.f, 9.f / 255.f), 1);
meshList[GEO_CUBE_BLUE] = MeshBuilder::GenerateCube("Cube", Color(67.f / 255.f, 153.f / 255.f, 181.f / 255.f), 1);
meshList[GEO_CUBE_RED] = MeshBuilder::GenerateCube("Cube", Color(1, 0, 0), 1);
meshList[GEO_CUBE_GREEN] = MeshBuilder::GenerateCube("Cube", Color(0, 1, 0), 1);
meshList[GEO_CONE] = MeshBuilder::GenerateCone("cone", Color(0.5f, 1, 0.3f), 36, 10.f, 1.f);
meshList[GEO_CONE]->material.kDiffuse.Set(0.99f, 0.99f, 0.99f);
meshList[GEO_CONE]->material.kSpecular.Set(0.f, 0.f, 0.f);
/** world object **/
meshList[GEO_OBJECT] = MeshBuilder::GenerateQuad("object", Color(1, 1, 1));
meshList[GEO_PAVEMENT] = MeshBuilder::GenerateOBJ("pavement", "OBJ//pavement2.obj");//MeshBuilder::GenerateCube("cube", 1);
meshList[GEO_PAVEMENT]->textureID[0] = LoadTGA("Image//pavement.tga");
/** UI **/
meshList[GEO_CROSSHAIR] = MeshBuilder::GenerateQuad("GEO_CROSSHAIR", Color(1, 1, 1), 1.f);
meshList[GEO_CROSSHAIR]->textureID[0] = LoadTGA("Image//crosshair.tga");
meshList[GEO_SELECTOR] = MeshBuilder::GenerateQuad("selector", Color(1, 1, 1), 1.f);
meshList[GEO_SELECTOR]->textureID[0] = LoadTGA("Image//selector.tga");
/** skybox **/
meshList[GEO_LEFT] = MeshBuilder::GenerateQuad("LEFT", Color(1, 1, 1), 1.f);
meshList[GEO_LEFT]->textureID[0] = LoadTGA("Image//sunset_left.tga");
meshList[GEO_RIGHT] = MeshBuilder::GenerateQuad("RIGHT", Color(1, 1, 1), 1.f);
meshList[GEO_RIGHT]->textureID[0] = LoadTGA("Image//sunset_right.tga");
meshList[GEO_TOP] = MeshBuilder::GenerateQuad("TOP", Color(1, 1, 1), 1.f);
meshList[GEO_TOP]->textureID[0] = LoadTGA("Image//sunset_top.tga");
meshList[GEO_BOTTOM] = MeshBuilder::GenerateQuad("BOTTOM", Color(1, 1, 1), 1.f);
meshList[GEO_BOTTOM]->textureID[0] = LoadTGA("Image//sunset_bottom.tga");
meshList[GEO_FRONT] = MeshBuilder::GenerateQuad("FRONT", Color(1, 1, 1), 1.f);
meshList[GEO_FRONT]->textureID[0] = LoadTGA("Image//sunset_front.tga");
meshList[GEO_BACK] = MeshBuilder::GenerateQuad("BACK", Color(1, 1, 1), 1.f);
/** terrain **/
meshList[GEO_BACK]->textureID[0] = LoadTGA("Image//sunset_back.tga");
meshList[GEO_SKYPLANE] = MeshBuilder::GenerateSkyPlane("GEO_SKYPLANE", Color(1, 1, 1), 128, 600.0f, 6000.0f, 6.0f, 6.0f);
meshList[GEO_SKYPLANE]->textureID[0] = LoadTGA("Image//night_sky6.tga");
meshList[GEO_TERRAIN] = meshList[GEO_TERRAIN] = MeshBuilder::GenerateTerrain("GEO_TERRAIN", "Image//valley.raw", m_heightMap);
meshList[GEO_TERRAIN]->textureID[0] = LoadTGA("Image//moss1.tga");
meshList[GEO_TERRAIN]->textureID[1] = LoadTGA("Image//brick.tga");
meshList[GEO_SNOWFLAKE] = MeshBuilder::GenerateOBJ("snow flake", "OBJ//snow_flake.obj");
meshList[GEO_SNOWFLAKE]->textureID[0] = LoadTGA("Image//snow_flake.tga");
meshList[GEO_ICE_RINK] = MeshBuilder::GenerateQuad("ice surface", Color(1, 1, 1), 1.f);
meshList[GEO_ICE_RINK]->textureID[0] = LoadTGA("Image//ice_surface.tga");
/* animation */
meshList[GEO_GIRL] = MeshBuilder::GenerateSpriteAnimation("girl", 3, 7, 1);
meshList[GEO_GIRL]->textureID[0] = LoadTGA("Image//sprite1.tga");
meshList[GEO_RUNNING_CAT] = MeshBuilder::GenerateSpriteAnimation("hot cat", 1, 6, 1);
meshList[GEO_RUNNING_CAT]->textureID[0] = LoadTGA("Image//cat.tga");
meshList[GEO_BUILDING] = MeshBuilder::GenerateOBJ("OBJ1", "OBJ//building-2.obj");//MeshBuilder::GenerateCube("cube", 1);
meshList[GEO_BUILDING]->textureID[0] = LoadTGA("Image//building-1.tga");
meshList[GEO_SIGNBOARD] = MeshBuilder::GenerateOBJ("signboard", "OBJ//signboard.obj");//MeshBuilder::GenerateCube("cube", 1);
meshList[GEO_SIGNBOARD]->textureID[0] = LoadTGA("Image//signboard.tga");
meshList[GEO_LAMPPOST] = MeshBuilder::GenerateOBJ("signboard", "OBJ//lamppost.obj");//MeshBuilder::GenerateCube("cube", 1);
meshList[GEO_LAMPPOST]->textureID[0] = LoadTGA("Image//signboard.tga");
/* police car */
meshList[GEO_CAR_MAIN_PART] = MeshBuilder::GenerateOBJ("car main part", "OBJ//car_main_part.obj");
meshList[GEO_CAR_MAIN_PART]->textureID[0] = LoadTGA("Image//car_main_part.tga");
meshList[GEO_CAR_GLASS] = MeshBuilder::GenerateOBJ("car glass", "OBJ//car_glass.obj");
meshList[GEO_CAR_GLASS]->textureID[0] = LoadTGA("Image//car_glass.tga");
meshList[GEO_CAR_SIREN] = MeshBuilder::GenerateOBJ("car siren", "OBJ//siren.obj");
meshList[GEO_CAR_SIREN]->textureID[0] = LoadTGA("Image//siren.tga");
/* building */
meshList[GEO_DERELICT_BUILDING_01] = MeshBuilder::GenerateOBJ("derelict building 01", "OBJ//derelict_building01.obj");
meshList[GEO_DERELICT_BUILDING_01]->textureID[0] = LoadTGA("Image//derelict_building01.tga");
/* tile map */
tileMap_List[TILEMAP_NATURE].mesh = MeshBuilder::GenerateTileMap("Tile Map", Color(1, 1, 1), 32.f, 32.f, 8, 8); //set the width/heignt of each tile same as the .tga w/h
tileMap_List[TILEMAP_NATURE].name = "Suck ma dick map";
tileMap_List[TILEMAP_NATURE].mesh->textureID[0] = LoadTGA("Image//tile2_ground.tga");
tileMap_List[TILEMAP_NATURE].totalTiles = 8 * 8; //num row * num col
tileMap_List[TILEMAP_NATURE].tileScale = 32.f;
tileMap_List[TILEMAP_NATURE].previewMesh = MeshBuilder::GenerateQuad("Tile Map preview", Color(1, 1, 1), 1.f);
tileMap_List[TILEMAP_NATURE].previewMesh->textureID[0] = LoadTGA("Image//tile2_ground.tga");
/* tile map */
tileMap_List[TILEMAP_MARKET].mesh = MeshBuilder::GenerateTileMap("Tile Map", Color(1, 1, 1), 32.f, 32.f, 16, 16); //set the width/heignt of each tile same as the .tga w/h
tileMap_List[TILEMAP_MARKET].name = "Suck ma dick map";
tileMap_List[TILEMAP_MARKET].mesh->textureID[0] = LoadTGA("Image//tileset_02.tga");
tileMap_List[TILEMAP_MARKET].totalTiles = 16 * 16; //num row * num col
tileMap_List[TILEMAP_MARKET].tileScale = 32.f;
tileMap_List[TILEMAP_MARKET].previewMesh = MeshBuilder::GenerateQuad("Tile Map preview", Color(1, 1, 1), 1.f);
tileMap_List[TILEMAP_MARKET].previewMesh->textureID[0] = LoadTGA("Image//tileset_02.tga");
animation.resize(2); //2 animations
animation[0] = dynamic_cast<SpriteAnimation*>(meshList[GEO_GIRL]);
animation[1] = dynamic_cast<SpriteAnimation*>(meshList[GEO_RUNNING_CAT]);
//startCol, startRow, endCol, endRow, opp dir
animation[0]->init(2.5f, 0, 0, 0, 0, false);
animation[1]->init(5.5f, 0, 0, 0, 2, true);
}
void Geometry::Exit()
{
// Cleanup VBO
for(int i = 0; i < NUM_GEOMETRY; ++i)
{
if(meshList[i])
delete meshList[i];
}
/*while(animation.size() > 0)
{
SpriteAnimation *go = animation.back();
delete go;
animation.pop_back();
}*/
}<file_sep>#include "View_MainMenu.h"
View_Main_Menu::View_Main_Menu(){}
View_Main_Menu::View_Main_Menu(Model_MainMenu* model, unsigned short console_width, unsigned short console_height, MODE mode) :
View(model, console_width, console_height, mode)
{
this->model = model;
}
View_Main_Menu::~View_Main_Menu()
{
}
/********************** Core functions *****************************/
void View_Main_Menu::Init()
{
/* Set up basic stuff */
View::StartInit();
}
void View_Main_Menu::Render(const float fps)
{
/* Set up basic stuff */
View::StartRendering(fps);
RenderCollideBox();
RenderObject();
RenderHUD();
}
void View_Main_Menu::RenderCollideBox()
{
for(vector<Object*>::iterator it = model->getObject()->begin(); it != model->getObject()->end(); ++it)
{
Object* o = (Object*)*it;
if( !o->getActive() )
continue;
modelStack.PushMatrix();
Vector3 pos = o->getBbox()->position;
modelStack.Translate(pos.x, pos.y, pos.z);
modelStack.Scale(o->getBbox()->scale.x, o->getBbox()->scale.y, o->getBbox()->scale.z);
RenderMesh(Geometry::meshList[Geometry::GEO_DEBUG_CUBE], false);
modelStack.PopMatrix();
}
}
void View_Main_Menu::RenderHUD()
{
//On screen text
if(Geometry::meshList[Geometry::GEO_AR_CHRISTY] != NULL)
{
std::ostringstream ss; //universal
/* FPS */
ss.precision(5);
ss << "FPS: " << fps;
RenderTextOnScreen(Geometry::meshList[Geometry::GEO_AR_CHRISTY], ss.str(), Color(1, 1, 0), 76, 55, 66);
ss.str("");
/* Pos */
ss << "Pos: " << model->getCamera()->position;
RenderTextOnScreen(Geometry::meshList[Geometry::GEO_AR_CHRISTY], ss.str(), Color(1, 0, 1), 76, 55, 32);
}
}
void View_Main_Menu::RenderObject()
{
/* Renders all objects */
for(vector<Object*>::iterator it = model->getObject()->begin(); it != model->getObject()->end(); ++it)
{
Object* o = (Object*)*it;
if(o->getActive())
{
modelStack.PushMatrix();
modelStack.LoadMatrix( *(o->getTRS()) );
RenderMesh(o->getMesh(), false);
modelStack.PopMatrix();
}
}
}
void View_Main_Menu::SetModel(Model_MainMenu* model)
{
this->model = model;
}
void View_Main_Menu::Exit()
{
View::Exit();
}
<file_sep>#include "Physics.h"
/* Constructor/destructor */
Physics::Physics()
{
remainingDist = acceleration = vel = 0.f;
dir.SetZero();
movement_state = SET_DIR;
}
Physics::~Physics()
{
}
/* Core */
void Physics::Set(float acceleration)
{
this->acceleration = acceleration;
movement_state = SET_DIR;
}
/* Movement */
bool Physics::Move(Vector3& pos, const float& max_speed, const Vector3& destination, double dt)
{
/** Set dir **/
if( movement_state == SET_DIR )
{
if( destination != pos )
dir = (destination - pos).Normalized();
movement_state = ACCELERATE;
}
/** Accelerate? **/
else if( movement_state == ACCELERATE )
{
if( vel < max_speed )
{
vel += acceleration * dt;
remainingDist += vel;
pos += dir * vel;
/* Reach max speed */
if( vel >= max_speed )
{
vel = max_speed;
movement_state = CONSTANT;
}
}
/** Decelerate **/
if( shouldDecelerate(pos + dir * vel, destination) )
{
pos += (dir * remainingDist) - (destination - pos);
movement_state = DECELERATE;
return false;
}
}
if( movement_state == DECELERATE )
{
vel -= acceleration * dt;
pos += dir * vel;
if( vel <= Math::EPSILON )
{
vel = 0.f;
remainingDist = 0.f;
dir.SetZero();
pos = destination;
movement_state = SET_DIR;
return true;
}
}
return false;
}
bool Physics::shouldDecelerate(const Vector3& pos, const Vector3& destination)
{
float remaining = (destination - pos).LengthSquared();
return remainingDist * remainingDist >= remaining;
}<file_sep>#include "Ammo.h"
/* Fixed vel */
const float Ammo::PISTOL_SPEED = 50.f;
const float Ammo::UZI_SPEED = 50.f;
const float Ammo::SHOTGUN_SPEED = 50.f;
const float Ammo::GRENADE_SPEED = 50.f;
/* physics */
const float Ammo::GRENADE_DECELERATION = 5.f;
/* Utilities */
bool Ammo::collide = false;
Object* Ammo::collidedObject = NULL;
/* constructor/destructor */
Ammo::Ammo()
{
vel.SetZero();
}
Ammo::~Ammo()
{
}
/* core */
void Ammo::Init(AMMO_TYPE type)
{
this->type = type;
Set("Bullet", Geometry::meshList[Geometry::GEO_CUBE_BLUE], NULL);
translateObject(0, 0, 2); //z is higer than many other stuff
scaleObject(50, 50, 50);
collide = false;
entity.setActive(false);
}
//pass in the relavant info variables and they will be updated
void Ammo::Update(vector<Object*>& objectList)
{
/* If collides */
if( collide )
{
//response: zombie loses hp...
//collidedObject.hitResponse()
setActive(false);
}
/* Check collision */
StartChecking(vel);
/* Check collision */
collide = false;
for(int i = 0; i < objectList.size(); ++i)
{
if( this == objectList[i] || !objectList[i]->getActive() )
continue;
if( checkCollision(*objectList[i]) ) //hit something
{
//response: zombie dies
collide = true;
collidedObject = objectList[i];
}
}
/* Reset */
collideBox.Reset();
/* collision response */
Response(vel);
}
void Ammo::Activate(const Vector3& pos, const Vector3& dir)
{
//set basics
setActive(true);
translate(pos);
/* Set vel */
switch( type )
{
case PISTOL:
vel = dir * PISTOL_SPEED;
break;
case UZI:
vel = dir * UZI_SPEED;
break;
case SHOTGUN:
vel = dir * SHOTGUN_SPEED;
break;
case GRENADE:
vel = dir * GRENADE_SPEED;
break;
}
}<file_sep>#include "View_LevelEditor.h"
View_Level_Editor::View_Level_Editor(){}
View_Level_Editor::View_Level_Editor(Model_Level_Editor* model, unsigned short console_width, unsigned short console_height, MODE mode) :
View(model, console_width, console_height, mode)
{
this->model = model;
}
View_Level_Editor::~View_Level_Editor()
{
}
/********************** Core functions *****************************/
void View_Level_Editor::Init()
{
/* Set up basic stuff */
View::StartInit();
}
void View_Level_Editor::Render(const float fps)
{
Vector3 pos11, scale11;
/* Set up basic stuff */
View::StartRendering(fps);
/** UI **/
for(int i = 0; i < model->UI_Object_List.size(); ++i)
RenderUI(model->UI_Object_List[i]);
/** Button **/
for(int i = 0; i < model->buttonList.size(); ++i)
RenderUI(model->buttonList[i]);
/** Text box **/
RenderUI(model->new_map_textbox);
/** Pop up **/
RenderUI(model->tileSelectionMenu);
/** Cursor **/
RenderUI(model->cursor);
/*************** Render TileMap ***************/
float start = model->getCamera()->position.x;
float end = start + model->getViewWidth();
pos11 = model->tile_startPos;
Vector3 selector;
/* So that tile sets final scale will match given scale */
float t_scale = (1.f / Geometry::tileMap_List[model->current_TileMap].tileScale) * model->tileScale;
for(int i = 1; i <= Geometry::tileMap_List[model->current_TileMap].totalTiles; ++i) //loop thru all tiles
{
if( pos11.x >= start && pos11.x <= end )
{
Render2DTile(Geometry::tileMap_List[model->current_TileMap].mesh, false, t_scale, pos11.x, pos11.y, pos11.z, i);
if( model->currentBlock == i ) //selected this block
{
RenderMeshIn2D(Geometry::meshList[Geometry::GEO_SELECTOR], false, model->tileScale * 1.1f, model->tileScale * 1.1f, pos11.x, pos11.y, pos11.z, 0);
}
}
pos11.x += model->tileSpacing; //go towards x positive
if( pos11.x > end )
break;
}
}
void View_Level_Editor::RenderCollideBox()
{
for(vector<Object*>::iterator it = model->getObject()->begin(); it != model->getObject()->end(); ++it)
{
Object* o = (Object*)*it;
if( !o->getActive() )
continue;
modelStack.PushMatrix();
Vector3 pos = o->getBbox()->position;
modelStack.Translate(pos.x, pos.y, pos.z);
modelStack.Scale(o->getBbox()->scale.x, o->getBbox()->scale.y, o->getBbox()->scale.z);
RenderMesh(Geometry::meshList[Geometry::GEO_DEBUG_CUBE], false);
modelStack.PopMatrix();
}
}
void View_Level_Editor::RenderObject()
{
/* Renders all objects */
for(vector<Object*>::iterator it = model->getObject()->begin(); it != model->getObject()->end(); ++it)
{
Object* o = (Object*)*it;
if(o->getActive())
{
modelStack.PushMatrix();
modelStack.LoadMatrix( *(o->getTRS()) );
RenderMesh(o->getMesh(), false);
modelStack.PopMatrix();
}
}
}
void View_Level_Editor::SetModel(Model_Level_Editor* model)
{
this->model = model;
}
void View_Level_Editor::Exit()
{
View::Exit();
}
<file_sep>#ifndef CAMERA_3_H
#define CAMERA_3_H
#include "Camera.h"
class Camera3 : public Camera
{
public:// Update Camera status
enum CAM_TYPE
{
LAND_CAM,
AIR_CAM,
NUM_CAM_TYPE
};
Vector3 defaultPosition;
Vector3 defaultTarget;
Vector3 defaultUp;
CAM_TYPE sCameraType;
float yawAngle;
/* bool flags for inertia */
bool pitchMovingUp, pitchMovingDown;
bool yawMovingRight, yawMovingLeft;
bool walkMovingForward;
bool walkMovingBackward;
bool straftMovingLeft;
bool straftMovingRight;
bool croutching;
/* inertia variables */
float pitchVelocity, yawVelocity; //up / down left / right
float movingVelocity; //forward / backward
float straftVelocity; //left / right
float moveAcceleration;
float camAcceleration; //pitch / yaw
float camBrakeOffset; //for rotating
float cameraSpeed; //speed
virtual void SetCameraType(CAM_TYPE sCameraType);
virtual CAM_TYPE GetCameraType(void);
Camera3();
~Camera3();
virtual void Init(const Vector3& pos, const Vector3& target, const Vector3& up);
virtual void Update(double dt, bool* myKeys);
virtual void Reset();
virtual void UpdateStatus(const unsigned char key);
virtual void SpinClockWise(const double dt);
virtual void SpinCounterClockWise(const double dt);
/* inertia functions */
virtual void TurnLeft(const double dt);
virtual void TurnRight(const double dt);
virtual void LookUp(const double dt);
virtual void LookDown(const double dt);
virtual void LookLeft(const double dt);
virtual void LookRight(const double dt);
void MoveForward(const double dt);
void MoveBackward(const double dt);
void MoveLeft(const double dt);
void MoveRight(const double dt);
void MoveUp(const double dt);
void MoveDown(const double dt);
void DecelerateBackward(const double dt);
void DecelerateForward(const double dt);
void DecelerateLeft(const double dt);
void DecelerateRight(const double dt);
void DecelerateUp(const double dt);
void DecelerateDown(const double dt);
void DecelerateLookLeft(const double dt);
void DecelerateLookRight(const double dt);
/* inertia functions */
// Applied methods
virtual void setJump(const double dt);
virtual void Pitch(const double dt);
virtual void Yaw(const double dt);
virtual void Roll(const double dt);
virtual void Walk(const double dt);
virtual void Strafe(const double dt);
virtual void Jump(const double dt);
virtual void Fly(const double dt);
void croutch(const double dt);
};
#endif<file_sep>#ifndef WRITETO_H
#define WRITETO_H
/* stream classes */
/*
ofstream: stream class to write to files (OUTPUT)
ifstream: stream class to read from files (INPUT)
fstream: stream class to both read and write to files
cin is an object of class istream and cout is an object of class ostream, we can use file stream the same way
we are using them for cin and cout, only difference is to associate these streams with physical files
*/
#include <iostream>
#include <fstream>
/* utilities */
#include <string>
#include <vector>
#include "utilities.h"
#include <ctime>
using namespace std;
bool writeToFile(string& name);
bool writeToFile(string& name, string word);
bool deleteFromFile(string& name, int line);
bool emptyFile(string& name);
#endif<file_sep>#include "Model_Level_Editor.h"
/**/
/*
Task: all class/data created in-function move to global
*/
/**/
string Model_Level_Editor::name;
/*********** constructor/destructor ***************/
Model_Level_Editor::Model_Level_Editor()
{
}
Model_Level_Editor::~Model_Level_Editor()
{
}
/*********** core functions ***************/
void Model_Level_Editor::Init()
{
/*** Stuff that need to always re-init here ***/
/*** Only init once stuff below here ***/
Model::Init();
/* Init local already? */
if( initLocalAlready ) //yes, init alr
return;
initLocalAlready = true; //no, then first time init
/* Current map */
currentMap = 0; //points to map 0
/* UI Vector resize */
buttonList.resize(TOTAL_BUTTON);
UI_Object_List.resize(TOTAL_UI);
/** Utilities **/
z = 1.f;
InitUtilities();
/** State Objects **/
InitAddNewMap();
InitAddNewLayer();
InitEditMap();
InitEditLayer();
InitChooseTileMap();
/** Blocks **/
shiftBlock_Left = shiftBlock_Right = false;
moveBlock.Set(20.f); //accelerate/decelerate when shifting left/right
/** Action **/
currentAction = NONE;
/**** Read from list and add maps ****/
PopulateMapsFromTxt();
/** Init everything of object origin in vectors **/
for(std::vector<Object*>::iterator it = elementObject.begin(); it != elementObject.end(); ++it)
{
Object *go = (Object *)*it;
go->Init();
}
/** States **/
state = EDIT_LAYER;
previousState = state;
}
void Model_Level_Editor::InitUtilities()
{
}
void Model_Level_Editor::InitAddNewMap()
{
buttonList[BUTTON_ADD_NEW_MAP] = new Button;
buttonList[BUTTON_ADD_NEW_MAP]->Set("Add new Map", Geometry::meshList[Geometry::GEO_BOTTOM], 32, 10, 17, 110, 1, true, 0.02f);
new_map_textbox = new TextBox;
new_map_textbox->Set(Geometry::meshList[Geometry::GEO_BACK], 32, 10, 50, 110, 1, true);
}
void Model_Level_Editor::InitAddNewLayer()
{
buttonList[BUTTON_ADD_NEW_LAYER] = new Button;
buttonList[BUTTON_ADD_NEW_LAYER]->Set("Add new Layer", Geometry::meshList[Geometry::GEO_BOTTOM], 32, 10, 17, 97, 1, true, 0.02f);
}
void Model_Level_Editor::InitEditLayer()
{
/* blocks selector bar */
UI_Object_List[UI_BLOCK_SELECTION_BAR] = new UI_Object;
UI_Object_List[UI_BLOCK_SELECTION_BAR]->Set("", Geometry::meshList[Geometry::GEO_CUBE_BLUE],
m_2D_view_width, m_2D_view_height * 0.1f, m_2D_view_width * 0.5f, m_2D_view_height * 0.05f, z, true);
z += 1.05f;
/** Tilemap stuff **/
current_TileMap = Geometry::TILEMAP_NATURE;
tile_startPos.Set(25.f, 5.5f, z);
currentBlock = 1;
tileScale = 10.f;
tileSpacing = 12.f; //2 spaces btw each tile in display in editor
z += 0.05f;
/* Buttons for block */
buttonList[BUTTON_PREVIOUS_BLOCK] = new Button;
buttonList[BUTTON_PREVIOUS_BLOCK]->Set("ASD", Geometry::meshList[Geometry::GEO_CUBE_RED],
15.f, 10.f, 8.f, 5.5f, z, true, 0.1f);
z += 0.05f;
buttonList[BUTTON_NEXT_BLOCK] = new Button;
buttonList[BUTTON_NEXT_BLOCK]->Set("ASD", Geometry::meshList[Geometry::GEO_CUBE_RED],
15.f, 10.f, 152.f, 5.5f, z, true, 0.1f);
z += 0.05f;
}
void Model_Level_Editor::InitEditMap()
{
/* side bar (select current map and layer) */
UI_Object_List[UI_SIDE_BAR] = new UI_Object;
UI_Object_List[UI_SIDE_BAR]->Set("", Geometry::meshList[Geometry::GEO_CUBE_RED],
18.f, m_2D_view_height * 0.9f, 9.f, m_2D_view_height * 0.55f, z, true);
z += 0.05f;
}
void Model_Level_Editor::InitChooseTileMap()
{
/* Button for selecting tilemap */
buttonList[BUTTON_CHANGE_TILE_MAP] = new Button;
buttonList[BUTTON_CHANGE_TILE_MAP]->Set("Select TileMap", Geometry::meshList[Geometry::GEO_CUBE_GREEN],
35.f, 10.f, 18.f, 55.5f, z, true, 0.1f);
/* pop-up for selecting tile map */
tileMap_Menu = new Popup;
tileMap_Menu->Set("", Geometry::meshList[Geometry::GEO_CUBE_GREEN],
m_2D_view_width * 0.85f, m_2D_view_height * 0.85f, m_2D_view_width * 0.5f, m_2D_view_height * 0.5f, z, false);
z += 0.5f;
/* Selection menu */
tileSelectionMenu = new Selection_Menu;
tileSelectionMenu->Set(m_2D_view_height * 0.75f, m_2D_view_height * 0.7f, m_2D_view_width * 0.5f, m_2D_view_height * 0.5f, z, false);
for(int i = 0; i < Geometry::TOTAL_TILEMAP; ++i)
{
tileSelectionMenu->AddItem(Geometry::tileMap_List[i].previewMesh);
}
tileSelectionMenu->Init();
z += 0.5f;
}
void Model_Level_Editor::PopulateMapsFromTxt()
{
}
void Model_Level_Editor::Update(double dt, bool* myKeys)
{
Model::Update(dt, myKeys);
/************************************* Switching state *************************************/
if( myKeys[AIM] )
{
switchState = true;
currentState = IN_GAME;
}
/** Selecting new tilemap **/
/** select new tileMap **/
if( buttonList[BUTTON_CHANGE_TILE_MAP]->CollisionDetection(cursor, myKeys[SHOOT]) )
{
//change to edit map, if click again, when button cools down then change back to previous state
if( state != CHOOSE_TILE_MAP )
{
previousState = state;
state = CHOOSE_TILE_MAP;
NewStateSetup();
}
}
/** Selecting/Adding map **/
if( buttonList[BUTTON_ADD_NEW_MAP]->CollisionDetection(cursor, myKeys[SHOOT]) )
{
state = ADD_NEW_MAP;
}
if( buttonList[BUTTON_ADD_NEW_LAYER]->CollisionDetection(cursor, myKeys[SHOOT]) )
{
}
/** Type something **/
new_map_textbox->CollisionDetection(cursor, myKeys[SHOOT]);
new_map_textbox->Update(dt);
/************************************* Update state *************************************/
switch ( state )
{
case ADD_NEW_MAP:
{
UpdateAddNewMap(dt, myKeys);
break;
}
case ADD_NEW_LAYER:
{
UpdateAddNewLayer(dt, myKeys);
break;
}
case EDIT_MAP:
{
UpdateEditMap(dt, myKeys);
break;
}
case EDIT_LAYER:
{
UpdateEditLayer(dt, myKeys);
break;
}
case CHOOSE_TILE_MAP:
{
UpdateChooseTileMap(dt, myKeys);
break;
}
}
/******************************** Update any neccessary stuff ********************************/
for(int i = 0; i < UI_Object_List.size(); ++i)
{
UI_Object_List[i]->Update(dt);
}
}
void Model_Level_Editor::UpdateAddNewMap(double dt, bool* myKeys)
{
/* Name for map */
cout << "Enter map name: ";
getline(cin, name);
/* Add to textfile */
//check if it already exists
if( !readFromFile( map_list, name ) )
{
ostringstream ss;
/* create and add this map to list */
ss.str("");
ss << mapList.size() + 1 << ": " << name;
writeToFile(map_list, ss.str());
/* Create new txt file for this map, name is index of this map */
ss.str("");
ss << "Maps//" << mapList.size() + 1 << ".txt";
writeToFile(ss.str(), "");
Map* map_ptr = new Map(name, mapList.size());
mapList.push_back(map_ptr);
/* current map is now this newly created map */
currentMap = mapList.back()->getIndex();
cout << "Map created: " << mapList.back()->getName() << endl;
}
else
cout << "Map existed: " << name << endl;
currentMapName = name;
state = ADD_NEW_LAYER;
}
void Model_Level_Editor::UpdateAddNewLayer(double dt, bool* myKeys)
{
/* Added one layer: at least have base layer */
//create txt file for this map
ostringstream ss;
ostringstream ss1;
ss.str("");
ss << "Lvl: " << 0 << " Tilesize: " << 32;
ss1.str("");
ss1 << "Maps//" << mapList[currentMap]->getIndex() + 1 << ".txt";
writeToFile(ss1.str(), ss.str());
state = EDIT_MAP;
}
void Model_Level_Editor::UpdateEditLayer(double dt, bool* myKeys)
{
/** Edit tiles **/
start = cursor->getPosition() - cursor->getScale() * 0.5f;
end = cursor->getPosition() + cursor->getScale() * 0.5f;
/******************************** If hit and click layer option, current layer selected ********************************/
/******************************** If hit and click checkbox beside layer option, layer turn invisible/not visible ********************************/
/******************************** If hit right arrow, scroll right, if hit left arrow, scroll left ********************************/
if( currentAction != SELECTING_TILES )
{
//right
if( buttonList[BUTTON_NEXT_BLOCK]->CollisionDetection(cursor, myKeys[SHOOT]) )
{
if( tile_startPos.x <= 0.f )
{
currentAction = SELECTING_TILES;
newPos = tile_startPos;
newPos.x += 60;
}
}
//left
else if( buttonList[BUTTON_PREVIOUS_BLOCK]->CollisionDetection(cursor, myKeys[SHOOT]) )
{
currentAction = SELECTING_TILES;
newPos = tile_startPos;
newPos.x -= 60;
}
/* Not clicking a button, then able to select tiles */
else if(myKeys[SHOOT])
{
/** If check is not SELECTING_TILES again in case in this frame click button and a tile together **/
/******************************** If click on a tile, that tile is selected ********************************/
Collision::setStartEnd2D(tile_startPos, Vector3(tileScale, tileScale, tileScale), checkStart, checkEnd);
/** Check collide with all blocks **/
for(int i = 1; i <= Geometry::tileMap_List[current_TileMap].totalTiles; ++i)
{
if( Collision::QuickAABBDetection2D(start, end, checkStart, checkEnd) )
{
currentBlock = i;
break;
}
/** If no collide, go further to next block **/
checkStart.x += tileSpacing;
checkEnd.x += tileSpacing;
}
}
}
/******************************** Check cursor pos.x / tileSize and cursor pos.y / tileSize to get current tile ********************************/
/******************************** Left click == add tile ********************************/
/******************************** Right click == remove the tile ********************************/
/******************************** Shift blocks ********************************/
if( currentAction == SELECTING_TILES )
{
//opp. since move function returns false when still moving and true if reached
if( moveBlock.Move(tile_startPos, 220.5f, newPos, dt) )
{
currentAction = NONE;
}
}
}
void Model_Level_Editor::UpdateEditMap(double dt, bool* myKey)
{
/** Add/Delete layers **/
//cout << "hahahhaah" << endl;
}
void Model_Level_Editor::UpdateChooseTileMap(double dt, bool* myKeys)
{
/** Check if quit selection menu **/
if( tileMap_Menu->CollisionDetection(cursor, myKeys[SHOOT]) )
{
state = previousState;
previousState = CHOOSE_TILE_MAP;
NewStateSetup();
}
/** Check select which tile map **/
if( tileSelectionMenu->CollisionDetection(cursor, myKeys[SHOOT]) )
{
current_TileMap = static_cast<Geometry::TILE_MAP>( tileSelectionMenu->getCurrentItem() );
}
}
void Model_Level_Editor::NewStateSetup()
{
/* Exit previous state */
OldStateExit();
/* Init new state */
switch ( state )
{
case CHOOSE_TILE_MAP:
tileMap_Menu->SetActive(true);
tileSelectionMenu->SetActive(true);
break;
case EDIT_LAYER:
tile_startPos.SetXY(25.f, 5.5f);
break;
}
}
void Model_Level_Editor::OldStateExit()
{
switch ( previousState )
{
case CHOOSE_TILE_MAP:
tileSelectionMenu->SetActive(false);
tileMap_Menu->SetActive(false);
break;
case EDIT_LAYER:
break;
}
}
void Model_Level_Editor::Exit()
{
}<file_sep>#include "SuperObject.h"
#include "View.h"
/*** constructor / destructor ***/
SuperObject::SuperObject()
{
}
SuperObject::~SuperObject()
{
}
/*** core ***/
void SuperObject::Set(string name)
{
}
void SuperObject::Init()
{
}
void SuperObject::Draw()
{
}
/*** getters setter ***/
Vector3 SuperObject::getMainPos()
{
return mainPos;
}<file_sep>#include "Map.h"
float Map::offset = 0.1f;
Layer* Map::layer_ptr = NULL;
Vector3 Map::global_vec;
/* Constructor/destructor */
Map::Map(string name, int index)
{
this->name = name;
this->index = index;
}
Map::~Map()
{
}
/* Core */
void Map::AddLayer(bool collidable, float tileScale)
{
layer_ptr = new Layer;
layerList.push_back(layer_ptr);
++totalLayers;
layerList.back()->Set(Geometry::TILEMAP_NATURE, totalLayers - 1, collidable, tileScale);
}
bool Map::deleteLayer(int layerNum)
{
if( layerNum < 0 || layerNum >= totalLayers)
return false;
layerList[layerNum]->Clear();
delete layerList[layerNum];
layerList.pop_back();
--totalLayers;
return true;
}
void Map::RecreateLayer(Geometry::TILE_MAP tileMap, int layer, int totalX, int totalY)
{
if(layer < 0 || layer >= totalLayers)
return;
layerList[layer]->Clear();
layerList[layer]->RecreateLayer(tileMap, totalX, totalY);
}
void Map::EditLayer(int layerIndex, int tileType, int& x, int& y)
{
layerList[layerIndex]->editTile(x, y, tileType);
}
void Map::Clear()
{
for(int i = 0; i < layerList.size(); ++i)
{
layerList[i]->Clear();
}
layerList.clear();
}
/* Get data */
float Map::getTileSize(int layerIndex)
{
return 0;
}
int Map::getLayerSize(int layerIndex)
{
return 0;
}
int Map::getMapSize()
{
return totalLayers;
}
string Map::getName()
{
return name;
}
int Map::getIndex()
{
return index;
}
void Map::setIndex(int i)
{
index = i;
}<file_sep>#include "Model.h"
#include "Controller.h"
#include "GL\glew.h"
#include <sstream>
Camera Model::camera;
bool Model::InitAlready = false;
bool Model::switchState = false;
UI_Object* Model::cursor;
string Model::map_list = "";
Model::STATES Model::currentState = IN_GAME;
unsigned short Model::m_2D_view_width = 160.f; //camera view size X
unsigned short Model::m_2D_view_height = 120.f; //camera view size Y
unsigned short Model::m_view_width = 2400.f; //camera view size X
unsigned short Model::m_view_height = 1600.f; //camera view size Y
/*********** constructor/destructor ***************/
Model::Model()
{
initLocalAlready = false;
}
Model::~Model()
{
}
/*********** core functions ***************/
void Model::Init()
{
/*** Stuff that need to always re-init here ***/
/*** Only init once stuff below here ***/
if( InitAlready ) //init already no need init again
return;
/* Must Init */
InitMesh();
//2D: look to Z
camera.Init(Vector3(0.f, 0.f, 5.f), Vector3(0.f, 0.f, 4.f), Vector3(0, 1, 0));
bLightEnabled = true;
InitAlready = true;
/* UI Object */
cursor = new UI_Object;
cursor->Set("", Geometry::meshList[Geometry::GEO_CUBE_GREEN],
3.f, 3.f, 0.f, 0.f, 9.f, true);
/* Name of map list .txt */
map_list = "Maps//map_list.txt";
}
void Model::InitMesh()
{
Geometry::Init();
}
void Model::Update(double dt, bool* myKeys)
{
cursor->Translate(getCursorPos(Controller::GetCursorPos()));
/* Sprite animation */
for(std::vector<SpriteAnimation*>::iterator it = Geometry::animation.begin(); it != Geometry::animation.end(); ++it)
{
SpriteAnimation *go = (SpriteAnimation *)*it;
go->Update(dt);
}
fps = (float)(1.f / dt);
/* Framerate checker: if drop below 57, performance issues */
if(fps < 58.f)
cout << "Framerate dropped to: " << fps << endl;
}
void Model::Exit()
{
Geometry::Exit();
/* Delete all objects */
for(int i = 0; i < elementObject.size(); ++i)
{
delete elementObject[i];
}
elementObject.clear();
}
void Model::NewStateSetup()
{
}
void Model::OldStateExit()
{
}
/*********** getter / setters ***************/
bool Model::getbLightEnabled(){return bLightEnabled;}
Camera* Model::getCamera(){return &camera;}
unsigned short Model::getViewWidth(){return m_view_width;}
unsigned short Model::getViewHeight(){return m_view_height;}
unsigned short Model::getViewWidth2D(){return m_2D_view_width;}
unsigned short Model::getViewHeight2D(){return m_2D_view_height;}
bool Model::getInitLocal(){return initLocalAlready;}
Vector3 Model::getCursorPos(Vector2 posOnScreen)
{
int w = View::getScreenWidth();
int h = View::getScreenHeight();
float posX = static_cast<float>(posOnScreen.x) / w * m_2D_view_width;
float posY = (h - static_cast<float>(posOnScreen.y)) / h * m_2D_view_height;
return Vector3(posX, posY, 0);
}
Position Model::getLightPos(int index)
{
//if index exceeds
if(index < 0 || index >= TOTAL_LIGHTS)
return Position(0, 0, 0);
else
return lightPos[index];
}
vector<Object*>* Model::getObject(){return &elementObject;}
Object* Model::getObject(int index)
{
return elementObject[index];
}
bool Model::getSwitchState()
{
return switchState;
}
void Model::SetSwitchState(bool b)
{
switchState = b;
}
Model::STATES Model::getCurrentState()
{
return currentState;
}
<file_sep>#ifndef SPRITEANIMATION_H
#define SPRITEANIMATION_H
#include "Mesh.h"
#include "Vector2.h"
#include <string>
using std::string;
/*** store animation info ***/
//struct Animation
//{
// Animation() {}
// void Set(int startCol, int startRow, float time)
// {
// this->startRow = startRow;
// this->startCol = startCol;
// this->animTime = time;
// }
// int startRow; //which row to start
// int startCol; //which col to start
// float animTime; //time per cycle
//};
/*** mesh class for animation ***/
class SpriteAnimation : public Mesh
{
public:
/* constructor/destructor */
SpriteAnimation(const std::string &meshName, int row, int col);
~SpriteAnimation();
/* init/update/render */
//oppDir: if true, going from bottom to top and right to left
void init(float time, int startCol, int startRow, int endCol, int endRow, bool oppDir);
void Update(double dt);
virtual void Render();
/* variables */
int m_row;
int m_col;
int startRow;
int endRow;
int startCol;
int endCol;
bool oppDir;
float m_frameTime; //time per frame
float m_currentTime; //keep track of current time
int m_currentRow; //keep track of current row
int m_currentCol; //keep track of current col
int m_totalFrame; //store total frame
};
struct SpriteData
{
string name;
int startRow, startCol;
int endRow, endCol;
};
#endif<file_sep>#include "AdvancedEntity.h"
#include "View.h"
const float OBJECT_DIST_OFFSET = 500.f;
/***** NOTES *****
1) do Angle face with new direction
2) rotate existing object angle will not be updated
3) use something better than define offset for collision dist check
**********/
/***** reusable temp data *****/
Mtx44 tmp_translation;
Mtx44 tmp_rotation;
Mtx44 tmp_scale;
Vector3 tmp_vec(0, 0, 0);
vector<AdvancedEntity*>::iterator it;
/***** constructor / destructor *****/
AdvancedEntity::AdvancedEntity()
{
}
AdvancedEntity::~AdvancedEntity()
{
parent = NULL;
}
/****** core ******/
void AdvancedEntity::Set(Mesh* mesh, AdvancedEntity* parent)
{
/* set individual variables */
this->mesh = mesh;
this->parent = parent;
active = true;
/* Deafult settings */
position.SetZero();
scale.Set(1, 1, 1);
/* update TRS */
TRS.SetToIdentity(); //trs
tmp_translation.SetToTranslation(position.x, position.y, position.z);
tmp_scale.SetToScale(scale.x, scale.y, scale.z); //scale
TRS = tmp_translation * tmp_scale;
}
void AdvancedEntity::AddParent(AdvancedEntity* parent)
{
this->parent = parent;
}
void AdvancedEntity::FinalizeWithParent()
{
if(parent != NULL)
{
transformWithParent(); //TRS transform with parent
}
}
void AdvancedEntity::Draw()
{
}
/****** utilities ******/
void AdvancedEntity::transformWithParent()
{
/* translate with parent (reset first) */
TRS = parent->TRS * TRS;
/* position */
position.SetZero();
position = TRS * position;
/* scale */
this->scale.x *= parent->scale.x;
this->scale.y *= parent->scale.y;
this->scale.z *= parent->scale.z;
}
/***** transformation *****/
void AdvancedEntity::scaleObject(float x, float y, float z)
{
scale.x *= x;
scale.y *= y;
scale.z *= z;
tmp_scale.SetToScale(x, y, z);
TRS = TRS * tmp_scale;
/* position */
position.SetZero();
position = TRS * position;
}
void AdvancedEntity::scaleObject(float all)
{
scale.x *= all;
scale.y *= all;
scale.z *= all;
tmp_scale.SetToScale(all, all, all);
TRS = TRS * tmp_scale;
/* position */
position.SetZero();
position = TRS * position;
}
void AdvancedEntity::translateObject(float x, float y, float z)
{
tmp_translation.SetToTranslation( x, y, z);
/* unscale TRS */
tmp_scale.SetToScale(1.f / scale.x, 1.f / scale.y, 1.f / scale.z);
TRS = TRS * tmp_scale;
TRS = TRS * tmp_translation;
/* scale back TRS */
tmp_scale.SetToScale(scale.x, scale.y, scale.z);
TRS = TRS * tmp_scale;
/* position */
position.SetZero();
position = TRS * position;
}
void AdvancedEntity::translateObject(Vector3 pos)
{
tmp_translation.SetToTranslation(pos.x, pos.y, pos.z);
/* unscale TRS */
tmp_scale.SetToScale(1.f / scale.x, 1.f / scale.y, 1.f / scale.z);
TRS = TRS * tmp_scale;
TRS = TRS * tmp_translation;
/* scale back TRS */
tmp_scale.SetToScale(scale.x, scale.y, scale.z);
TRS = TRS * tmp_scale;
/* position */
position.SetZero();
position = TRS * position;
}
void AdvancedEntity::rotateObject(float angle, float xAxis, float yAxis, float zAxis)
{
tmp_rotation.SetToRotation(angle, xAxis, yAxis, zAxis);
TRS = TRS * tmp_rotation;
/* position */
position.SetZero();
position = TRS * position;
}
void AdvancedEntity::translate(const Vector3& pos)
{
Vector3 translatePos = pos - position;
tmp_translation.SetToTranslation(translatePos.x, translatePos.y, translatePos.z);
TRS = tmp_translation * TRS;
/* position */
position = pos;
}
void AdvancedEntity::translate(float x, float y, float z)
{
tmp_vec.Set(x, y, z);
Vector3 translatePos = tmp_vec - position;
tmp_translation.SetToTranslation(translatePos.x, translatePos.y, translatePos.z);
TRS = tmp_translation * TRS;
/* position */
position = tmp_vec;
}
/*** getters ***/
Mesh* AdvancedEntity::getMesh(){return mesh;}
Vector3 AdvancedEntity::getScale(){return scale;}
Vector3 AdvancedEntity::getPosition(){return position;}
AdvancedEntity* AdvancedEntity::getParent(){return parent;}
void AdvancedEntity::setParent(AdvancedEntity* parent){this->parent = parent;}
Mtx44* AdvancedEntity::getTRS(){return &TRS;}
void AdvancedEntity::setActive(bool b){active = b;}
bool AdvancedEntity::getActive(){return active;}<file_sep>#include "Controller.h"
#include "View_3D_Game.h"
#include "Model_Gameplay.h"
int main( void )
{
/* Memory leak checker */
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); //call this if program does not exit at same place everytime
/* Pass in View into Controller and set mode (2D/3D) */
Controller myController;
/* Init, Run and Exit */
myController.Init();
myController.Run();
myController.Exit();
}
|
24e81c6c9c047dc646859092abca0b8e297838a9
|
[
"C",
"C++"
] | 75
|
C++
|
FieryGazette/2D-Game
|
fee2978b380e47338c0400b047bff22b0fe3dd37
|
ff94f920b07439d60a818bf4ee8a648f1fe2db22
|
refs/heads/master
|
<file_sep>"use strict";
exports.__esModule = true;
var through2 = require("through2");
var split = require("split2");
var XLSX = require("xlsx");
var replaceExt = require("replace-ext");
var PluginError = require("plugin-error");
var pkginfo = require("pkginfo")(module); // project package.json info into module.exports
var PLUGIN_NAME = module.exports.name;
var loglevel = require("loglevel");
var log = loglevel.getLogger(PLUGIN_NAME); // get a logger instance based on the project name
log.setLevel(process.env.DEBUG_LEVEL || "warn");
function targetSpreadsheet(configObj) {
if (!configObj) configObj = {};
if (!configObj.bookType) configObj.bookType = "xlsx";
configObj.type = "buffer";
var strm = through2.obj(function(file, encoding, callback) {
var returnErr = null;
if (file.isNull() || returnErr) {
//return empty file or if there is an error
return callback(returnErr, file);
}
else if (file.isStream()) {
throw new PluginError(PLUGIN_NAME, "Does not support streaming");
}
else if (file.isBuffer()) {
var linesArr = file.contents.toString().split("\n");
var resultArr = [];
var tempObj = void 0;
var streamNames = [];
var workbook = XLSX.utils.book_new();
for (var lineIdx in linesArr) {
var lineObj = JSON.parse(linesArr[lineIdx]);
tempObj = lineObj.record;
var stream = lineObj.stream;
if (!streamNames.includes(stream)) {
streamNames.push(stream);
resultArr.push([]);
}
var streamIdx = streamNames.indexOf(stream);
var tempStr = JSON.stringify(tempObj);
log.debug(tempStr);
resultArr[streamIdx].push(tempObj);
}
for (var sheetIdx in streamNames) {
var tempSheet = XLSX.utils.json_to_sheet(resultArr[sheetIdx]);
XLSX.utils.book_append_sheet( workbook, tempSheet, streamNames[sheetIdx]);
}
try {
var wbout = XLSX.write(workbook, configObj);
file.contents = Buffer.from(wbout);
switch (configObj.bookType) {
case "biff8":
file.path = replaceExt(file.path, ".xls");
break;
case "biff5":
file.path = replaceExt(file.path, ".xls");
break;
case "biff2":
file.path = replaceExt(file.path, ".xls");
break;
case "xlml":
file.path = replaceExt(file.path, ".xls");
break;
default:
file.path = replaceExt(file.path, "." + configObj.bookType);
}
}
catch (err) {
returnErr = new PluginError(PLUGIN_NAME, err);
}
log.debug("calling callback");
callback(returnErr, file);
}
});
return strm;
}
exports.targetSpreadsheet = targetSpreadsheet;
|
0a7ab1d1ac7e7f240b8d39b44066044792a30e02
|
[
"JavaScript"
] | 1
|
JavaScript
|
chloeosgood/gulp-etl-target-spreadsheet
|
1587a05d17e3a17caaee7e9d382640bd31e60d4e
|
2b77e199e99931091836469bc1d3a1f837c3d2c3
|
refs/heads/master
|
<file_sep><?php
class Student {
public $name ;
public $index;
public $rating;
public $city;
function __construct($name, $index, $rating, $city){
$this->name = $name;
$this->index = $index;
$this->rating = $rating;
$this->city = $city;
}
}
?>
<file_sep>{
"require" : {
"ext-zip": "*" ,
"phpoffice/phpspreadsheet" : "1.14.0",
}
}
<file_sep># PHPsite
Small web app for learning PHP and Yii2
<file_sep><!DOCTYPE html>
<html>
<body>
<?php
require 'vendor/autoload.php';
require 'student_model.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$arrayOfStudents = [
new Student('<NAME>', '11101/18', 8.14, '<NAME>'),
new Student('<NAME>', '1101/19', 9.32, 'Doboj'),
new Student('<NAME>', '1213/17', 6.24 , 'I.Sarajevo')
];
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$i=1;
foreach($arrayOfStudents as $x){
$sheet->setCellValue("A$i", $x->index);
$sheet->setCellValue("B$i", $x->name);
$sheet->setCellValue("C$i", $x->city);
$sheet->setCellValue("D$i", $x->rating);
$i++;
}
$writer = new Xlsx($spreadsheet);
$writer->save('helloworld.xlsx');
echo 'Generisan dokument.';
?>
</body>
</html>
|
a01f41fc68b137b412b657c1c6735ab50905dff0
|
[
"Markdown",
"JSON",
"PHP"
] | 4
|
PHP
|
MilosKarakas/PHPsite
|
80b031f5d3714a5f16b7124490f86fa0f78f5dfc
|
71c56a9eafea1af20e22458c9ecf11a21bd88bed
|
refs/heads/master
|
<repo_name>VishavKirat/React_forms<file_sep>/src/App.js
import React from 'react';
import Form from './Forms';
import {connect} from 'react-redux'
class App extends React.Component {
state = {}
handleSubmitButon = (e)=>{
e.preventDefault();
this.props.addingDetails(this.state);
}
handleInput = (e)=>{
this.setState({
[e.target.id]: e.target.value
})
}
render(){
return (
<div className="App">
<Form handleInput={this.handleInput} handleSubmitButon = {this.handleSubmitButon}/>
{this.props.name && <div className="details container col center">
<p >Name: {this.props.name}</p>
<p >Phone: {this.props.phone}</p>
</div>}
</div>
);
}
}
const mapStateToProps = (state)=>{
return (
{
name: state.name,
phone: state.phone
}
)
}
const mapDispatchToProps = (dispatch)=>(
{
addingDetails :(details)=> dispatch({type:'ADDINGDETAILS',details})
}
)
export default connect(mapStateToProps,mapDispatchToProps)(App);
<file_sep>/src/Redux-store/Reducer/index.js
import {addDetails} from '../Actions'
const initState = {
name:null,
phone: null
}
const reducer = (state=initState,action)=>{
if(action.type === 'ADDINGDETAILS'){
return {...state,name:action.details.name,phone:action.details.phone}
}else{
return state}
}
export default reducer;<file_sep>/src/Redux-store/Actions/index.js
const TYPES = {
ADDINGDETAILS : 'ADDINGDETAILS'
}
export const addDetails = (details)=>{
return ({
type : TYPES.ADDINGDETAILS,
payload : details
})
}
|
6bd94a22da48a8c42dc962630d9d43db26806d84
|
[
"JavaScript"
] | 3
|
JavaScript
|
VishavKirat/React_forms
|
a1c756a27366582e545a3240f5e035af23f5a731
|
c8e5484969647e31986f0a1f84440412d967d04f
|
refs/heads/master
|
<file_sep>from __future__ import print_function
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
# create a new Firefox session
driver = webdriver.Firefox()
driver.implicitly_wait(30)
driver.maximize_window()
# navigate to the application home page
driver.get("http://www.gmail.com")
username = driver.find_element_by_id('identifierId')
username.send_keys('<EMAIL>')
username.send_keys(Keys.RETURN)
password = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[1]/div[1]/div[2]/div[2]/form/div[2]/div/div/div[1]/div[1]/div/div[1]/div/div[1]/input")))
password.click()
password.send_keys("")
password.send_keys(Keys.RETURN)
driver.close()
<file_sep>#!/usr/bin/python
import requests
def consumePOSTRequestSync():
params = {'test1':'param1','test2':'param2'}
url = 'http://httpbin.org/post'
headers = {"Accept": "application/json"}
# call post service with headers and params
response = requests.post(url,headers= headers,data = params)
print "code:"+ str(response.status_code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "content:"+ str(response.text)
# call
consumePOSTRequestSync()
<file_sep>#!/usr/bin/python
import requests
import pdb; pdb.set_trace()
response = requests.get("http://services.groupkt.com/country/get/iso2code/IN");
data = response.json()
#from requests.auth import HTTPBasicAuth
#requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
#<Response [200]>
|
ef1ce8714287fbd26e9ec5a2d5a4c3dd6eff65dd
|
[
"Python"
] | 3
|
Python
|
jaimini76/sel-rest
|
d9182f4ab5af0cb2adada5b3e495c48e2bf1737d
|
82e7e5bfea2dadfcad2ea012c0af855e957b8883
|
refs/heads/master
|
<repo_name>manojsilwal/Lab4<file_sep>/src/main/webapp/WEB-INF/messages_np.properties
addProduct.form.productId.label = Product ID in Nepal
addCustomer.form.birthdate.label = <NAME>
addCustomer.form.sex.label = linga
addCustomer.form.password.label = <PASSWORD>
addCustomer.form.male.label = Purush
addCustomer.form.female.label = Istri
addCustomer.form.username.label = PrayogKarta
addCustomer.form.address.label = thegana<file_sep>/src/main/java/com/example/service/ProductServiceImpl.java
package com.example.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.domain.Product;
import com.example.repository.ProductRepo;
@Service
public class ProductServiceImpl implements ProductService{
@Autowired
ProductRepo productRepo;
@Override
public List<Product> findAll() {
// TODO Auto-generated method stub
return productRepo.findAll();
}
@Override
public Product findById(String productId) {
// TODO Auto-generated method stub
return productRepo.getProduct(productId);
}
@Override
public void addProduct(Product product) {
// TODO Auto-generated method stub
productRepo.addProduct(product);
}
@Override
public void remove(Product product) {
// TODO Auto-generated method stub
productRepo.remove(product);
}
@Override
public void update(Product product) {
// TODO Auto-generated method stub
productRepo.updateProduct(product);
}
}
<file_sep>/src/main/webapp/WEB-INF/messages.properties
validator.message = name is not manoj
<file_sep>/src/main/java/com/example/controller/CustomerController.java
package com.example.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.domain.Customer;
import com.example.service.CustomerService;
import com.example.validate.CustomizeValidation;
@Controller
public class CustomerController {
@Autowired
private CustomerService customerService;
@Autowired
private CustomizeValidation validator;
/*product page showing list of products*/
@RequestMapping(value="/customers", method=RequestMethod.GET)
public String getAll(Model model){
model.addAttribute("customers",customerService.findAll());
return "customers";
}
/*product detail page*/
@RequestMapping(value="/customer/{username}", method=RequestMethod.GET)
public String getProduct(@PathVariable String username, Model model){
Customer customer = customerService.findByUsername(username);
if(customer!=null){
model.addAttribute("customer",customer);
}
return "customerDetail";
}
/*addProduct page*/
@RequestMapping(value="/addCustomer", method=RequestMethod.GET)
public String addProduct(Model model){
model.addAttribute("customer", new Customer());
return "addCustomer";
}
/*save product into storage*/
@RequestMapping(value="/addCustomer", method=RequestMethod.POST)
public String saveProduct(@Valid @ModelAttribute("customer") Customer customer, BindingResult result){
if(result.hasErrors()){
System.out.println(result);
return "addCustomer";
}
customerService.addProduct(customer);
return "redirect:/customers";
}
/*update product page*/
@RequestMapping(value="/updateCustomer/{username}", method=RequestMethod.GET)
public String updateProduct(@PathVariable String username, Model model){
model.addAttribute("customer", customerService.findByUsername(username));
return "addCustomer";
}
@RequestMapping(value="/deleteCustomer/{username}", method=RequestMethod.GET)
public String deleteProduct(@PathVariable String username){
customerService.remove(customerService.findByUsername(username));
return "redirect:/customers";
}
}
<file_sep>/src/main/webapp/WEB-INF/messages_en.properties
addProduct.form.productId.label = Product ID english
addCustomer.form.username.label = <NAME>
addCustomer.form.birthdate.label = BirthDate
addCustomer.form.sex.label = Sex
addCustomer.form.male.label = Male
addCustomer.form.female.label = Female
addCustomer.form.password.label = <PASSWORD>
addCustomer.form.address.label = Address<file_sep>/README.md
# lab2-solution
# Lab4
<file_sep>/src/main/java/com/example/controller/HomeController.java
package com.example.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.example.service.CustomerService;
import com.example.service.UserService;
import com.example.service.UserServiceImpl;
@Controller
public class HomeController {
@Autowired
CustomerService customerService;
/*home page*/
@RequestMapping("/")
public String home(Model model){
System.out.println(customerService.findAll());
return "redirect:/customers";
}
@RequestMapping(value="/login", method=RequestMethod.POST)
public String login(@RequestParam("name") String name, @RequestParam("pass") String pass,Model model){
UserServiceImpl userService = new UserServiceImpl();
if(userService.loginCheck(name, pass)){
return "home";
}
else{
model.addAttribute("error","UserName and/or password incorrect");
return "redirect:/login";
}
}
@RequestMapping(value="/login", method=RequestMethod.GET)
public String loginpage(@ModelAttribute("error") String error, Model model){
model.addAttribute("error", error);
return "login";
}
}
<file_sep>/src/main/java/com/example/service/CustomerServiceImpl.java
package com.example.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.domain.Customer;
import com.example.repository.CustomerRepo;
@Service
public class CustomerServiceImpl implements CustomerService{
@Autowired
CustomerRepo customerRepo;
@Override
public List<Customer> findAll() {
// TODO Auto-generated method stub
return customerRepo.findAll();
}
@Override
public Customer findByUsername(String username) {
// TODO Auto-generated method stub
return customerRepo.getCustomer(username);
}
@Override
public void addProduct(Customer customer) {
// TODO Auto-generated method stub
customerRepo.addCustomer(customer);
}
@Override
public void remove(Customer product) {
// TODO Auto-generated method stub
customerRepo.remove(product);
}
@Override
public void updateCustomer(Customer product) {
// TODO Auto-generated method stub
customerRepo.updateCustomer(product);
}
}
|
e03d415c986dd262fea0575609e1af9bc0e64fd2
|
[
"Markdown",
"Java",
"INI"
] | 8
|
INI
|
manojsilwal/Lab4
|
f2a5efd15e28c8238b3c7911a9264dd5c3b3ddca
|
2cc5faed056e7e48bc9ac12dd3cdd30dc8936cff
|
refs/heads/master
|
<repo_name>maktouch/csv-cleaner<file_sep>/pages/index.js
import { useState } from "react";
import Head from "next/head";
import styles from "../styles/Home.module.css";
import Papa from "papaparse";
import { useFormState } from "../components/hooks/useFormState";
import { DateTime } from "luxon";
import fixUtf8 from "fix-utf8";
export default function Home() {
const [
{ headers, data, filename, ...types },
{ checkbox, select, setValue },
] = useFormState({
filename: "",
headers: [],
data: [],
});
const onChange = (e) => {
const [file] = e.target.files;
const [filename] = file.name.split(".");
setValue(`filename`, `cleaned-${filename}.xlsx`);
Papa.parse(file, {
complete: function (results) {
const [headers, ...data] = results.data;
setValue("headers", headers);
headers.forEach((val, i) => {
setValue(`type-${i}`, "disabled");
});
setValue("data", data);
},
});
};
const save = async (e) => {
const outputHeader = [];
headers.forEach((header, i) => {
const key = `type-${i}`;
const type = types[key];
if (type === "disabled") {
return;
}
outputHeader.push(header);
});
const output = [];
data.forEach((row) => {
const thisRow = [];
row.forEach((val, i) => {
const key = `type-${i}`;
const type = types[key];
if (type === "disabled") {
return null;
}
if (type === "string") {
thisRow.push(fixUtf8(String(val)));
return;
}
if (type === "number") {
thisRow.push(Number(val));
return;
}
if (type === "M/d/yyyy") {
thisRow.push(DateTime.fromFormat(val, "M/d/yyyy").toISODate());
}
});
output.push(thisRow);
});
const response = await fetch(`/api/xlsx`, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
},
redirect: "follow", // manual, *follow, error
body: JSON.stringify({
data: [outputHeader, ...output],
filename,
}), // body data type must match "Content-Type" header
});
const blob = await response.blob();
const link = document.createElement("a");
const url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = "hidden";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
return (
<div className={styles.container}>
<Head>
<title>CSV to XLS</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<input type="file" onChange={onChange} />
<button onClick={save}>Save</button>
<table style={{ border: "1px" }}>
<thead>
<tr>
{headers.map((head, index) => {
return (
<th key={index}>
<p>{head}</p>
<select {...select(`type-${index}`)}>
<option>disabled</option>
<option>string</option>
<option value="M/d/yyyy">date (M/d/yyyy)</option>
{/* <option>date (day/month/year)</option>
<option>date (year/month/day)</option> */}
{/* <option>datetime</option> */}
<option>number</option>
</select>
</th>
);
})}
</tr>
</thead>
<tbody>
{data.map((row, index) => {
return (
<tr key={index}>
{row.map((col, index2) => {
return <td key={`${index}-${index2}`}>{col}</td>;
})}
</tr>
);
})}
</tbody>
</table>
</div>
);
}
<file_sep>/components/hooks/useFormState.js
import { useState, useCallback } from "react";
export function useFormState(_initialState = {}) {
const [initialState, _setInitialState] = useState(_initialState);
const [values, setValues] = useState(_initialState);
const [dirty, setDirtyItems] = useState(new Set());
const [touched, setTouchedItems] = useState(new Set());
const setValue = useCallback(
function (name, value, makeTouched = true, makeDirty = true) {
setValues((state) => ({
...state,
[name]: value,
}));
makeTouched && setTouchedItems((state) => state.add(name));
if (makeDirty) {
if (initialState[name]) {
if (typeof value === "object") {
if (JSON.stringify(value) === JSON.stringify(initialState[name])) {
setDirtyItems((state) => {
state.delete(name);
return state;
});
} else {
setDirtyItems((state) => state.add(name));
}
} else {
if (value === initialState[name]) {
setDirtyItems((state) => {
state.delete(name);
return state;
});
} else {
setDirtyItems((state) => state.add(name));
}
}
} else {
if (value === "" || value === false) {
setDirtyItems((state) => {
state.delete(name);
return state;
});
} else {
setDirtyItems((state) => state.add(name));
}
}
}
},
[initialState]
);
const setInitialState = useCallback(function (state) {
_setInitialState(state);
setValues(state);
setDirtyItems(new Set());
setTouchedItems(new Set());
}, []);
const clear = useCallback(function (name) {
setValues((state) => ({
...state,
[name]: "",
}));
setDirtyItems(new Set());
setTouchedItems(new Set());
}, []);
const text = function (name, options = {}) {
const { onChange } = options;
return {
name,
get value() {
return values[name] || "";
},
onChange: (event) => {
setValue(name, event.target.value);
onChange && onChange(event);
},
};
};
const radio = function (name, value, options = {}) {
const { onChange } = options;
return {
name,
value,
get checked() {
return values[name] === value;
},
onChange: (event) => {
setValue(name, event.target.value);
onChange && onChange(event);
},
};
};
const checkbox = function (name, value, options = {}) {
const { onChange } = options;
const isArray = name.includes("[]");
return {
name,
value,
get checked() {
if (isArray) {
return (values[name] || []).includes(value);
}
return values[name] || false;
},
onChange: (event) => {
if (isArray) {
const copy = [...(values[name] ?? [])];
if (event.target.checked) {
copy.push(value);
} else {
const index = copy.indexOf(value);
if (index > -1) {
copy.splice(index, 1);
}
}
setValue(name, copy);
} else {
setValue(name, event.target.checked);
}
onChange && onChange(event);
},
};
};
const raw = function (name, options = {}) {
const { onChange } = options;
return {
name,
get value() {
return values[name];
},
onChange: (value) => {
setValue(name, value);
onChange && onChange(value);
},
};
};
return [
values,
{
text,
radio,
checkbox,
select: text,
raw,
setValue,
clear,
setInitialState,
dirty,
touched,
},
];
}
<file_sep>/pages/api/xlsx.js
import xlsx from "node-xlsx";
export default (req, res) => {
const { data, filename } = req.body;
const buffer = xlsx.build([{ name: "Sheet 1", data }]);
res.setHeader("Content-disposition", `attachment; filename=${filename}`);
res.setHeader(
"Content-Type",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
);
res.send(buffer);
};
|
dca3319ade9a948b08720b89718bdc7a3cebe2d1
|
[
"JavaScript"
] | 3
|
JavaScript
|
maktouch/csv-cleaner
|
b6822409bd6dee39002b5a6fdd6079c6f9e6757e
|
32261932fad08e324149afc4c5d54b9d740b11ae
|
refs/heads/master
|
<file_sep>import numpy as np
import pygame
from pygame.locals import *
width = 640
height = 640
class sumo_robot:
def __init__(self, enemy):
self.speed = (0,0)
self.mass = 5
self.size = 80
self.rad = self.size * np.sqrt(2)
self.motor_speed = 0.1
if enemy:
self.angle = np.pi*1.5
self.color = (255,0,0)
self.x3 = (width/2)-40
self.y3 = 100
self.x4 = self.x3 + self.size
self.y4 = self.y3
self.x1 = self.x4
self.y1 = self.y4+self.size
self.x2 = self.x3
self.y2 = self.y1
else:
self.angle = np.pi /2
self.color = (0,0,255)
self.x1 = (width/2)-40
self.y1 = height - 180
self.x2 = self.x1 + self.size
self.y2 = self.y1
self.x3 = self.x2
self.y3 = self.y2+self.size
self.x4 = self.x1
self.y4 = self.y3
def display(self):
pygame.draw.polygon(screen, self.color, [
[int(self.x1), int(self.y1)],
[int(self.x2), int(self.y2)],
[int(self.x3), int(self.y3)],
[int(self.x4), int(self.y4)]], 5)
def rotate_left(self):
self.rotation_angle = 2*self.motor_speed/self.size
self.ang01 = np.arctan2(self.y3 - self.y1, self.x1 - self.x3)
self.ang02 = np.arctan2(self.y4 - self.y2, self.x2 - self.x4)
self.ang1 = self.ang01 + self.rotation_angle
if self.ang1 >= np.pi*2: self.ang1 -= (np.pi*2)
elif self.ang1<0: self.ang1 += (np.pi*2)
self.ang2 = self.ang02 + self.rotation_angle
if self.ang2 >= np.pi*2: self.ang2 -= (np.pi*2)
elif self.ang2<0: self.ang2 += (np.pi*2)
self.x1 += self.rad * (np.cos(self.ang1)-np.cos(self.ang01))
self.y1 -= self.rad * (np.sin(self.ang1)-np.sin(self.ang01))
self.x2 += self.rad * (np.cos(self.ang2)-np.cos(self.ang02))
self.y2 -= self.rad * (np.sin(self.ang2)-np.sin(self.ang02))
self.x3 += self.rad * (np.cos(np.pi+self.ang1)-np.cos(np.pi+self.ang01))
self.y3 -= self.rad * (np.sin(np.pi+self.ang1)-np.sin(np.pi+self.ang01))
self.x4 += self.rad * (np.cos(np.pi+self.ang2)-np.cos(np.pi+self.ang02))
self.y4 -= self.rad * (np.sin(np.pi+self.ang2)-np.sin(np.pi+self.ang02))
def rotate_right(self):
self.rotation_angle = -2*self.motor_speed/self.size
self.ang01 = np.arctan2(self.y3 - self.y1, self.x1 - self.x3)
self.ang02 = np.arctan2(self.y4 - self.y2, self.x2 - self.x4)
self.ang1 = self.ang01 + self.rotation_angle
if self.ang1 >= np.pi*2: self.ang1 -= (np.pi*2)
elif self.ang1<0: self.ang1 += (np.pi*2)
self.ang2 = self.ang02 + self.rotation_angle
if self.ang2 >= np.pi*2: self.ang2 -= (np.pi*2)
elif self.ang2<0: self.ang2 += (np.pi*2)
self.x1 += self.rad * (np.cos(self.ang1)-np.cos(self.ang01))
self.y1 -= self.rad * (np.sin(self.ang1)-np.sin(self.ang01))
self.x2 += self.rad * (np.cos(self.ang2)-np.cos(self.ang02))
self.y2 -= self.rad * (np.sin(self.ang2)-np.sin(self.ang02))
self.x3 += self.rad * (np.cos(np.pi+self.ang1)-np.cos(np.pi+self.ang01))
self.y3 -= self.rad * (np.sin(np.pi+self.ang1)-np.sin(np.pi+self.ang01))
self.x4 += self.rad * (np.cos(np.pi+self.ang2)-np.cos(np.pi+self.ang02))
self.y4 -= self.rad * (np.sin(np.pi+self.ang2)-np.sin(np.pi+self.ang02))
def move_forward(self):
self.direction = np.arctan2(self.y1-self.y4, self.x1-self.x4)
self.x1 += np.cos(self.direction) * self.motor_speed
self.y1 += np.sin(self.direction) * self.motor_speed
self.x2 += np.cos(self.direction) * self.motor_speed
self.y2 += np.sin(self.direction) * self.motor_speed
self.x3 += np.cos(self.direction) * self.motor_speed
self.y3 += np.sin(self.direction) * self.motor_speed
self.x4 += np.cos(self.direction) * self.motor_speed
self.y4 += np.sin(self.direction) * self.motor_speed
def move_backward(self):
self.direction = np.pi+np.arctan2(self.y1-self.y4, self.x1-self.x4)
self.x1 += np.cos(self.direction) * self.motor_speed
self.y1 += np.sin(self.direction) * self.motor_speed
self.x2 += np.cos(self.direction) * self.motor_speed
self.y2 += np.sin(self.direction) * self.motor_speed
self.x3 += np.cos(self.direction) * self.motor_speed
self.y3 += np.sin(self.direction) * self.motor_speed
self.x4 += np.cos(self.direction) * self.motor_speed
self.y4 += np.sin(self.direction) * self.motor_speed
pygame.init()
pygame.display.set_caption('Sumo robots')
screen = pygame.display.set_mode((width, height))
screen.fill(Color(0,0,0))
pygame.draw.circle(screen, (255,255,255), (320,320), 300, 30)
my_robot = sumo_robot(False)
en_robot = sumo_robot(True)
my_robot.display()
en_robot.display()
efw = False
ebw = False
ert = False
elt = False
mfw = False
mbw = False
mrt = False
mlt = False
pygame.display.update()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
elt = True
if event.key == pygame.K_RIGHT:
ert = True
if event.key == pygame.K_UP:
efw = True
if event.key == pygame.K_DOWN:
ebw = True
if event.key == pygame.K_a:
mlt = True
if event.key == pygame.K_d:
mrt = True
if event.key == pygame.K_w:
mfw = True
if event.key == pygame.K_s:
mbw = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
elt = False
if event.key == pygame.K_RIGHT:
ert = False
if event.key == pygame.K_UP:
efw = False
if event.key == pygame.K_DOWN:
ebw = False
if event.key == pygame.K_a:
mlt = False
if event.key == pygame.K_d:
mrt = False
if event.key == pygame.K_w:
mfw = False
if event.key == pygame.K_s:
mbw = False
if efw: en_robot.move_forward()
if ebw: en_robot.move_backward()
if ert: en_robot.rotate_right()
if elt: en_robot.rotate_left()
if mfw: my_robot.move_forward()
if mbw: my_robot.move_backward()
if mrt: my_robot.rotate_right()
if mlt: my_robot.rotate_left()
screen.fill(Color(0,0,0))
pygame.draw.circle(screen, (255,255,255), (320,320), 300, 30)
my_robot.display()
en_robot.display()
pygame.display.update()
|
942999ab45bdc6b30389ba230b957a7b916a238b
|
[
"Python"
] | 1
|
Python
|
dankaki/Sumo-pygame
|
17a87c609b543528ff1f07e3bd07ad4843226634
|
89debf32dd125d710724e253a44798a919bb20c5
|
refs/heads/master
|
<repo_name>AndyClayDavidSteph/Project1<file_sep>/Master.js
$(document).ready(function () {
var articleCount = 3;
// NEW YORK TIMES ===========================================================================================
// New York Times Authorization Key
var authKeyNYT = "<KEY>";
// URL Base for New York Times
var queryURLBaseNYT = "https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=" + authKeyNYT + "&q=";
console.log("this is url: " + queryURLBaseNYT);
// New York Times API Call
function runNYT(queryTest) {
// AJAX Function
$.ajax({
url: queryTest,
method: "GET"
}).then(function (NYTData) {
for (var i = 1; i <= articleCount; i++) {
console.log("this is nydata", NYTData);
var multimedia = NYTData.response.docs[i].multimedia[i];
if (multimedia && multimedia.url) {
var nytImage = "https://www.nytimes.com/" + NYTData.response.docs[i].multimedia[i].url;
} else {
var nytImage = "assets/images/noImage.jpg";
};
var nytDescription = NYTData.response.docs[i].snippet;
var nytTitle = NYTData.response.docs[i].headline.main;
var nytURL = NYTData.response.docs[i].web_url;
var nytLogo = "nyt_logo.png";
// Run in the makeCard function, the following inputs set above
makeCard(nytTitle, nytDescription, nytImage, nytURL, nytLogo);
};
});
};
// CNN ===========================================================================================
// News API key that works with CNN and Fox
var authKey = "<KEY>";
// queryURLBase is the start of our API endpoint. The searchTerm will be appended to this when
var queryURLBase = "https://newsapi.org/v2/everything?apiKey=" +
authKey + "&q=";
console.log(queryURLBase);
// This runQuery function expects two parameters:
// (the number of articles to show and the final URL to download data from)
// RUNNIG CNN
function runQuery(queryURL) {
// The AJAX function uses the queryURL and GETS the JSON data associated with it.
// The data then gets stored in the variable called: "newsData"
$.ajax({
url: queryURL,
method: "GET"
}).then(function (newsData) {
// Logging the URL so we have access to it for troubleshooting
console.log("------------------------------------");
console.log("URL: " + queryURL);
console.log("------------------------------------");
// Log the newsData to console, where it will show up as an object
console.log(newsData);
console.log("------------------------------------");
for (var i = 1; i <= articleCount; i++) {
var cnnImage = newsData.articles[i].urlToImage;
var cnnTitle = newsData.articles[i].title;
var cnnDescription = newsData.articles[i].description;
var cnnURL = newsData.articles[i].url;
var cnnLogo = newsData.articles[i].source.id + ".png";
console.log("Logo TEST: " + cnnLogo);
// Run in the makeCard function, the following inputs set above
makeCard(cnnTitle, cnnDescription, cnnImage, cnnURL, cnnLogo);
}
});
}
// FOX ===========================================================================================
function runFox(queryURL) {
$.ajax({
url: queryURL,
method: "GET"
}).then(function (newsData) {
console.log("------------------------------------");
console.log("URL: " + queryURL);
console.log("------------------------------------");
console.log(newsData);
console.log("------------------------------------");
console.log(newsData.articles[0].publishedAt);
console.log(newsData.articles[0].source.name);
console.log(newsData.articles[0].url);
console.log(newsData.articles[0].title);
for (var i = 1; i <= articleCount; i++) {
var foxImage = newsData.articles[i].urlToImage;
var foxTitle = newsData.articles[i].title;
var foxDescription = newsData.articles[i].description;
var foxURL = newsData.articles[i].url;
var foxLogo = "fox-news.png";
console.log("this is fox " + foxImage);
// Delete the // before the URL if it has it and add "https://"
foxImage = foxImage.replace(/^\/\//, 'https://');
// Run in the makeCard function, the following inputs set above
makeCard(foxTitle, foxDescription, foxImage, foxURL, foxLogo);
};
});
}
// Create the cards with each news source for the user to see
function makeCard(title, description, img, link, logo) {
if (!img) {
img = "assets/images/noImage.jpg";
};
var one = $("<div>").addClass("col s12 m4").attr("id", "columnOne")
var two = $("<img>").attr("src", "assets/images/" + logo);
let thumbnail = $("<img>").attr("src", img);
var three = $('<div class="card">'
+ '<div class="card-image crop-height">'
+ '</div>'
+ '<div class="titleMargin">'
+ '<span class="card-title">' + title + '</span>'
+ '<a href= "' + link + '" target="_blank" class="btn-floating halfway-fab waves-effect waves-light red"><i class="material-icons">arrow_forward</i></a>'
+ '</div>'
+ '<div class="card-content">'
+ '<p>' + description + '</p>'
+ '<button id="sentimentButton" data-name = "' + link +'"> Analyze Sentiment </button>'
+ '</div>'
+ '</div>')
// Respond to errors when no image is present by displaying a placeholder image
$(thumbnail).on('error', function (err) {
this.onerror = null;
$(this).attr('src', 'assets/images/noImage.jpg');
});
// Append the proper information to the card
three.children('.card-image').prepend(thumbnail);
one.append(two, three);
$("#newsRow").prepend(one);
}
// Activate the search term to populate the API function search terms when clicked on
$("#searchButton").on("click", function (event) {
// Empty existing query to allow for a new one
$("#newsRow").empty();
// Prevent page from refreshing upon search button click
event.preventDefault();
// Grab the search term value
searchTerm = $("#first_name").val().trim();
var searchURL = queryURLBase + searchTerm;
var newsSource = $('input[name=newsGroup]:checked').val();
console.log("this is the news source 1test: " + newsSource);
var queryTest = queryURLBaseNYT + searchTerm;
// This is taking the checked boxes and giving them the correct value to run through the API.
// NYT still calls it's own API, the rest are funneled to the newsAPI
// I'm calling the function within the if/else statement instead of at the bottom
var val = [];
$(':checkbox:checked').each(function (i) {
val[i] = $(this).val();
if (val[i] == "nyt"){
runNYT(queryTest);
} else {
searchURLC = searchURL + "&sources=" + val[i];
runQuery(searchURLC);
console.log("check box = " + val[i]);
}
});
// searchURLF = searchURL + "&sources=" + "fox-news";
// searchURLC = searchURL + "&sources=" + newsSource;
console.log("search URL test: " + searchURL);
});
// Firebase =================================================================================================
var config = {
apiKey: "<KEY>",
authDomain: "project1-3912c.firebaseapp.com",
databaseURL: "https://project1-3912c.firebaseio.com",
projectId: "project1-3912c",
storageBucket: "",
messagingSenderId: "406225880569"
};
// Standard firebase configuration
firebase.initializeApp(config);
// Set database variable
var database = firebase.database();
// On click button search function
$("#searchButton").on("click", function (event) {
// Prevent page from refreshing upon button click
event.preventDefault();
// Grabs user input
var search = $("#first_name").val().trim();
if (search === ""){
return;
}
var search = {
search: search,
};
// Push into the database what the search item was
database.ref().push(search);
// Clear the search value
$("#first_name").val("");
});
// Pull back from the database the 10 last values stored
// database.ref().limitToLast(10).on("child_added", function (childSnapshot) {
// console.log(childSnapshot.val());
// // Store everything into a variable.
// var search = childSnapshot.val().search;
// // Add each train's data into the table
// $("#dataDump").append("<button id='oldSearch'>" + search + "</button>");
// });
database.ref().on("value",function(snapshot){
$("#dataDump").empty();
var data = snapshot.val();
// console.log(data);
var searchTerms = {};
// Search through the stored database search terms... if it exists, add +1 to it, otherwise, set it to 0
for (var key in data) {
var term = data[key].search.toLowerCase();
if (searchTerms[term] || searchTerms[term] === 0){
searchTerms[term] = searchTerms[term] + 1;
} else {
searchTerms[term] = 1;
}
};
// Create an empty array
var array = [];
// Create an object for the searchTerm that involves the term and its counter
for (var term in searchTerms) {
let obj = {
term: term,
count : searchTerms[term]
};
array.push(obj);
}
// Actually sort through the array pushing the highest value in front
array = array.sort(function(a, b) {
if (a.count < b.count) return 1;
if (a.count > b.count) return -1;
});
console.log(array)
// Return 10 values from the array
var length;
if (array.length > 10){
length = 10;
} else{
length = array.length -1;
};
// Store 10 values or less from the array in the array[i].term and color code it accordingly
for (var i =0; i <= length; i++){
$("#dataDump").append("<a id='oldSearch'>" + array[i].term + " (" + array[i].count + ") |" + "</a>");
};
});
// Run on click for firebase terms to then re-populate cards for the user to see
$("#dataDump").on("click", "a", function (event) {
// Empty the news div to clear for next query
$("#newsRow").empty();
// Prevent page from refreshing upon button click
event.preventDefault();
// searchTerm = $("#oldSearch").val().trim();
var searchTerm = $(this).text();
var searchURL = queryURLBase + searchTerm;
var queryTest = queryURLBaseNYT + searchTerm;
searchURLF = searchURL + "&sources=" + "fox-news";
searchURLC = searchURL + "&sources=" + "cnn";
console.log("search URL test: " + searchURL);
// Call the APIs to run again passing through the proper search terms
runFox(searchURLF);
runQuery(searchURLC);
runNYT(queryTest);
});
// grabbing the link, and running it through a couple API's to get the text and a "sentiment score"
function scoreFunction() {
var appendScoreHere = $(this);
var loadingImage = $('<div><img src="assets/images/loading.gif"></div>')
appendScoreHere.after(loadingImage)
var urlToCheck = $(this).attr("data-name");
console.log("Score FUnction URL: " + urlToCheck);
var authKey = "234735fed7408c1c6423de7e0364aa78";
// queryURLBase is the start of our API endpoint. The searchTerm will be appended to this when
var queryURLBase = "https://api.diffbot.com/v3/analyze?token=" + authKey + "&url=" + urlToCheck;
console.log(queryURLBase);
$.ajax({
url: queryURLBase,
method: "GET"
}).then(function (articleData) {
loadingImage.remove()
// Logging the URL so we have access to it for troubleshooting
console.log("this is the URL in the AJAX function: " + queryURLBase);
console.log(articleData);
console.log(articleData.objects[0].text);
articleText = articleData.objects[0].text;
getSentiment(articleText, appendScoreHere);
});
}
// Sentiment and policital analysis pulled from an API
function getSentiment(articleText, appendScoreHere) {
$.post(
'https://apiv2.indico.io/apis/multiapi?apis=political,emotion',
JSON.stringify({
'api_key': "<KEY>",
'data': articleText,
})
).then(function (res) {
res = JSON.parse(res);
console.log(res);
console.log(res.results.emotion.results.anger);
console.log(res.results.emotion.results.joy);
console.log(res.results.emotion.results.sadness);
console.log(res.results.emotion.results.fear);
console.log(res.results.emotion.results.surprise);
var anger = res.results.emotion.results.anger;
var joy = res.results.emotion.results.joy;
var sadness = res.results.emotion.results.sadness;
var fear = res.results.emotion.results.fear;
var surprise = res.results.emotion.results.surprise;
// Sentimental analysis
if ( anger > joy && anger > sadness && anger > fear && anger > surprise) {
anger = (anger * 100);
anger = (anger.toFixed(2) + "%");
anger = "Anger " + anger;
console.log("Anger is the greatest " + anger);
appendScoreHere.after($("<h6>").html("Strongest Emotion: " + anger.bold()));
} else if (joy > anger && joy > sadness && joy > fear && joy > surprise) {
joy = (joy * 100);
joy = (joy.toFixed(2) + "%")
joy = "Joy " + joy;
console.log("Joy is the greatest " + joy);
appendScoreHere.after($("<h6>").html("Strongest Emotion: " + joy.bold()));
} else if (sadness > anger && sadness > joy && sadness > fear && sadness > surprise) {
sadness = (sadness * 100);
sadness = (sadness.toFixed(2) + "%");
sadness = "Sadness " + sadness;
console.log("Sadness is the greatest " + sadness);
appendScoreHere.after($("<h6>").html("Strongest Emotion: " + sadness.bold()));
} else if (fear > anger && fear > joy && fear > sadness && fear > surprise) {
fear = (fear * 100);
fear = (fear.toFixed(2) + "%");
fear = "Fear " + fear;
console.log("sadness is the greatest " + fear);
appendScoreHere.after($("<h6>").html("Strongest Emotion: " + fear.bold()));
} else {
surprise = (surprise * 100);
surprise = (surprise.toFixed(2) + "%");
surprise = "Surprise " + surprise;
console.log("surpirse is the greatest: " + surprise);
appendScoreHere.after($("<h6>").html("Strongest Emotion: " + surprise.bold()));
}
var libertarian = res.results.political.results.Libertarian;
var green = res.results.political.results.Green;
var liberal = res.results.political.results.Liberal;
var conservative = res.results.political.results.Conservative;
// Political analysis
if (libertarian > green && libertarian > liberal && libertarian > conservative) {
libertarian = (libertarian * 100);
libertarian = (libertarian.toFixed(2) + "%");
libertarian = "Libertarian " + libertarian;
console.log("libertarian is the greatest " + libertarian);
appendScoreHere.after($("<h6>").html("Political Ideology: " + libertarian.bold()));
} else if (green > libertarian && green > liberal && green > conservative) {
green = (green * 100);
green = (green.toFixed(2) + "%");
green = "Green " + green;
console.log("Anger is the greatest " + green);
appendScoreHere.after($("<h6>").html("Political Ideology: " + green.bold()));
} else if (liberal > libertarian && liberal > green && liberal > conservative) {
liberal = (liberal * 100);
liberal = (liberal.toFixed(2) + "%");
liberal = "Liberal " + liberal;
console.log("Liberal is the greatest " + liberal);
appendScoreHere.after($("<h6>").html("Political Ideology: " + liberal.bold()));
} else {
conservative = (conservative * 100);
conservative = (conservative.toFixed(2) + "%");
conservative = "Conservative " + conservative;
console.log("conservative is the greatest: " + conservative);
appendScoreHere.after($("<h6>").html("Political Ideology: " + conservative.bold()));
}
console.log(res.results.political.results.Libertarian);
console.log(res.results.political.results.Green);
console.log(res.results.political.results.Liberal);
console.log(res.results.political.results.Conservative);
});
}
$(document).on("click", "#sentimentButton", scoreFunction);
});
<file_sep>/README.md
# Project1
## Welcome to the Comparison Tool!
#### Search any item and sit back and watch the magic happen! The APIs will do all the work for you!
## API's used:
#### The New York Times API as well as News API. All rights are reserved to them respectively.
## Tools used:
#### HTML, CSS, Javascript, JQuery, AJAX, Firebase
## People Involved:
#### <NAME>, <NAME>, <NAME>, <NAME><file_sep>/Old Material/project1_template(1.1).js
var nytImage;
var nytDescription;
var nytTitle;
var webUrl;
// $(document).ready(function(){
// function makeACardFox() {
// var one = $("<div>").addClass("col s12 m4").attr("id","columnOne")
// var two = $("<img>").attr("src", "assets/images/fox_logo.png")
// var three = '<div class="card">'
// +'<div class="card-image">'
// +'<img src=' + foxImage + '>'
// +'<span class="card-title">' + foxTitle + '</span>'
// +'<a class="btn-floating halfway-fab waves-effect waves-light red"><i class="material-icons">arrow_forward</i></a>'
// +'</div>'
// +'<div class="card-content">'
// +'<p>' + foxDescription + '</p>'
// +'</div>'
// +'</div>'
// $("#newsRow").append(one);
// one.append(two, three);
// }
// function makeACardCNN() {
// var one = $("<div>").addClass("col s12 m4").attr("id","columnOne")
// var two = $("<img>").attr("src", "assets/images/cnn_logo.png")
// var three = '<div class="card">'
// +'<div class="card-image">'
// +'<img src=' + cnnImage + '>'
// +'<span class="card-title">' + cnnTitle + '</span>'
// +'<a class="btn-floating halfway-fab waves-effect waves-light red"><i class="material-icons">arrow_forward</i></a>'
// +'</div>'
// +'<div class="card-content">'
// +'<p>' + cnnDescription + '</p>'
// +'</div>'
// +'</div>'
// $("#newsRow").append(one);
// one.append(two, three);
// }
function makeACardNYT() {
var one = $("<div>").addClass("col s12 m4").attr("id","columnOne")
var two = $("<img>").attr("src", "assets/images/nyt_logo.png")
var three = '<div class="card">'
+'<div class="card-image">'
+'<img src=' + nytImage + '>'
+'<span class="card-title">' + nytTitle + '</span>'
+'<a class="btn-floating halfway-fab waves-effect waves-light red"><i class="material-icons">arrow_forward</i></a>'
+'</div>'
+'<div class="card-content">'
+'<p>' + nytDescription + '</p>'
+'</div>'
+'</div>'
$("#newsRow").append(one);
one.append(two, three);
console.log(NYTData);
}
// $("#searchButton").on("click", makeACardFox);
// $("#searchButton").on("click", makeACardCNN);
$("#searchButton").on("click", makeACardNYT);
// });
|
a52c8db1e1653037e834f7022fc8462d9786dc2e
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
AndyClayDavidSteph/Project1
|
34a4db88e6fddbe2998ea7e9e3a1204d63c479fc
|
b957c95c0c89a2c43a8501e8bee9f5de1a14a2e1
|
refs/heads/main
|
<repo_name>STEMlib/geogeometry<file_sep>/README.md
# Geogeometry

Answering: average number of sides for closed polygons made from 10 randomly drawn lines on a sheet of paper?
The answer to this question suggests fundamental laws about the geometry of geology. For example, the distinct features of cracked mud or broken rocks. The lines used in this analysis represent lines of tension which generate fracturing. By knowing the average number of edges for a specific geological formation we can work backwards to learn about the topology (e.g. the internal and external stresses, material properties).
Inspired by the Quanta article ["Scientists Uncover the Universal Geometry of Geology"](https://www.quantamagazine.org/geometry-reveals-how-the-world-is-assembled-from-cubes-20201119/)
# Quick Start
Put `geogeometry.py` and `test_basic.py` in same folder. Run test from command line as
```bash
$ python test_basic.py
```
# Summary
According to the Quanta article the average number of sides should be 6. This simulation calculates the average by counting the number of edges for a given number of lines drawn (e.g. draw 2 lines, 3 lines, ..., N lines) then averages the array of edge counts.
```python
Mean: 6.597915891328619
Max: 15
Mode: 6
Median: 6.0
```
The example above looped from 2 lines to 10 lines.
An interesting analysis is to look at the number of intersections as a function of lines drawn.

**Further analysis should be explored in the future!**
# Notes
* half of the lines are drawn horizontally and half vertically. This guarantees line intersections
* each line is drawn by randomly selecting a point on each opposing boundary (e.g. left/right [horizontal] or bottom/top [vertical])
# Future Work
* extend the *no. intersections vs. no. lines* to a much larger number (e.g. 100)
* calculate *no. mosaics vs no. lines*
* calculate *area vs. no. lines*
* expect this area to plateau; this should be number of lines drawn, $N_0$
* repeat mosaic simulation using $10k$ iterations of $N_0$ lines drawn
* map from flat surface to generalized geometry
<file_sep>/test_basic.py
from geogeometry import *
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# plot number of intersections as a function of lines drawn
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NUM = 50 # total number of lines drawn
intersections_global = []
for k in range(2,NUM+1):
intersections_local = []
for q in range(100):
num_xs, _, lines = count_intersections(k)
intersections_local.append(num_xs)
intersections_global.append(intersections_local)
plt.figure(figsize=(16,12))
fig = plt.boxplot(intersections_global)
plt.rcParams.update({'font.size': 28})
plt.rc('font', family='serif')
plt.title('Number of Intersections vs Lines Drawn')
plt.xlabel('Number of Lines Drawn')
plt.ylabel('Counts')
plt.xticks(rotation=45)
plt.savefig('intersections_counted.png')
plt.show()
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# calculate average number of edges for mosaic
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
max_lines = 20
global_mosaics_pass, global_mosaics_size = count_mosaics(max_lines)
plt.figure(figsize=(20,10))
for item in global_mosaics_size[0][0]:
plt.boxplot(global_mosaics_size[0])
plt.show()
print("Mean: ", np.mean(global_mosaics_size[0]))
print("Max: ", np.max(global_mosaics_size[0]))
print("Mode: ", stats.mode(global_mosaics_size[0])[0][0])
print("Median: ", np.median(global_mosaics_size[0]))<file_sep>/geogeometry.py
import numpy as np
import pylab as plt
import itertools
from scipy import stats
from shapely.geometry import Point, Polygon, LineString, MultiPolygon
def count_intersections(N=2):
"""This function counts the number of intersections from the randomly
drawn lines
Args:
N (int, optional): number of lines drawn. Defaults to 2.
Returns:
len(xx): number of intersections
xx: intersections
lines: randomly drawn lines
"""
#N = 10
lines = []
for _ in range(int(N/2)):
line_h = LineString([(np.random.random()*10,0),(np.random.random()*10,10)])
line_v = LineString([(np.random.random()*10,0),(np.random.random()*10,10)])
lines.append(line_h) # horizontal
lines.append(line_v) # vertical
combos = itertools.combinations(lines, 2)
intersections = []
for seg in combos:
x = seg[0].intersection(seg[1])
intersections.append(x)
xx = [x.coords[:][0] for x in intersections if x.is_empty is False]
return len(xx), xx, lines
def count_mosaics(max_lines):
"""This function counts the mosaics created from the randomly drawn
lines
Args:
max_lines ([type]): maximum number of lines to draw; used in loop
Returns:
global_mosaics_pass [type]: mosaics created from all loops
global_mosaics_size []: number of mosaics created as function of
the number of lines drawn
"""
global_mosaics_pass = [] # array for all passed mosaics
global_mosaics_size = [] # array for all passed mosaics sizes
for num in range(3,max_lines+1):
intersections_count, intersections, lines = count_intersections(num)
mosaics = []
for NN in range(3,intersections_count+1):
mosaics.extend(itertools.combinations(intersections, NN))
mosaics = [mosaic for mosaic in mosaics if Polygon(mosaic).is_valid]
# remove mosaic if it intersects with any of the lines
# count number of points/nodes for remaining mosaics
local_mosaics_pass = []
local_mosaics_size = []
for mosaic in mosaics:
tst = []
for line in lines:
tst.append(line.within(Polygon(mosaic)))
if not sum(tst*1):
local_mosaics_pass.append(mosaic)
local_mosaics_size.append(len(mosaic))
global_mosaics_pass.append([local_mosaics_pass])
global_mosaics_size.append([local_mosaics_size])
return global_mosaics_pass, global_mosaics_size
|
7cbb1b2324b10450dddcfb28036e63fcc3b55f95
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
STEMlib/geogeometry
|
9a1e5f25a6ea3c83335917b0bdbab4c46f02a677
|
f23b613fe742439006ce6f95e9e12cceacbee908
|
refs/heads/master
|
<file_sep>'''
Created on Mar 22, 2016
@author: eduardo
'''
class Template():
chars = []
def __init__(self, folder, name):
import os
with open(os.path.dirname(os.getcwd()) + '/res/' + folder + '/' + str(name), 'r') as f:
self.chars = [[char for char in line.decode('utf-8')] for line in f]
#---------------------------------------------------- for line in f:
#----------------------------------- line = line.decode('utf-8')
#--------------------------- charsLine = [char for char in line]
#---------------------------------- self.chars.append(charsLine)
print len(self.chars)
print len(self.chars[0])
MAP_FOLDER = 'Maps'
MESSAGE_FOLDER = 'Messages'<file_sep>'''
Created on Mar 22, 2016
@author: eduardo
'''
class Message():
WIDTH = 19
HEIGHT = 6
chars = []
def __init__(self, template):
from character import Character
import game
room = game.getAtualRoom()
for line in template.chars:
charLine = []
for char in line:
charLine.append(Character(char, room.style.fgColor, room.style.bgColor))
self.chars.append(charLine)
def writeTo(self, charMatrix):
for i in xrange(Message.HEIGHT):
for j in xrange(Message.WIDTH):
charMatrix[i+3][j+9] = self.chars[i][j]
return charMatrix
import template
from template import Template
START1 = Template(template.MESSAGE_FOLDER, 0)
FOUND = Template(template.MESSAGE_FOLDER, 1)
LAYOUT = Template(template.MESSAGE_FOLDER, 2)<file_sep>
if __name__ == '__main__':
import os, pygame, sys, game, player
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.init()
screen = pygame.display.set_mode((game.SCREEN_WIDTH, game.SCREEN_HEIGHT))
black = 0, 0, 0
game.init()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit
elif event.type == pygame.KEYDOWN:
if game.MESSAGES:
game.MESSAGES.pop()
if event.key == pygame.K_w:
player.POS_Y -= 1
if player.POS_Y < 0:
player.POS_Y = game.ROOM_HEIGHT - 1
elif event.key == pygame.K_a:
player.POS_X -= 1
if player.POS_X < 0:
player.POS_X = game.ROOM_WIDTH - 1
elif event.key == pygame.K_s:
player.POS_Y += 1
if player.POS_Y >= game.ROOM_HEIGHT:
player.POS_Y = 0
elif event.key == pygame.K_d:
player.POS_X += 1
if player.POS_X >= game.ROOM_WIDTH:
player.POS_X = 0
game.update()
screen.fill(black)
game.render(screen)
pygame.display.update()<file_sep>'''
Created on Mar 22, 2016
@author: eduardo
'''
import game
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
PURPLE = (255, 0, 255)
WHITE = (255, 255, 255)
class Character():
def __init__(self, char, fgColor=WHITE, bgColor=BLACK, bold=False):
font = game.FONT
self.bgColor = bgColor
font.set_bold(bold)
self.label = font.render(char, 1, fgColor, bgColor)
def render(self, screen, y, x):
screen.blit(self.label, (x * game.FONT_WIDTH, y * game.FONT_SIZE))<file_sep>'''
Created on Mar 22, 2016
@author: eduardo
'''
import message
from message import Message
import room
import pygame
class State():
def __init__(self):
self.ticks = 0
self.limit = -1
def update(self):
self.ticks += 1
RUNNING = State()
SWITCHING_ROOM = State()
class Command():
def __init__(self, value):
self.value = value
@classmethod
def valueOf(commands):
value = 4 * commands[0].value + commands[1].value
return value
@classmethod
def add(commands, newCommand):
commands[0] = commands[1]
commands[1] = newCommand
DOWN = Command(0)
LEFT = Command(1)
UP = Command(2)
RIGHT = Command(3)
FONT_SIZE = 35
FONT_WIDTH = int(FONT_SIZE * 0.6)
ROOM_WIDTH = 38
ROOM_HEIGHT = 12
SCREEN_HEIGHT = FONT_SIZE * ROOM_HEIGHT
SCREEN_WIDTH = FONT_WIDTH * ROOM_WIDTH
pygame.font.init()
FONT = pygame.font.SysFont("Courier", FONT_SIZE)
STATE = RUNNING
MODIFIED = True
GOT_BONUS = False
ROOMS = []
ROOMS_ENTERED = 1
ATUAL_ROOM_ID = 0
LAST_ROOM_ID = -1
COMMANDS = [DOWN, DOWN]
MESSAGES = []
import player
def init():
ROOMS.append(room.generateRoom(0))
MESSAGES.append(Message(message.START1))
def render(screen):
charMatrix = [[char for char in line] for line in getAtualRoom().chars]
playerPos = charMatrix[player.POS_Y][player.POS_X]
charMatrix[player.POS_Y][player.POS_X] = player.getSymbolWithBackground(playerPos.bgColor)
if MESSAGES:
charMatrix = MESSAGES[0].writeTo(charMatrix)
for i in xrange(len(charMatrix)):
for j in xrange(len(charMatrix[i])):
charMatrix[i][j].render(screen, i, j)
def update():
pass
def getAtualRoom():
return ROOMS[ATUAL_ROOM_ID]
<file_sep>'''
Created on Mar 22, 2016
@author: eduardo
'''
import game
import character
from character import Character
def generateRoom(roomID):
room = None
if roomID == 0:
room = Room(CLEAN_WHITE)
room.openDoors(0, 2)
return room
class Room():
chars = []
def __init__(self, style):
self.style = style
self.doors = [False, False, False, False]
for i in xrange(game.ROOM_HEIGHT):
self.chars.append([])
for j in xrange(game.ROOM_WIDTH):
#print [i, j]
self.chars[i].append(Character(style.template.chars[i][j], style.fgColor, style.bgColor))
def openDoors(self, *doors):
for door in doors:
self.doors[door] = True
class RoomStyle():
id = 0
def __init__(self, bgColor=character.BLACK, fgColor=character.WHITE):
import template
from template import Template
self.bgColor = bgColor
self.fgColor = fgColor
self.template = Template(template.MAP_FOLDER, RoomStyle.id)
RoomStyle.id += 1
CLEAN_WHITE = RoomStyle(bgColor=character.WHITE, fgColor=character.BLACK)
|
764761c92c7f05e4a2fe4381fd922f48f7cd5aba
|
[
"Python"
] | 6
|
Python
|
eduardoHoefel/MovementGamePython
|
5022df125d6e997bba509dc5e0a7e96a8a75c44c
|
6993b392a04de4a6388ddabe5d5d0a407845885b
|
refs/heads/master
|
<file_sep>module.exports = function(sequelize, DataTypes){
var bpcia_applications = sequelize.define("bpcia_applications",{
organization_legal_name:{
type: DataTypes.STRING,
allowNull: true
},
organization_doing_business_as:{
type: DataTypes.STRING,
allowNull: true
},
date_established: {
type: DataTypes.DATE,
allowNull: true
},
organization_street_name: {
type: DataTypes.STRING,
allowNull: true
},
address_line_2:{
type: DataTypes.STRING,
allowNull: true
},
city: {
type: DataTypes.STRING,
allowNull: true
},
state: {
type: DataTypes.STRING,
allowNull: true
},
zip_code: {
type: DataTypes.STRING,
allowNull: true
},
zip_code_4: {
type: DataTypes.STRING,
allowNull: true
},
organiztion_type: {
type: DataTypes.STRING,
allowNull: true
},
tin_ein: {
type: DataTypes.STRING,
allowNull: true
},
npi: {
type: DataTypes.STRING,
allowNull: true
},
ccn: {
type: DataTypes.STRING,
allowNull: true
},
facility_bed_size: {
type: DataTypes.STRING,
allowNull: true
},
entity_type: {
type: DataTypes.STRING,
allowNull: true
},
entity_type_if_other: {
type: DataTypes.STRING,
allowNull: true
},
academic_medical_center: {
type: DataTypes.STRING,
allowNull: true
},
current_previous_phase2_bpci_participation: {
type: DataTypes.STRING,
allowNull: true
},
medicare_program_participation_excluding_bpci: {
type: DataTypes.STRING,
allowNull: true
},
specify_current_future_medicare_model_or_program: {
type: DataTypes.STRING,
allowNull: true
},
medicare_model_program_identifier: {
type: DataTypes.STRING,
allowNull: true
},
contact_first_name: {
type: DataTypes.STRING,
allowNull: true
},
contact_last_name: {
type: DataTypes.STRING,
allowNull: true
},
contact_email: {
type: DataTypes.STRING,
allowNull: true
},
contact_business_phone: {
type: DataTypes.STRING,
allowNull: true
},
contact_business_phone_ext: {
type: DataTypes.STRING,
allowNull: true
}
});
return bpcia_applications;
}<file_sep>document.getElementById("defaultOpen").click();
$(document).ready(function() {
$('.tooltipped').tooltip();
});
$(document).ready(function() {
$('select').formSelect();
});
function openAppTab(evt, app_step_num) {
var i, tabcontent, tablinks;
// Get all elements with class="tabcontent" and hide them
tabcontent = $(".tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
tablinks = $(".tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// Show the current tab, and add an "active" class to the button that opened the tab
document.getElementById(app_step_num).style.display = "block";
evt.currentTarget.className += " active";
}
$("#step1_button").on("click", function() {
openAppTab(event, 'participant_info');
$('#participant').addClass("active");
})
$("#step2_button").on("click", function() {
openAppTab(event, 'physician_info');
$("#physicians").addClass("active");
})
$("#step3_button").on("click", function() {
openAppTab(event, 'additional_info');
$("#info").addClass("active");
})
$(document).ready(function() {
var max_fields = 5; //maximum input boxes allowed
var wrapper = $("#sanction_table > tbody:last-child"); //Fields wrapper
var add_button = $("#sanction_button"); //Add button ID
var x = 1; //initlal text box count
var y = 3; //Adding data to the table row for looping later;// Pat's comment.
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<tr><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td></tr>'); //add input box
}
});
$("#remove_button").on("click", function(e) { //user click on remove text
e.preventDefault();
if (x > 1) {
$("#sanction_table tr:last").remove();
x--;
}
})
});
///////////////////////////////////////////////////////////////////////////////
////////////////// adding a new surgeon to the table function//////////////////
///////////////////////////////////////////////////////////////////////////////
$(document).ready(function() {
var max_fields = 15; //maximum input boxes allowed
var wrapper = $("#physician_table > tbody:last-child"); //Fields wrapper
var add_button = $("#phys_add_button"); //Add button ID
var x = 1; //initlal text box count
var y = 2; //setting the data for each row.
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
y++; //increment data by 1.
$(wrapper).append('<tr data=' + y + '><td><input class="fName tooltipped" type="text" data-tooltip="Enter the Physician First Name" ></td><td><input class="lName tooltipped" type="text" data-tooltip="Enter the Physician last name"></td><td><input class="NPI tooltipped" type="text" data-tooltip="Enter the Physician National Provider Identifier (NPI). A NPI must be ten digits in length"></td><td><input class="EIN tooltipped" type="text" data-tooltip="Enter the Group Practice Tax Number (TIN) or Employer Identification Number (EIN). A TIN or EIN must be nine digits in length"></td><td><input class="CCN tooltipped" type="text" data-tooltip="Enter all the Hospital CCNs where the Physician is expected to trigger clinical episodes. If there are multiple CCNs per Physician, list each CCN on seperated by a comma. CCNs must be six digits in length"></td></tr>'); //add input box
}
});
$("#phys_remove_button").on("click", function(e) { //user click on remove text
e.preventDefault();
if (x > 4) {
$("#physician_table tr:last").remove();
x--;
y--;
}
})
});
//////////////////////////////////////////////////////////////////
////////////// Creating objects for each physicians///////////////
//////////////////////////////////////////////////////////////////
$("#step3_button").on("click", function() {
var table = document.getElementById("physician_table");
//Looping through the rows of Surgeons and creating objects to send to DB.
for (var i = 1, row; row = table.rows[i]; i++) {
var fname = row.cells[0].children[0].value;
var lname = row.cells[1].children[0].value;
var NPI = row.cells[2].children[0].value;
var EIN = row.cells[3].children[0].value;
var ccn = row.cells[4].children[0].value;
// Creating an object with the physicians info.
var newSurgeon = {
physicians_first_name: fname,
physicians_last_name: lname,
tin_ein: EIN,
npi: NPI,
CCN_expected_to_trigger_clinical_episodes: ccn,
organization_legal_name: $("#organizationLegalName").val()
}
//This is our ajax push to the DB.
$.ajax("/api/pgp_practitioners", {
method: "POST",
data: newSurgeon
}).then(function() {
console.log("New Surgeon - Check your DB.");
});
}
})
$(document).ready(function() {
var max_fields = 15; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".ccn_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input class="form-control" type="text" name="mytext[]"/><a href="#" class="remove_field">Remove </a></div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
/////////////////////////////////////////////////////////////////////////////////
////////////// DONT MESS WITH WITH THIS FUNCTION RIGHT NOW///////////////////////
$("#submitOrgInfo").on("click", function() {
alert("Welcome the the SPS Convener, Where the upside is that there is no downside")
// Getting Values:
let organization_legal_name = $("#organizationLegalName").val();
let organization_doing_business_as = $("#dba").val();
let date_established = $("#dateEstablished").val()
let organization_street_name = $("#address").val();
let address_line_2 = $("#address2").val();
let organiztion_type = $("#orgType option:selected").text();
let city = $("#city").val();
let state = $("#state option:selected").text();
let zip_code = $("#zipCode").val();
let zip_code_4 = null;
let tin_ein = $("#EIN").val();
let npi = $("#GroupNPI").val();
let ccn = $("#CCN").val();
let facility_bed_size = $("#bedSize").val();
let entity_type = $("#EntityType option:selected").val();
let entity_type_if_other = $("#EntityTypeOther").val();
let academic_medical_center = $("#AMC option:selected").val();
let current_previous_phase2_bpci_participation = $("#prevBPCI option:selected").val();
let medicare_program_participation_excluding_bpci = $("#futureBPCI option:selected").val();
let specify_current_future_medicare_model_or_program = $("#FutureCMSProgamText").val();
let medicare_model_program_identifier = $("#CMSModelID").val();
let contact_first_name = $("#fname").val();
let contact_last_name = $("#lname").val();
let contact_email = $("#email").val();
let contact_business_phone = $("#phone").val();
let contact_business_phone_ext = $("#ext").val();
// Creating my object to push to my API.
var organizationApplication = {
organization_legal_name: organization_legal_name,
organization_doing_business_as: organization_doing_business_as,
date_established: date_established,
organization_street_name: organization_street_name,
address_line_2: address_line_2,
city: city,
state: state,
zip_code: zip_code,
zip_code_4: zip_code_4,
organiztion_type: organiztion_type,
tin_ein: tin_ein,
npi: npi,
ccn: ccn,
facility_bed_size: facility_bed_size,
entity_type: entity_type,
entity_type_if_other: entity_type_if_other,
academic_medical_center: academic_medical_center,
current_previous_phase2_bpci_participation: current_previous_phase2_bpci_participation,
medicare_program_participation_excluding_bpci: medicare_program_participation_excluding_bpci,
specify_current_future_medicare_model_or_program: specify_current_future_medicare_model_or_program,
medicare_model_program_identifier: medicare_model_program_identifier,
contact_first_name: contact_first_name,
contact_last_name: contact_last_name,
contact_email: contact_email,
contact_business_phone: contact_business_phone,
contact_business_phone_ext: contact_business_phone_ext
}
console.log(organizationApplication);
// Validating that the data is not blank.
// if (orgnization_legal_name == "") {
// console.log("This condition is true")
// } else {
$.ajax("/api/bpci_applications", {
method: "POST",
data: organizationApplication
}).then(function() {
console.log("New Applciation Submitted - Check your DB.");
});
// }
});
////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////Form Validation Work/////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
$("#orgType").on("change", function() {
if ($("#orgType option:selected").text() == 'Physician Group Practice') {
$("#GroupNPI").prop('disabled', true);
$('#GroupNPI').css({ 'background-color': '#ddd' })
$('#CCN').prop('disabled', true);
$('#CCN').css({ 'background-color': '#ddd' });
$("#bedSize").prop('disabled', true);
$("#bedSize").css({ 'background-color': '#ddd' });
$("#AMC").prop('disabled', true);
$("#AMC").css({ 'background-color': '#ddd' });
$("#bedSize").prop('disabled', true);
$("#bedSize").css({ 'background-color': '#ddd' });
}
if ($("#orgType option:selected").text() == 'Acute Care Hospital') {
$("#GroupNPI").prop('disabled', false);
$('#GroupNPI').css({ 'background-color': 'white' })
$('#CCN').prop('disabled', false);
$('#CCN').css({ 'background-color': 'white' })
$("#bedSize").prop('disabled', false);
$("#bedSize").css({ 'background-color': 'white' })
$("#AMC").prop('disabled', false);
$("#AMC").css({ 'background-color': 'white' })
$("#bedSize").prop('disabled', false);
$("#bedSize").css({ 'background-color': 'white' })
}
});
$("#EntityType").on("change", function() {
if ($("#EntityType option:selected").text() != "Other") {
$("#EntityTypeOther").prop('disabled', true);
$("#EntityTypeOther").css({ 'background-color': '#ddd' });
}
if ($("#EntityType option:selected").text() == "Other") {
$("#EntityTypeOther").prop('disabled', false);
$("#EntityTypeOther").css({ 'background-color': 'white' });
}
});<file_sep>module.exports = function(sequelize, DataTypes){
var pgp_practitioners = sequelize.define("pgp_practitioners",{
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: DataTypes.UUIDV4,
allowNull: true
},
physicians_first_name:{
type: DataTypes.STRING,
allowNull: true,
},
physicians_last_name:{
type: DataTypes.STRING,
allowNull: true,
},
tin_ein: {
type: DataTypes.STRING,
allowNull: true,
},
npi: {
type: DataTypes.STRING,
allowNull: true
},
current_member_of_group: {
type: DataTypes.STRING,
allowNull: true
},
date_member_entered_group: {
type: DataTypes.DATE,
allowNull: true
},
date_member_left_the_group:{
type: DataTypes.DATE,
allowNull: true
},
CCN_expected_to_trigger_clinical_episodes: {
type: DataTypes.STRING(1234),
allowNull: true
},
organization_legal_name: {
type: DataTypes.STRING,
allowNull: true
}
});
// pgp_practitioners.associate = function(models) {
// // We're saying that a Post should belong to an Author
// // A Post can't be created without an Author due to the foreign key constraint
// pgp_practitioners.belongsTo(models.bpcia_applications, {
// foreignKey: true,
// allowNull: true
// })
// };
return pgp_practitioners;
}<file_sep>var db = require("../models");
// create new row for data.
module.exports = function(app){
app.post("/api/pgp_practitioners", function(req, res){
// console.log(req.body);
// console.log("This is Working");
db.pgp_practitioners.create({
physicians_first_name: req.body.physicians_first_name,
physicians_last_name: req.body.physicians_last_name,
tin_ein: req.body.tin_ein,
npi: req.body.npi,
current_member_of_group: req.body.current_member_of_group,
date_member_entered_group: req.body.date_member_entered_group,
CCN_expected_to_trigger_clinical_episodes: req.body.CCN_expected_to_trigger_clinical_episodes,
organization_legal_name: req.body.organization_legal_name
}).then(function(dbPost){
res.json(dbPost);
console.log(dbPost);
});
})
app.post("/api/bpci_applications", function(req, res){
console.log(req.body);
console.log("This is Working");
db.bpcia_applications.create({
organization_legal_name: req.body.organization_legal_name,
organization_doing_business_as: req.body.organization_doing_business_as,
date_established: req.body.date_established,
organization_street_name: req.body.organization_street_name,
address_line_2: req.body.address_line_2,
city: req.body.city,
state: req.body.state,
zip_code: req.body.zip_code,
zip_code_4: req.body.zip_code_4,
organiztion_type: req.body.organiztion_type,
tin_ein: req.body.tin_ein,
npi: req.body.npi,
ccn: req.body.ccn,
facility_bed_size: req.body.facility_bed_size,
entity_type: req.body.entity_type,
entity_type_if_other: req.body.entity_type_if_other,
academic_medical_center: req.body.academic_medical_center,
current_previous_phase2_bpci_participation: req.body.current_previous_phase2_bpci_participation,
medicare_program_participation_excluding_bpci:req.body.medicare_program_participation_excluding_bpci,
specify_current_future_medicare_model_or_program: req.body.specify_current_future_medicare_model_or_program,
medicare_model_program_identifier: req.body.medicare_model_program_identifier,
contact_first_name: req.body.contact_first_name,
contact_last_name: req.body.contact_last_name,
contact_email: req.body.contact_email,
contact_business_phone: req.body.contact_business_phone,
contact_business_phone_ext: req.body.contact_business_phone_ext
}).then(function(dbPost){
res.json(dbPost);
console.log(dbPost);
});
})
}
|
2785e5b21973e3cebe5c32d1eda485a2a7fa5ac2
|
[
"JavaScript"
] | 4
|
JavaScript
|
pd164594/bpcia-signup
|
7c863c6d703d5cf3797841cfe2b7d220adc2385b
|
42a9bfb24663563a8ebb2210156677e3aa967806
|
refs/heads/master
|
<file_sep>--
-- PostgreSQL database dump
--
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner:
--
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner:
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
SET search_path = public, pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: auth_group; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE auth_group (
id integer NOT NULL,
name character varying(80) NOT NULL
);
ALTER TABLE public.auth_group OWNER TO alexander;
--
-- Name: auth_group_id_seq; Type: SEQUENCE; Schema: public; Owner: alexander
--
CREATE SEQUENCE auth_group_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.auth_group_id_seq OWNER TO alexander;
--
-- Name: auth_group_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alexander
--
ALTER SEQUENCE auth_group_id_seq OWNED BY auth_group.id;
--
-- Name: auth_group_permissions; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE auth_group_permissions (
id integer NOT NULL,
group_id integer NOT NULL,
permission_id integer NOT NULL
);
ALTER TABLE public.auth_group_permissions OWNER TO alexander;
--
-- Name: auth_group_permissions_id_seq; Type: SEQUENCE; Schema: public; Owner: alexander
--
CREATE SEQUENCE auth_group_permissions_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.auth_group_permissions_id_seq OWNER TO alexander;
--
-- Name: auth_group_permissions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alexander
--
ALTER SEQUENCE auth_group_permissions_id_seq OWNED BY auth_group_permissions.id;
--
-- Name: auth_permission; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE auth_permission (
id integer NOT NULL,
name character varying(255) NOT NULL,
content_type_id integer NOT NULL,
codename character varying(100) NOT NULL
);
ALTER TABLE public.auth_permission OWNER TO alexander;
--
-- Name: auth_permission_id_seq; Type: SEQUENCE; Schema: public; Owner: alexander
--
CREATE SEQUENCE auth_permission_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.auth_permission_id_seq OWNER TO alexander;
--
-- Name: auth_permission_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alexander
--
ALTER SEQUENCE auth_permission_id_seq OWNED BY auth_permission.id;
--
-- Name: auth_user; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE auth_user (
id integer NOT NULL,
password character varying(128) NOT NULL,
last_login timestamp with time zone,
is_superuser boolean NOT NULL,
username character varying(150) NOT NULL,
first_name character varying(30) NOT NULL,
last_name character varying(30) NOT NULL,
email character varying(254) NOT NULL,
is_staff boolean NOT NULL,
is_active boolean NOT NULL,
date_joined timestamp with time zone NOT NULL
);
ALTER TABLE public.auth_user OWNER TO alexander;
--
-- Name: auth_user_groups; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE auth_user_groups (
id integer NOT NULL,
user_id integer NOT NULL,
group_id integer NOT NULL
);
ALTER TABLE public.auth_user_groups OWNER TO alexander;
--
-- Name: auth_user_groups_id_seq; Type: SEQUENCE; Schema: public; Owner: alexander
--
CREATE SEQUENCE auth_user_groups_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.auth_user_groups_id_seq OWNER TO alexander;
--
-- Name: auth_user_groups_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alexander
--
ALTER SEQUENCE auth_user_groups_id_seq OWNED BY auth_user_groups.id;
--
-- Name: auth_user_id_seq; Type: SEQUENCE; Schema: public; Owner: alexander
--
CREATE SEQUENCE auth_user_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.auth_user_id_seq OWNER TO alexander;
--
-- Name: auth_user_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alexander
--
ALTER SEQUENCE auth_user_id_seq OWNED BY auth_user.id;
--
-- Name: auth_user_user_permissions; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE auth_user_user_permissions (
id integer NOT NULL,
user_id integer NOT NULL,
permission_id integer NOT NULL
);
ALTER TABLE public.auth_user_user_permissions OWNER TO alexander;
--
-- Name: auth_user_user_permissions_id_seq; Type: SEQUENCE; Schema: public; Owner: alexander
--
CREATE SEQUENCE auth_user_user_permissions_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.auth_user_user_permissions_id_seq OWNER TO alexander;
--
-- Name: auth_user_user_permissions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alexander
--
ALTER SEQUENCE auth_user_user_permissions_id_seq OWNED BY auth_user_user_permissions.id;
--
-- Name: django_admin_log; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE django_admin_log (
id integer NOT NULL,
action_time timestamp with time zone NOT NULL,
object_id text,
object_repr character varying(200) NOT NULL,
action_flag smallint NOT NULL,
change_message text NOT NULL,
content_type_id integer,
user_id integer NOT NULL,
CONSTRAINT django_admin_log_action_flag_check CHECK ((action_flag >= 0))
);
ALTER TABLE public.django_admin_log OWNER TO alexander;
--
-- Name: django_admin_log_id_seq; Type: SEQUENCE; Schema: public; Owner: alexander
--
CREATE SEQUENCE django_admin_log_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.django_admin_log_id_seq OWNER TO alexander;
--
-- Name: django_admin_log_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alexander
--
ALTER SEQUENCE django_admin_log_id_seq OWNED BY django_admin_log.id;
--
-- Name: django_content_type; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE django_content_type (
id integer NOT NULL,
app_label character varying(100) NOT NULL,
model character varying(100) NOT NULL
);
ALTER TABLE public.django_content_type OWNER TO alexander;
--
-- Name: django_content_type_id_seq; Type: SEQUENCE; Schema: public; Owner: alexander
--
CREATE SEQUENCE django_content_type_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.django_content_type_id_seq OWNER TO alexander;
--
-- Name: django_content_type_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alexander
--
ALTER SEQUENCE django_content_type_id_seq OWNED BY django_content_type.id;
--
-- Name: django_migrations; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE django_migrations (
id integer NOT NULL,
app character varying(255) NOT NULL,
name character varying(255) NOT NULL,
applied timestamp with time zone NOT NULL
);
ALTER TABLE public.django_migrations OWNER TO alexander;
--
-- Name: django_migrations_id_seq; Type: SEQUENCE; Schema: public; Owner: alexander
--
CREATE SEQUENCE django_migrations_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.django_migrations_id_seq OWNER TO alexander;
--
-- Name: django_migrations_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alexander
--
ALTER SEQUENCE django_migrations_id_seq OWNED BY django_migrations.id;
--
-- Name: django_session; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE django_session (
session_key character varying(40) NOT NULL,
session_data text NOT NULL,
expire_date timestamp with time zone NOT NULL
);
ALTER TABLE public.django_session OWNER TO alexander;
--
-- Name: product_application; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE product_application (
id integer NOT NULL,
fio character varying(100) NOT NULL,
phone character varying(50) NOT NULL,
mail character varying(254) NOT NULL,
count integer NOT NULL,
sum_order double precision NOT NULL,
datetime timestamp with time zone NOT NULL,
product_id integer NOT NULL
);
ALTER TABLE public.product_application OWNER TO alexander;
--
-- Name: product_application_id_seq; Type: SEQUENCE; Schema: public; Owner: alexander
--
CREATE SEQUENCE product_application_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.product_application_id_seq OWNER TO alexander;
--
-- Name: product_application_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alexander
--
ALTER SEQUENCE product_application_id_seq OWNED BY product_application.id;
--
-- Name: product_cart; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE product_cart (
id integer NOT NULL,
price double precision NOT NULL,
count integer NOT NULL,
user_ip character varying(50) NOT NULL,
product_id integer NOT NULL
);
ALTER TABLE public.product_cart OWNER TO alexander;
--
-- Name: product_cart_id_seq; Type: SEQUENCE; Schema: public; Owner: alexander
--
CREATE SEQUENCE product_cart_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.product_cart_id_seq OWNER TO alexander;
--
-- Name: product_cart_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alexander
--
ALTER SEQUENCE product_cart_id_seq OWNED BY product_cart.id;
--
-- Name: product_category; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE product_category (
id integer NOT NULL,
name character varying(50) NOT NULL
);
ALTER TABLE public.product_category OWNER TO alexander;
--
-- Name: product_category_id_seq; Type: SEQUENCE; Schema: public; Owner: alexander
--
CREATE SEQUENCE product_category_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.product_category_id_seq OWNER TO alexander;
--
-- Name: product_category_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alexander
--
ALTER SEQUENCE product_category_id_seq OWNED BY product_category.id;
--
-- Name: product_imageproduct; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE product_imageproduct (
id integer NOT NULL,
path character varying(100) NOT NULL,
name character varying(100) NOT NULL,
product_id integer
);
ALTER TABLE public.product_imageproduct OWNER TO alexander;
--
-- Name: product_imageproduct_id_seq; Type: SEQUENCE; Schema: public; Owner: alexander
--
CREATE SEQUENCE product_imageproduct_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.product_imageproduct_id_seq OWNER TO alexander;
--
-- Name: product_imageproduct_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alexander
--
ALTER SEQUENCE product_imageproduct_id_seq OWNED BY product_imageproduct.id;
--
-- Name: product_product; Type: TABLE; Schema: public; Owner: alexander; Tablespace:
--
CREATE TABLE product_product (
id integer NOT NULL,
name character varying(50) NOT NULL,
count integer NOT NULL,
description text NOT NULL,
price double precision NOT NULL,
main_img character varying(100) NOT NULL,
category_id integer NOT NULL
);
ALTER TABLE public.product_product OWNER TO alexander;
--
-- Name: product_product_id_seq; Type: SEQUENCE; Schema: public; Owner: alexander
--
CREATE SEQUENCE product_product_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.product_product_id_seq OWNER TO alexander;
--
-- Name: product_product_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: alexander
--
ALTER SEQUENCE product_product_id_seq OWNED BY product_product.id;
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY auth_group ALTER COLUMN id SET DEFAULT nextval('auth_group_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY auth_group_permissions ALTER COLUMN id SET DEFAULT nextval('auth_group_permissions_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY auth_permission ALTER COLUMN id SET DEFAULT nextval('auth_permission_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY auth_user ALTER COLUMN id SET DEFAULT nextval('auth_user_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY auth_user_groups ALTER COLUMN id SET DEFAULT nextval('auth_user_groups_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY auth_user_user_permissions ALTER COLUMN id SET DEFAULT nextval('auth_user_user_permissions_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY django_admin_log ALTER COLUMN id SET DEFAULT nextval('django_admin_log_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY django_content_type ALTER COLUMN id SET DEFAULT nextval('django_content_type_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY django_migrations ALTER COLUMN id SET DEFAULT nextval('django_migrations_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY product_application ALTER COLUMN id SET DEFAULT nextval('product_application_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY product_cart ALTER COLUMN id SET DEFAULT nextval('product_cart_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY product_category ALTER COLUMN id SET DEFAULT nextval('product_category_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY product_imageproduct ALTER COLUMN id SET DEFAULT nextval('product_imageproduct_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY product_product ALTER COLUMN id SET DEFAULT nextval('product_product_id_seq'::regclass);
--
-- Data for Name: auth_group; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY auth_group (id, name) FROM stdin;
\.
--
-- Name: auth_group_id_seq; Type: SEQUENCE SET; Schema: public; Owner: alexander
--
SELECT pg_catalog.setval('auth_group_id_seq', 1, false);
--
-- Data for Name: auth_group_permissions; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY auth_group_permissions (id, group_id, permission_id) FROM stdin;
\.
--
-- Name: auth_group_permissions_id_seq; Type: SEQUENCE SET; Schema: public; Owner: alexander
--
SELECT pg_catalog.setval('auth_group_permissions_id_seq', 1, false);
--
-- Data for Name: auth_permission; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY auth_permission (id, name, content_type_id, codename) FROM stdin;
1 Can add log entry 1 add_logentry
2 Can change log entry 1 change_logentry
3 Can delete log entry 1 delete_logentry
4 Can add user 2 add_user
5 Can change user 2 change_user
6 Can delete user 2 delete_user
7 Can add permission 3 add_permission
8 Can change permission 3 change_permission
9 Can delete permission 3 delete_permission
10 Can add group 4 add_group
11 Can change group 4 change_group
12 Can delete group 4 delete_group
13 Can add content type 5 add_contenttype
14 Can change content type 5 change_contenttype
15 Can delete content type 5 delete_contenttype
16 Can add session 6 add_session
17 Can change session 6 change_session
18 Can delete session 6 delete_session
19 Can add image product 7 add_imageproduct
20 Can change image product 7 change_imageproduct
21 Can delete image product 7 delete_imageproduct
22 Can add category 8 add_category
23 Can change category 8 change_category
24 Can delete category 8 delete_category
25 Can add product 9 add_product
26 Can change product 9 change_product
27 Can delete product 9 delete_product
28 Can add application 10 add_application
29 Can change application 10 change_application
30 Can delete application 10 delete_application
31 Can add cart 11 add_cart
32 Can change cart 11 change_cart
33 Can delete cart 11 delete_cart
\.
--
-- Name: auth_permission_id_seq; Type: SEQUENCE SET; Schema: public; Owner: alexander
--
SELECT pg_catalog.setval('auth_permission_id_seq', 33, true);
--
-- Data for Name: auth_user; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY auth_user (id, password, last_login, is_superuser, username, first_name, last_name, email, is_staff, is_active, date_joined) FROM stdin;
1 pbkdf2_sha256$30000$8sILpLml2BFx$Eyu89NicNYAvVu++bc46+vxJPc0s26W52zPghjVEZSw= 2017-03-24 13:55:48.016633+07 t sovushka <EMAIL> t t 2017-03-24 13:55:27.430278+07
\.
--
-- Data for Name: auth_user_groups; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY auth_user_groups (id, user_id, group_id) FROM stdin;
\.
--
-- Name: auth_user_groups_id_seq; Type: SEQUENCE SET; Schema: public; Owner: alexander
--
SELECT pg_catalog.setval('auth_user_groups_id_seq', 1, false);
--
-- Name: auth_user_id_seq; Type: SEQUENCE SET; Schema: public; Owner: alexander
--
SELECT pg_catalog.setval('auth_user_id_seq', 1, true);
--
-- Data for Name: auth_user_user_permissions; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY auth_user_user_permissions (id, user_id, permission_id) FROM stdin;
\.
--
-- Name: auth_user_user_permissions_id_seq; Type: SEQUENCE SET; Schema: public; Owner: alexander
--
SELECT pg_catalog.setval('auth_user_user_permissions_id_seq', 1, false);
--
-- Data for Name: django_admin_log; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY django_admin_log (id, action_time, object_id, object_repr, action_flag, change_message, content_type_id, user_id) FROM stdin;
1 2017-03-24 15:45:31.656997+07 1 Одежда 1 [{"added": {}}] 8 1
2 2017-03-24 15:45:41.228222+07 2 Обувь 1 [{"added": {}}] 8 1
3 2017-03-24 15:46:15.154545+07 3 Аксессуар 1 [{"added": {}}] 8 1
4 2017-03-24 16:00:03.864072+07 1 Kamora 1 [{"added": {}}] 9 1
5 2017-03-24 16:02:43.229141+07 1 kamora1 1 [{"added": {}}] 7 1
6 2017-03-24 16:04:27.148842+07 1 kamora1 3 7 1
7 2017-03-24 16:05:36.840325+07 3 Аксессуар 3 8 1
8 2017-03-24 16:05:36.883356+07 2 Обувь 3 8 1
9 2017-03-24 16:05:36.894389+07 1 Одежда 3 8 1
10 2017-03-24 16:13:11.964901+07 4 clothes 1 [{"added": {}}] 8 1
11 2017-03-24 16:13:34.813773+07 5 footwear 1 [{"added": {}}] 8 1
12 2017-03-24 16:13:55.291246+07 6 accessory 1 [{"added": {}}] 8 1
13 2017-03-24 16:16:58.847162+07 2 Kamora 1 [{"added": {}}] 9 1
14 2017-03-24 16:17:22.372692+07 2 kamora1 1 [{"added": {}}] 7 1
15 2017-03-24 16:17:57.736867+07 2 kamora1 2 [{"changed": {"fields": ["path"]}}] 7 1
16 2017-03-24 16:18:32.564723+07 3 kamora2 1 [{"added": {}}] 7 1
17 2017-03-24 16:18:49.484808+07 4 kamora3 1 [{"added": {}}] 7 1
18 2017-03-24 16:21:57.431709+07 3 Парка <NAME> 1 [{"added": {}}] 9 1
19 2017-03-24 16:23:08.694328+07 5 tommy_hilfiger1 1 [{"added": {}}] 7 1
20 2017-03-24 16:23:22.669332+07 6 tommy_hilfiger2 1 [{"added": {}}] 7 1
21 2017-03-24 16:23:32.600325+07 7 tommy_hilfiger3 1 [{"added": {}}] 7 1
22 2017-03-24 18:42:53.750844+07 1 clothes 1 [{"added": {}}] 8 1
23 2017-03-24 18:43:09.775872+07 2 footwear 1 [{"added": {}}] 8 1
24 2017-03-24 18:43:16.158571+07 3 accessory 1 [{"added": {}}] 8 1
25 2017-03-24 18:44:49.247148+07 1 Kamora 1 [{"added": {}}] 9 1
26 2017-03-24 18:46:44.590707+07 2 Парка <NAME> 1 [{"added": {}}] 9 1
27 2017-03-24 18:58:49.786458+07 2 <NAME> 2 [{"changed": {"fields": ["main_img"]}}] 9 1
28 2017-03-24 19:00:25.86355+07 2 Парка <NAME> 2 [{"changed": {"fields": ["main_img"]}}] 9 1
29 2017-03-24 19:00:37.880877+07 1 Kamora 2 [{"changed": {"fields": ["main_img"]}}] 9 1
30 2017-03-24 19:08:14.119727+07 3 Кеды NIKE SB CHECK SOLAR Nike 1 [{"added": {}}] 9 1
31 2017-03-24 19:10:23.91867+07 4 Бейсболка oodji 1 [{"added": {}}] 9 1
32 2017-03-24 19:12:37.869756+07 5 Кроссовки UMBRO NEWHAVEN 2 Umbro 1 [{"added": {}}] 9 1
33 2017-03-24 19:15:58.84391+07 6 Джинсы 512 Levi's® 1 [{"added": {}}] 9 1
34 2017-03-24 19:17:33.913295+07 7 Шапка Springfield 1 [{"added": {}}] 9 1
35 2017-03-24 19:18:54.370602+07 8 Очки солнцезащитные Polaroid 1 [{"added": {}}] 9 1
36 2017-03-24 19:21:15.373896+07 9 Платье Topshop 1 [{"added": {}}] 9 1
37 2017-03-24 21:48:48.94362+07 10 Bruebeck 1 [{"added": {}}] 9 1
38 2017-03-24 21:50:22.088129+07 11 Туфли Ideal 1 [{"added": {}}] 9 1
39 2017-03-24 21:51:58.160697+07 12 Сумка Topshop 1 [{"added": {}}] 9 1
40 2017-03-24 21:53:30.317281+07 13 <NAME> 1 [{"added": {}}] 9 1
41 2017-03-24 21:55:12.505875+07 14 Платье oodji 1 [{"added": {}}] 9 1
42 2017-03-24 21:56:50.175482+07 15 Берет oodji 1 [{"added": {}}] 9 1
43 2017-03-24 21:58:38.055069+07 16 Слипоны TOMMY NO-LACE PLIMSOLL Lost Ink 1 [{"added": {}}] 9 1
44 2017-03-24 22:00:29.89971+07 17 Ботфорты River Island 1 [{"added": {}}] 9 1
45 2017-03-24 22:03:18.143554+07 18 Кеды YMD 1 [{"added": {}}] 9 1
46 2017-03-24 22:04:46.102835+07 19 Ремень Wrangler 1 [{"added": {}}] 9 1
47 2017-03-25 01:24:09.794393+07 1 1 [{"added": {}}] 7 1
48 2017-03-25 01:24:24.897118+07 2 1 [{"added": {}}] 7 1
49 2017-03-25 01:24:43.119534+07 2 ymd3 2 [{"changed": {"fields": ["name"]}}] 7 1
50 2017-03-25 01:24:49.70103+07 1 ymd2 2 [{"changed": {"fields": ["name"]}}] 7 1
51 2017-03-25 01:31:45.479666+07 3 to 1 [{"added": {}}] 7 1
52 2017-03-25 01:32:00.692168+07 3 tommy_hilfiger2 2 [{"changed": {"fields": ["name"]}}] 7 1
53 2017-03-25 01:32:17.670709+07 4 tommy_hilfiger3 1 [{"added": {}}] 7 1
54 2017-03-25 09:28:50.195349+07 5 Кроссовки UMBRO NEWHAVEN 2 Umbro 2 [{"changed": {"fields": ["description"]}}] 9 1
55 2017-03-25 09:29:11.103827+07 5 Кроссовки UMBRO NEWHAVEN 2 Umbro 2 [] 9 1
56 2017-03-25 09:29:32.775642+07 5 Кроссовки UMBRO NEWHAVEN 2 Umbro 2 [{"changed": {"fields": ["description"]}}] 9 1
57 2017-03-25 09:29:55.03359+07 5 Кроссовки UMBRO NEWHAVEN 2 Umbro 2 [{"changed": {"fields": ["description"]}}] 9 1
58 2017-03-25 10:34:57.938611+07 3 Кеды NIKE SB CHECK SOLAR Nike 2 [{"changed": {"fields": ["description"]}}] 9 1
59 2017-03-25 10:35:24.207538+07 3 Кеды NIKE SB CHECK SOLAR Nike 2 [{"changed": {"fields": ["description"]}}] 9 1
60 2017-03-25 10:35:39.291596+07 3 Кеды NIKE SB CHECK SOLAR Nike 2 [{"changed": {"fields": ["description"]}}] 9 1
61 2017-03-25 14:21:51.45208+07 2 Application object 3 10 1
62 2017-03-25 14:21:51.500079+07 1 Application object 3 10 1
63 2017-03-25 15:38:38.359199+07 4 <EMAIL> (2017-03-25 07:29:26.572520+00:00) 3 10 1
64 2017-03-25 15:38:38.380118+07 3 <EMAIL> (2017-03-25 07:29:26.541387+00:00) 3 10 1
65 2017-03-25 15:40:40.344335+07 7 <EMAIL> (2017-03-25 08:38:43.263222+00:00) 3 10 1
66 2017-03-25 15:40:40.361978+07 6 <EMAIL> (2017-03-25 08:38:43.207987+00:00) 3 10 1
67 2017-03-25 15:40:40.373038+07 5 <EMAIL> (2017-03-25 08:38:43.170468+00:00) 3 10 1
68 2017-03-25 16:42:56.973925+07 11 <EMAIL> (2017-03-25 08:41:37.458382+00:00) 3 10 1
69 2017-03-25 16:42:57.040675+07 10 <EMAIL> (2017-03-25 08:41:37.396811+00:00) 3 10 1
70 2017-03-25 16:42:57.051683+07 9 <EMAIL> (2017-03-25 08:41:37.369394+00:00) 3 10 1
71 2017-03-25 16:42:57.062823+07 8 <EMAIL> (2017-03-25 08:41:37.328384+00:00) 3 10 1
72 2017-03-25 17:25:59.682709+07 14 <EMAIL> (2017-03-25 09:45:05.681191+00:00) 3 10 1
73 2017-03-25 17:25:59.702701+07 13 <EMAIL> (2017-03-25 09:43:03.728464+00:00) 3 10 1
74 2017-03-25 17:25:59.713711+07 12 <EMAIL> (2017-03-25 09:43:03.647727+00:00) 3 10 1
\.
--
-- Name: django_admin_log_id_seq; Type: SEQUENCE SET; Schema: public; Owner: alexander
--
SELECT pg_catalog.setval('django_admin_log_id_seq', 74, true);
--
-- Data for Name: django_content_type; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY django_content_type (id, app_label, model) FROM stdin;
1 admin logentry
2 auth user
3 auth permission
4 auth group
5 contenttypes contenttype
6 sessions session
7 product imageproduct
8 product category
9 product product
10 product application
11 product cart
\.
--
-- Name: django_content_type_id_seq; Type: SEQUENCE SET; Schema: public; Owner: alexander
--
SELECT pg_catalog.setval('django_content_type_id_seq', 11, true);
--
-- Data for Name: django_migrations; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY django_migrations (id, app, name, applied) FROM stdin;
1 contenttypes 0001_initial 2017-03-24 10:14:07.774528+07
2 auth 0001_initial 2017-03-24 10:14:08.563271+07
3 admin 0001_initial 2017-03-24 10:14:08.740587+07
4 admin 0002_logentry_remove_auto_add 2017-03-24 10:14:08.762636+07
5 contenttypes 0002_remove_content_type_name 2017-03-24 10:14:08.806922+07
6 auth 0002_alter_permission_name_max_length 2017-03-24 10:14:08.828839+07
7 auth 0003_alter_user_email_max_length 2017-03-24 10:14:08.85121+07
8 auth 0004_alter_user_username_opts 2017-03-24 10:14:08.868173+07
9 auth 0005_alter_user_last_login_null 2017-03-24 10:14:08.883866+07
10 auth 0006_require_contenttypes_0002 2017-03-24 10:14:08.895197+07
11 auth 0007_alter_validators_add_error_messages 2017-03-24 10:14:08.927601+07
12 auth 0008_alter_user_username_max_length 2017-03-24 10:14:09.006029+07
13 sessions 0001_initial 2017-03-24 10:14:09.183732+07
14 product 0001_initial 2017-03-24 15:35:15.329268+07
15 product 0002_auto_20170324_0910 2017-03-24 16:10:47.51323+07
16 product 0003_auto_20170324_1135 2017-03-24 18:35:43.536801+07
17 product 0004_auto_20170324_1141 2017-03-24 18:41:58.838278+07
18 product 0005_auto_20170324_1158 2017-03-24 18:58:30.155452+07
19 product 0006_auto_20170324_1200 2017-03-24 19:00:13.042583+07
20 product 0007_application_cart 2017-03-25 10:49:45.608622+07
21 product 0008_auto_20170325_0421 2017-03-25 11:21:15.93227+07
\.
--
-- Name: django_migrations_id_seq; Type: SEQUENCE SET; Schema: public; Owner: alexander
--
SELECT pg_catalog.setval('django_migrations_id_seq', 21, true);
--
-- Data for Name: django_session; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY django_session (session_key, session_data, expire_date) FROM stdin;
8mybnt8ap6ro4pgsd674asoxjs7zzk6q <KEY> 2017-04-07 13:55:48.060704+07
\.
--
-- Data for Name: product_application; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY product_application (id, fio, phone, mail, count, sum_order, datetime, product_id) FROM stdin;
\.
--
-- Name: product_application_id_seq; Type: SEQUENCE SET; Schema: public; Owner: alexander
--
SELECT pg_catalog.setval('product_application_id_seq', 14, true);
--
-- Data for Name: product_cart; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY product_cart (id, price, count, user_ip, product_id) FROM stdin;
33 2900 1 127.0.0.1 6
32 4190 1 127.0.0.1 3
31 499 1 127.0.0.1 7
\.
--
-- Name: product_cart_id_seq; Type: SEQUENCE SET; Schema: public; Owner: alexander
--
SELECT pg_catalog.setval('product_cart_id_seq', 33, true);
--
-- Data for Name: product_category; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY product_category (id, name) FROM stdin;
1 clothes
2 footwear
3 accessory
\.
--
-- Name: product_category_id_seq; Type: SEQUENCE SET; Schema: public; Owner: alexander
--
SELECT pg_catalog.setval('product_category_id_seq', 3, true);
--
-- Data for Name: product_imageproduct; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY product_imageproduct (id, path, name, product_id) FROM stdin;
2 ymd3.jpg ymd3 18
1 ymd2.jpg ymd2 18
3 tommy_hilfiger2.jpg tommy_hilfiger2 2
4 tommy_hilfiger3.jpg tommy_hilfiger3 2
\.
--
-- Name: product_imageproduct_id_seq; Type: SEQUENCE SET; Schema: public; Owner: alexander
--
SELECT pg_catalog.setval('product_imageproduct_id_seq', 4, true);
--
-- Data for Name: product_product; Type: TABLE DATA; Schema: public; Owner: alexander
--
COPY product_product (id, name, count, description, price, main_img, category_id) FROM stdin;
12 Сумка Topshop 6 Сумка Topshop выполнена из фактурной искусственной кожи, текстильная подкладка. Детали: застежка на магнитную кнопку, небольшие удобные ручки, два внутренних отделения, средник на молнии, три внутренних кармана - один на молнии, два - накладных без застежки. Пристежной плечевой ремень в комплекте. 3999 sumka_topshop1.jpg 3
2 Парка <NAME> 5 Парка <NAME> выполнена из плотного текстиля. Модель с натуральным утеплителем из пуха и пера. Детали: прямой крой; съемный капюшон дополнен отстегивающимся искусственным мехом; застежка на молнию и пуговицы; один внутренний карман; четыре внешних кармана; эластичные манжеты. 41199 tommy_hilfiger1.jpg 1
1 Kamora 4 Куртка Kamora выполнена из износостойкого водоотталкивающего текстиля и утеплена мягким синтепоном. Модель прямого кроя. Детали: пристроченный регулируемый по ширине капюшон со съемной оторочкой из искусственного меха, застежка на молнию и ветрозащитный клапан на пуговицах, один внутренний и четыре внешних кармана, декоративные молнии, вставки из искусственной кожи. 12399 kamora1.jpg 1
4 Бейсболка oodji 8 Состав Полиэстер - 100%\r\nЦвет серый\r\nСезон Мульти\r\nСтиль Повседневный\r\nКоллекция Весна-лето\r\nДетали аксессуаров вышивка\r\nУзор Рисунки и надписи\r\nТип головного убора Бейсболка\r\nАртикул OO001CMLIH76 990 oodji1.jpg 3
6 Джинсы 512 Levi's® 4 Джинсы 512. Низкая посадка, облегающий в бедрах крой, зауженные к низу брючины. Ткань с добавлением эластана для лучше посадки. Вес ткани 12,7унций. 2900 levis1.jpg 1
7 Шапка Springfield 8 Состав Акрил - 100%\r\nДлина 23 см\r\nЦвет серый\r\nСезон Демисезон, Зима\r\nСтиль Повседневный\r\nКоллекция Осень-зима\r\nУзор Однотонный\r\nТип головного убора Шапка-бини\r\nАртикул SP014CMKKM30 499 springfield1.jpg 3
8 Очки солнцезащитные Polaroid 20 Солнцезащитные очки Polaroid в легкой ударопрочной оправе с прозрачными линзами. Линзы с поляризацией и антибликовым покрытием UltraSight, высокая степень защиты от ультрафиолета 3N. Детали: в комплекте жесткий чехол на молнии. 3599 polaroid1.jpg 3
9 Платье Topshop 3 О ТОВАРЕ\r\nСостав Хлопок - 100%\r\nРазмер модели на фото 44\r\nРост модели на фото 177\r\nПараметры модели 83-60-89\r\nДлина мини\r\nРукав без рукава\r\nЗастежка на пуговицах\r\nЦвет черный\r\nСтрана производства Турция\r\nСезон Мульти\r\nСтиль Повседневный\r\nКоллекция Весна-лето\r\nУзор Однотонный\r\nВырез/воротник На бретелях\r\nНазначение платья Повседневное\r\nАртикул TO029EWNSZ68 3499 topshop1.jpg 1
10 Bruebeck 7 Куртка Bruebeck выполнена из плотного текстиля. Модель приталенного кроя с искусственным утеплителем. Детали: капюшон дополнен съемным искусственным мехом; гладкая подкладка; застежка на молнию и кнопки; два внешних кармана на молнии; пояс в комплекте. 1990 bruebeck1.jpg 1
11 Туфли Ideal 3 Материал верха искусственная лаковая кожа\r\nВнутренний материал искусственная кожа\r\nМатериал стельки искусственная кожа\r\nМатериал подошвы искусственный материал\r\nВысота каблука 10.5 см\r\nТип каблука Шпилька\r\nЗастежка без застежки\r\nЦвет черный\r\nСезон Мульти\r\nСтиль Сексуальный\r\nКоллекция Осень-зима\r\nДетали обуви лакированные\r\nУзор Однотонный\r\nВысота каблука Высокий\r\nТип туфель Лодочки\r\nАртикул ID005AWLQX17 3199 ideal1.jpg 2
13 <NAME> 20 Состав Полиэстер - 100%\r\nШирина 96 см\r\nДлина 190 см\r\nЦвет синий\r\nСезон Мульти\r\nСтиль Повседневный\r\nКоллекция Весна-лето\r\nДетали аксессуаров бахрома/кисточки\r\nУзор Однотонный\r\nАртикул JE008GWLVV41 599 jennyfer1.jpg 3
14 <NAME> 3 Состав Хлопок - 95%, Эластан - 5%\r\nДлина рукава 40 см\r\nДлина 79 см\r\nРазмер модели на фото 42/44\r\nРост модели на фото 175\r\nПараметры модели 85-63-90\r\nДлина мини\r\nРукав 3/4\r\nЗастежка без застежки\r\nЦвет фиолетовый\r\nСтрана производства Узбекистан\r\nСезон Мульти\r\nСтиль Повседневный\r\nКоллекция Весна-лето\r\nУзор Однотонный\r\nВырез/воротник Круглый вырез\r\nНазначение платья Повседневное\r\nАртикул OO001EWNLV70 499 plat_oodji1.jpg 1
15 Берет oodji 9 Состав Вискоза - 40%, Полиамид - 40%, Хлопок - 15%, Ангора - 5%\r\nЦвет черный\r\nСезон Демисезон, Зима\r\nСтиль Повседневный\r\nКоллекция Весна-лето\r\nУзор Геометрия\r\nТип головного убора Берет\r\nАртикул OO001CWMEA48 249 beret_oodji1.jpg 3
16 Слипоны TOMMY NO-LACE PLIMSOLL Lost Ink 4 Слипоны LOST INK выполнены из искусственной кожи. Детали: внутренняя отделка из искусственной кожи; подошва из термопластиковой резины. 2499 tommy_no-lace1.jpg 2
17 Ботфорты River Island 5 Ботфорты River Island выполнены из искусственной замши. Детали: сбоку застежка на молнию; шнурок по верху; высокий каблук. 8299 river_island1.jpg 2
18 Кеды YMD 6 Кеды YMD выполнены из текстиля в сочетании с искусственной замшей. Детали: контрастная шнуровка, текстильная внутренняя отделка, контрастная подошва. 2999 ymd1.jpg 2
19 Ремень Wrangler 25 Мужской ремень от Wrangler. Аксессуар создан из натуральной кожи черного цвета. Детали: контрастная белая прошивка, квадратная металлическая пряжка. 2400 remen_wrangler1.jpg 3
5 Кроссовки UMBRO NEWHAVEN 2 Umbro 3 Легкие повседневные кроссовки Umbro NEWHAVEN 2 выполнены из прочной искусственной кожи с воздухопроницаемыми вставками. Детали: шнуровка, амортизирующая подошва, стелька из легкого ЭВА. 2200 umbro1.jpg 2
3 Кеды NIKE SB CHECK SOLAR Nike 7 Кеды Nike "SB CHECK SOLAR" выполнены из натурального велюра. Детали: шнурки с наконечниками; текстильная внутренняя отделка; съемная легкая и амортизирующая стелька; резиновая подошва; контрастный логотип. 4190 solar_nike1.jpg 2
\.
--
-- Name: product_product_id_seq; Type: SEQUENCE SET; Schema: public; Owner: alexander
--
SELECT pg_catalog.setval('product_product_id_seq', 19, true);
--
-- Name: auth_group_name_key; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY auth_group
ADD CONSTRAINT auth_group_name_key UNIQUE (name);
--
-- Name: auth_group_permissions_group_id_0cd325b0_uniq; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY auth_group_permissions
ADD CONSTRAINT auth_group_permissions_group_id_0cd325b0_uniq UNIQUE (group_id, permission_id);
--
-- Name: auth_group_permissions_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY auth_group_permissions
ADD CONSTRAINT auth_group_permissions_pkey PRIMARY KEY (id);
--
-- Name: auth_group_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY auth_group
ADD CONSTRAINT auth_group_pkey PRIMARY KEY (id);
--
-- Name: auth_permission_content_type_id_01ab375a_uniq; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY auth_permission
ADD CONSTRAINT auth_permission_content_type_id_01ab375a_uniq UNIQUE (content_type_id, codename);
--
-- Name: auth_permission_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY auth_permission
ADD CONSTRAINT auth_permission_pkey PRIMARY KEY (id);
--
-- Name: auth_user_groups_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY auth_user_groups
ADD CONSTRAINT auth_user_groups_pkey PRIMARY KEY (id);
--
-- Name: auth_user_groups_user_id_94350c0c_uniq; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY auth_user_groups
ADD CONSTRAINT auth_user_groups_user_id_94350c0c_uniq UNIQUE (user_id, group_id);
--
-- Name: auth_user_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY auth_user
ADD CONSTRAINT auth_user_pkey PRIMARY KEY (id);
--
-- Name: auth_user_user_permissions_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY auth_user_user_permissions
ADD CONSTRAINT auth_user_user_permissions_pkey PRIMARY KEY (id);
--
-- Name: auth_user_user_permissions_user_id_14a6b632_uniq; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY auth_user_user_permissions
ADD CONSTRAINT auth_user_user_permissions_user_id_14a6b632_uniq UNIQUE (user_id, permission_id);
--
-- Name: auth_user_username_key; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY auth_user
ADD CONSTRAINT auth_user_username_key UNIQUE (username);
--
-- Name: django_admin_log_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY django_admin_log
ADD CONSTRAINT django_admin_log_pkey PRIMARY KEY (id);
--
-- Name: django_content_type_app_label_76bd3d3b_uniq; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY django_content_type
ADD CONSTRAINT django_content_type_app_label_76bd3d3b_uniq UNIQUE (app_label, model);
--
-- Name: django_content_type_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY django_content_type
ADD CONSTRAINT django_content_type_pkey PRIMARY KEY (id);
--
-- Name: django_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY django_migrations
ADD CONSTRAINT django_migrations_pkey PRIMARY KEY (id);
--
-- Name: django_session_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY django_session
ADD CONSTRAINT django_session_pkey PRIMARY KEY (session_key);
--
-- Name: product_application_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY product_application
ADD CONSTRAINT product_application_pkey PRIMARY KEY (id);
--
-- Name: product_cart_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY product_cart
ADD CONSTRAINT product_cart_pkey PRIMARY KEY (id);
--
-- Name: product_category_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY product_category
ADD CONSTRAINT product_category_pkey PRIMARY KEY (id);
--
-- Name: product_imageproduct_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY product_imageproduct
ADD CONSTRAINT product_imageproduct_pkey PRIMARY KEY (id);
--
-- Name: product_product_pkey; Type: CONSTRAINT; Schema: public; Owner: alexander; Tablespace:
--
ALTER TABLE ONLY product_product
ADD CONSTRAINT product_product_pkey PRIMARY KEY (id);
--
-- Name: auth_group_name_a6ea08ec_like; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX auth_group_name_a6ea08ec_like ON auth_group USING btree (name varchar_pattern_ops);
--
-- Name: auth_group_permissions_0e939a4f; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX auth_group_permissions_0e939a4f ON auth_group_permissions USING btree (group_id);
--
-- Name: auth_group_permissions_8373b171; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX auth_group_permissions_8373b171 ON auth_group_permissions USING btree (permission_id);
--
-- Name: auth_permission_417f1b1c; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX auth_permission_417f1b1c ON auth_permission USING btree (content_type_id);
--
-- Name: auth_user_groups_0e939a4f; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX auth_user_groups_0e939a4f ON auth_user_groups USING btree (group_id);
--
-- Name: auth_user_groups_e8701ad4; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX auth_user_groups_e8701ad4 ON auth_user_groups USING btree (user_id);
--
-- Name: auth_user_user_permissions_8373b171; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX auth_user_user_permissions_8373b171 ON auth_user_user_permissions USING btree (permission_id);
--
-- Name: auth_user_user_permissions_e8701ad4; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX auth_user_user_permissions_e8701ad4 ON auth_user_user_permissions USING btree (user_id);
--
-- Name: auth_user_username_6821ab7c_like; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX auth_user_username_6821ab7c_like ON auth_user USING btree (username varchar_pattern_ops);
--
-- Name: django_admin_log_417f1b1c; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX django_admin_log_417f1b1c ON django_admin_log USING btree (content_type_id);
--
-- Name: django_admin_log_e8701ad4; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX django_admin_log_e8701ad4 ON django_admin_log USING btree (user_id);
--
-- Name: django_session_de54fa62; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX django_session_de54fa62 ON django_session USING btree (expire_date);
--
-- Name: django_session_session_key_c0390e0f_like; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX django_session_session_key_c0390e0f_like ON django_session USING btree (session_key varchar_pattern_ops);
--
-- Name: product_application_9bea82de; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX product_application_9bea82de ON product_application USING btree (product_id);
--
-- Name: product_cart_9bea82de; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX product_cart_9bea82de ON product_cart USING btree (product_id);
--
-- Name: product_imageproduct_9bea82de; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX product_imageproduct_9bea82de ON product_imageproduct USING btree (product_id);
--
-- Name: product_product_b583a629; Type: INDEX; Schema: public; Owner: alexander; Tablespace:
--
CREATE INDEX product_product_b583a629 ON product_product USING btree (category_id);
--
-- Name: auth_group_permiss_permission_id_84c5c92e_fk_auth_permission_id; Type: FK CONSTRAINT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY auth_group_permissions
ADD CONSTRAINT auth_group_permiss_permission_id_84c5c92e_fk_auth_permission_id FOREIGN KEY (permission_id) REFERENCES auth_permission(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: auth_group_permissions_group_id_b120cbf9_fk_auth_group_id; Type: FK CONSTRAINT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY auth_group_permissions
ADD CONSTRAINT auth_group_permissions_group_id_b120cbf9_fk_auth_group_id FOREIGN KEY (group_id) REFERENCES auth_group(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: auth_permiss_content_type_id_2f476e4b_fk_django_content_type_id; Type: FK CONSTRAINT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY auth_permission
ADD CONSTRAINT auth_permiss_content_type_id_2f476e4b_fk_django_content_type_id FOREIGN KEY (content_type_id) REFERENCES django_content_type(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: auth_user_groups_group_id_97559544_fk_auth_group_id; Type: FK CONSTRAINT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY auth_user_groups
ADD CONSTRAINT auth_user_groups_group_id_97559544_fk_auth_group_id FOREIGN KEY (group_id) REFERENCES auth_group(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: auth_user_groups_user_id_6a12ed8b_fk_auth_user_id; Type: FK CONSTRAINT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY auth_user_groups
ADD CONSTRAINT auth_user_groups_user_id_6a12ed8b_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: auth_user_user_per_permission_id_1fbb5f2c_fk_auth_permission_id; Type: FK CONSTRAINT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY auth_user_user_permissions
ADD CONSTRAINT auth_user_user_per_permission_id_1fbb5f2c_fk_auth_permission_id FOREIGN KEY (permission_id) REFERENCES auth_permission(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: auth_user_user_permissions_user_id_a95ead1b_fk_auth_user_id; Type: FK CONSTRAINT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY auth_user_user_permissions
ADD CONSTRAINT auth_user_user_permissions_user_id_a95ead1b_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: django_admin_content_type_id_c4bce8eb_fk_django_content_type_id; Type: FK CONSTRAINT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY django_admin_log
ADD CONSTRAINT django_admin_content_type_id_c4bce8eb_fk_django_content_type_id FOREIGN KEY (content_type_id) REFERENCES django_content_type(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: django_admin_log_user_id_c564eba6_fk_auth_user_id; Type: FK CONSTRAINT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY django_admin_log
ADD CONSTRAINT django_admin_log_user_id_c564eba6_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: product_application_product_id_10854a46_fk_product_product_id; Type: FK CONSTRAINT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY product_application
ADD CONSTRAINT product_application_product_id_10854a46_fk_product_product_id FOREIGN KEY (product_id) REFERENCES product_product(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: product_cart_product_id_ab32bd2e_fk_product_product_id; Type: FK CONSTRAINT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY product_cart
ADD CONSTRAINT product_cart_product_id_ab32bd2e_fk_product_product_id FOREIGN KEY (product_id) REFERENCES product_product(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: product_imageproduct_product_id_c3beed8b_fk_product_product_id; Type: FK CONSTRAINT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY product_imageproduct
ADD CONSTRAINT product_imageproduct_product_id_c3beed8b_fk_product_product_id FOREIGN KEY (product_id) REFERENCES product_product(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: product_product_category_id_0c725779_fk_product_category_id; Type: FK CONSTRAINT; Schema: public; Owner: alexander
--
ALTER TABLE ONLY product_product
ADD CONSTRAINT product_product_category_id_0c725779_fk_product_category_id FOREIGN KEY (category_id) REFERENCES product_category(id) DEFERRABLE INITIALLY DEFERRED;
--
-- Name: public; Type: ACL; Schema: -; Owner: postgres
--
REVOKE ALL ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON SCHEMA public FROM postgres;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO PUBLIC;
--
-- PostgreSQL database dump complete
--
<file_sep>from django.shortcuts import render, render_to_response
from django.template import Context
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator
from django.db.models import F, Sum
import json
from .models import Product, ImageProduct, Cart, Application
from .forms import Ordering
from Shop.utils import base_args
# Create your views here.
def home(request, page=1, filt='all'):
args = base_args(request)
if request.method == 'GET' and filt != 'all':
category = Product.objects.filter(category__name=filt)
current_page = Paginator(category, 12)
args['products'] = current_page.page(page)
else:
all_products = Product.objects.all()
current_page = Paginator(all_products, 12)
args['products'] = current_page.page(page)
return render(request, 'product/home.html', args)
def prod_page(request, pk):
args = base_args(request)
if request.method == 'POST':
if request.POST['operation'] == 'add':
user_ip = request.META['REMOTE_ADDR']
prod = Product.objects.get(pk=pk)
if Cart.objects.filter(user_ip=user_ip, product=prod).exists():
cart = Cart.objects.get(user_ip=user_ip, product=prod)
cart.count += 1
cart.save()
else:
Cart(product=prod, price=prod.price, user_ip=user_ip).save()
return HttpResponseRedirect(reverse('product:prod_page', args=(pk,)))
args['product'] = Product.objects.get(pk=pk)
args['gallery'] = ImageProduct.objects.filter(product=args['product'])
return render(request, 'product/prod_page.html', args)
def cart(request):
args = base_args(request)
form = Ordering(request.POST or None)
ip = request.META['REMOTE_ADDR']
orders = Cart.objects.filter(user_ip=ip)
if form.is_valid():
fio = form.cleaned_data['fio']
phone = form.cleaned_data['phone']
mail = form.cleaned_data['mail']
for order in orders:
count = order.count
price = order.product.price
Application(fio=fio, phone=phone, mail=mail,
product=order.product, count=count, sum_order=count*price).save()
Cart.objects.filter(user_ip=ip).delete()
return HttpResponseRedirect(reverse('product:cart', args=()))
if request.method == 'POST':
try:
if 'del' in request.POST:
sels = request.POST.getlist('select')
if sels:
for sel in sels:
Cart.objects.get(user_ip=ip, product__pk=sel).delete()
return HttpResponseRedirect(reverse('product:cart', args=()))
if 'tov_count' in request.POST and 'tov_pk' in request.POST:
count = request.POST['tov_count']
pk = request.POST['tov_pk']
order = Cart.objects.get(user_ip=ip, product__pk=pk)
order.count = count
order.save()
ords = list(Cart.objects.filter(user_ip=ip))
ord_sum = 0
for o in ords:
ord_sum += o.price*o.count
args['sum'] = ord_sum
return HttpResponse(json.dumps({"sum": ord_sum}), content_type="application/json")
except KeyError: print('ОШИБКА')
ords = list(Cart.objects.filter(user_ip=ip))
ord_sum = 0
for o in ords:
ord_sum += o.price*o.count
args['sum'] = ord_sum
args['form'] = Ordering()
args['orders'] = orders
return render(request, 'product/cart.html', args)
<file_sep>from product.models import Cart
from django.template import Context
def base_args(request):
args = {}
try:
ip = request.META['REMOTE_ADDR']
cart_ords = list(Cart.objects.filter(user_ip=ip))
args['count'] = len(cart_ords)
except: pass
return Context(args)
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-24 09:10
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('product', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='imageproduct',
name='product',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='product.Product'),
),
migrations.AlterField(
model_name='imageproduct',
name='name',
field=models.CharField(blank=True, max_length=100, null=True),
),
migrations.AlterField(
model_name='imageproduct',
name='path',
field=models.ImageField(blank=True, upload_to=''),
),
migrations.AlterField(
model_name='product',
name='category',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='product.Category'),
),
migrations.AlterField(
model_name='product',
name='description',
field=models.TextField(blank=True, null=True),
),
]
<file_sep>from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Product(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length=50)
count = models.IntegerField(default=0)
description = models.TextField(blank=True)
price = models.FloatField(default=0.0)
main_img = models.ImageField(blank=True)
def __str__(self):
return self.name
class ImageProduct(models.Model):
product = models.ForeignKey(Product, blank=True, null=True)
path = models.ImageField(blank=True)
name = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.name
class Cart(models.Model):
product = models.ForeignKey(Product)
price = models.FloatField()
count = models.IntegerField(default=1)
user_ip = models.CharField(max_length=50)
def __str__(self):
return self.user_ip
class Application(models.Model):
fio = models.CharField(max_length=100)
phone = models.CharField(max_length=50)
mail = models.EmailField(blank=True)
product = models.ForeignKey(Product)
count = models.IntegerField()
sum_order = models.FloatField()
datetime = models.DateTimeField(auto_now=True)
def __str__(self):
return '%s (%s)' % (self.mail, self.datetime)
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-24 12:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0005_auto_20170324_1158'),
]
operations = [
migrations.AlterField(
model_name='imageproduct',
name='path',
field=models.ImageField(blank=True, upload_to=''),
),
migrations.AlterField(
model_name='product',
name='main_img',
field=models.ImageField(blank=True, upload_to=''),
),
]
<file_sep>from django import forms
class Ordering(forms.Form):
fio = forms.CharField(max_length=100)
phone = forms.CharField(max_length=50)
mail = forms.EmailField(required=False)
<file_sep>{%extends 'product/base.html'%}
{%load static%}
{%block content%}
<div class="row">
{%if orders%}
<div class="col-md-7">
<form method="POST" action="{%url 'product:cart'%}">
{%csrf_token%}
<div class="del_ord"><input type="submit" name="del" value="удалить"></div>
{%for order in orders%}
<div class="row row_product">
<div class="col-md-1">
<input type="checkbox" name="select" value="{{order.product.pk}}">
</div>
<div class="col-md-2">
<img class="cart_img" src="{{BASE_URL}}/media/{{order.product.main_img}}">
</div>
<div class="col-md-4">{{order.product.name}}<br>{{order.product.price}} руб.</div>
<div class="col-md-122 count_div"><span>кол-во: </span><input min="1" name="{{order.product.pk}}" class="count_pr" type="number" value="{{order.count}}"></div>
</div>
{%endfor%}
</form>
</div>
<div class="col-md-5">
<form action="{%url 'product:cart'%}" method="POST" class="send_order">
{%csrf_token%}
<label for="fio">Ф.И.О</label><br>
{{form.fio}}<br>
<label for="phone">Телефон</label><br>
{{form.phone}}<br>
<label for="mail">Эл. почта</label><br>
{{form.mail}}<br><br>
<input type="submit" value="оформить заказ">
</form>
<div class="res">общая сумма: <span id="res">{{sum}}</span> руб.</div>
</div>
{%else%}
<h2>Корзина пуста<h2>
{%endif%}
</div>
{%endblock%}
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-24 11:58
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('product', '0004_auto_20170324_1141'),
]
operations = [
migrations.AlterField(
model_name='imageproduct',
name='path',
field=models.ImageField(blank=True, upload_to='media'),
),
migrations.AlterField(
model_name='product',
name='main_img',
field=models.ImageField(blank=True, upload_to='media'),
),
]
<file_sep>from django.conf.urls import url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from django.conf import settings
from . import views
app_name = 'product'
urlpatterns = [
url(r'^cart/$', views.cart, name='cart'),
url(r'^category/(?P<filt>\w+)/$', views.home, name='home_filt'),
url(r'^page/(?P<page>\d+)/$', views.home, name='home_pag'),
url(r'^$', views.home, name='home'),
url(r'product/(?P<pk>\d+)/$', views.prod_page, name="prod_page"),
]
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns() + static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT
)
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-25 03:49
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('product', '0006_auto_20170324_1200'),
]
operations = [
migrations.CreateModel(
name='Application',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('fio', models.CharField(max_length=100)),
('phone', models.CharField(max_length=50)),
('mail', models.EmailField(blank=True, max_length=254)),
('count', models.IntegerField()),
('sum_order', models.FloatField()),
('datetime', models.DateTimeField(auto_now=True)),
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='product.Product')),
],
),
migrations.CreateModel(
name='Cart',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('price', models.FloatField()),
('count', models.IntegerField()),
('user_ip', models.CharField(max_length=50)),
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='product.Product')),
],
),
]
<file_sep>from django.contrib import admin
from .models import Category, Product, ImageProduct, Cart, Application
# Register your models here.
class ApplicationAdmin(admin.ModelAdmin):
readonly_fields = ('fio', 'phone', 'mail', 'product', 'count', 'sum_order',)
admin.site.register(Category)
admin.site.register(Product)
admin.site.register(ImageProduct)
admin.site.register(Application, ApplicationAdmin)
|
c4d66c8e152d71cb6869749e5b13cc222e5aa15a
|
[
"SQL",
"Python",
"HTML"
] | 12
|
SQL
|
ayanin/Shop
|
09824826a4b16d8ecf67042d52fac2344552ef38
|
4b87ad2dacfe30a0854774fc888d32cf5a6031d5
|
refs/heads/master
|
<repo_name>imclab/visdat<file_sep>/R/vis_compare.R
#' compare two dataframes and see where they are different.
#'
#' \code{vis_compare}, like the other vis_* families, gives an at-a-glance ggplot of a particular feature. In this case, it is the difference between two dataframes. This function has not been implemented yet, but this serves as a note of how it might work. It would be very similar to vis_miss, where you basically colouring cells according to "match" and "non-match". The code for this would be pretty crazy simple. `x <- 1:10; y <- c(1:5, 10:14) ;x == y` returns ` [1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE` Here black could indicate a match, and white a non match. One of the challenges with this would be cases where the datasets are different dimensions. One option could be to return as a message the columns that are not in the same dataset. Matching rows could be done by row number, and just lopping off the trailing ones and spitting out a note. Then, if the user wants, it could use an ID/key to match by.
#'
#' @param x a data.frame
#'
#' @param sort_match logical TRUE/FALSE. TRUE arranges the columns in order of most matches.
#'
#'
# NOTE: This function is not yet complete, and is unexported as it is still mostly in the idea phase
vis_compare <- function(x,
sort_match = FALSE){
# make a TRUE/FALSE matrix of the data.
# This tells us whether it is missing (true) or not (false)
x.na <- is.na(x)
# But we would want some sort of equivalent function where it
if (sort_match == TRUE) {
# arrange by the columns with the highest missingness
# code inspired from https://r-forge.r-project.org/scm/viewvc.php/pkg/R/missing.pattern.plot.R?view=markup&root=mi-dev
# get the order of columns with highest missingness
na_sort <- order(colSums(is.na(x)), decreasing = TRUE)
# get the names of those columns
col_order_index <- names(x)[na_sort]
# original code was a bit slower:
#
# col_order_index <-
# x.na %>%
# as.data.frame %>%
# dplyr::summarise_each(funs(mean)) %>%
# names
} else {
col_order_index <- names(x)
}
# Arranged data by dendrogram order index
d <- x.na %>%
as.data.frame %>%
mutate(rows = row_number()) %>%
# gather the variables together for plotting
# here we now have a column of the row number (row),
# then the variable(variables),
# then the contents of that variable (value)
tidyr::gather_(key_col = "variables",
value_col = "valueType",
gather_cols = names(.)[-length(.)])
d$value <- tidyr::gather_(x, "variables", "value", names(x))$value
# then we plot it
ggplot(data = d,
aes_string(x = "variables",
y = "rows",
# text assists with plotly mouseover
text = "value")) +
geom_raster(aes_string(fill = "valueType")) +
# change the colour, so that missing is grey, present is black
scale_fill_grey(name = "",
labels = c("Present",
"Missing")) +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45,
vjust = 1,
hjust = 1)) +
labs(x = "Variables in Data",
y = "Observations") +
scale_x_discrete(limits = col_order_index)
# Thanks to http://www.markhneedham.com/blog/2015/02/27/rggplot-controlling-x-axis-order/
# For the tip on using scale_x_discrete
}
|
356dfc9cc26a553cc9d6d0f2f08f01961a503b59
|
[
"R"
] | 1
|
R
|
imclab/visdat
|
b24cecc2865038686e058c15c3785415d92b2e55
|
7516974d6a6e0b1d8fd8f7a284845f443c110778
|
refs/heads/master
|
<file_sep>import React, {useState} from 'react'
import { View, Text, Image, StyleSheet, FlatList, ScrollView, SafeAreaView } from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome'
import Icon1 from 'react-native-vector-icons/EvilIcons'
import Swiper from 'react-native-swiper'
import HeaderTop from "./header_1"
const DATA1 = [
{
id: "1",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://product.hstatic.net/1000075078/product/caphesuada_ba1ebc3227b34e97b5bb1e711cb3676f_large.jpg",
date: "23/08"
},
{
id: "2",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://product.hstatic.net/1000075078/product/caphesuada_ba1ebc3227b34e97b5bb1e711cb3676f_large.jpg",
date: "23/08"
},
{
id: "3",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://product.hstatic.net/1000075078/product/caphesuada_ba1ebc3227b34e97b5bb1e711cb3676f_large.jpg",
date: "23/08"
},
{
id: "4",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://product.hstatic.net/1000075078/product/caphesuada_ba1ebc3227b34e97b5bb1e711cb3676f_large.jpg",
date: "23/08"
},
{
id: "5",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://product.hstatic.net/1000075078/product/caphesuada_ba1ebc3227b34e97b5bb1e711cb3676f_large.jpg",
date: "23/08"
},
{
id: "6",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://product.hstatic.net/1000075078/product/caphesuada_ba1ebc3227b34e97b5bb1e711cb3676f_large.jpg",
date: "23/08"
},
{
id: "7",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://product.hstatic.net/1000075078/product/caphesuada_ba1ebc3227b34e97b5bb1e711cb3676f_large.jpg",
date: "23/08"
},
{
id: "8",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://product.hstatic.net/1000075078/product/caphesuada_ba1ebc3227b34e97b5bb1e711cb3676f_large.jpg",
date: "23/08"
},
{
id: "9",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://product.hstatic.net/1000075078/product/caphesuada_ba1ebc3227b34e97b5bb1e711cb3676f_large.jpg",
date: "23/08"
},
{
id: "10",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://product.hstatic.net/1000075078/product/caphesuada_ba1ebc3227b34e97b5bb1e711cb3676f_large.jpg",
date: "23/08"
},
];
const DATA2 = [
{
id: "1",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/article/bannerhome-freeship_dec45eaf64c84bd693884264423d2064_grande.jpg",
date: "23/08"
},
{
id: "2",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/article/bannerhome-freeship_dec45eaf64c84bd693884264423d2064_grande.jpg",
date: "23/08"
},
{
id: "3",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/article/bannerhome-freeship_dec45eaf64c84bd693884264423d2064_grande.jpg",
date: "23/08"
},
{
id: "4",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/article/bannerhome-freeship_dec45eaf64c84bd693884264423d2064_grande.jpg",
date: "23/08"
},
{
id: "5",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/article/bannerhome-freeship_dec45eaf64c84bd693884264423d2064_grande.jpg",
date: "23/08"
},
{
id: "6",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/article/bannerhome-freeship_dec45eaf64c84bd693884264423d2064_grande.jpg",
date: "23/08"
},
{
id: "7",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/article/bannerhome-freeship_dec45eaf64c84bd693884264423d2064_grande.jpg",
date: "23/08"
},
{
id: "8",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/article/bannerhome-freeship_dec45eaf64c84bd693884264423d2064_grande.jpg",
date: "23/08"
},
{
id: "9",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/article/bannerhome-freeship_dec45eaf64c84bd693884264423d2064_grande.jpg",
date: "23/08"
},
{
id: "10",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/article/bannerhome-freeship_dec45eaf64c84bd693884264423d2064_grande.jpg",
date: "23/08"
},
];
const DATA3 = [
{
id: "1",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/file/28827277_2051622368445112_5970865629524999462_o_2x_grande.jpg",
date: "23/08"
},
{
id: "2",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/file/28827277_2051622368445112_5970865629524999462_o_2x_grande.jpg",
date: "23/08"
},
{
id: "3",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/file/28827277_2051622368445112_5970865629524999462_o_2x_grande.jpg",
date: "23/08"
},
{
id: "4",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/file/28827277_2051622368445112_5970865629524999462_o_2x_grande.jpg",
date: "23/08"
},
{
id: "5",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/file/28827277_2051622368445112_5970865629524999462_o_2x_grande.jpg",
date: "23/08"
},
{
id: "6",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/file/28827277_2051622368445112_5970865629524999462_o_2x_grande.jpg",
date: "23/08"
},
{
id: "7",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/file/28827277_2051622368445112_5970865629524999462_o_2x_grande.jpg",
date: "23/08"
},
{
id: "8",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/file/28827277_2051622368445112_5970865629524999462_o_2x_grande.jpg",
date: "23/08"
},
{
id: "9",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/file/28827277_2051622368445112_5970865629524999462_o_2x_grande.jpg",
date: "23/08"
},
{
id: "10",
title: "Mừng Tuổi Mới, Nhà Mời 50%(23/08 - 29/08)",
image: "https://file.hstatic.net/1000075078/file/28827277_2051622368445112_5970865629524999462_o_2x_grande.jpg",
date: "23/08"
},
];
const renderItem=({item})=>{
return(
<View style={style.list_item}>
<Image style={style.list_item_image} source={{uri: item.image}}/>
<View style={style.list_item_text}>
<Text style={style.list_item_text_tittle}>{item.title}</Text>
<View style={{flexDirection: "row", justifyContent: "space-between", alignItems: "center", width: "40%"}}><Icon name="calendar" size={20} color="black" /><Text style={style.list_item_text_date}>{item.date}</Text></View>
</View>
</View>
)
}
const HeaderFooter=()=>{
return(
<View style={style.HeaderFooter}>
<Image style={style.HeaderFooter_image} source={{uri: "https://cdn.pixabay.com/photo/2021/08/22/15/48/nature-6565499_960_720.jpg"}}/>
<View style={style.HeaderFooter_text}>
<View style={style.HeaderFooter_text_frame}>
<Image style={{width: "100%", height: 300, borderRadius: 15,}} source={{uri: "https://cdn.pixabay.com/photo/2015/10/02/15/00/diary-968592_960_720.jpg"}}></Image>
<View style={{position: "absolute", top: 15, left: 15}} >
<Text style={{fontSize: 25, color: "white", textTransform: "uppercase", fontWeight: "500", marginBottom: 5, }}><NAME></Text>
<View style={{flexDirection: "row", width: "40%", justifyContent: "space-between", alignItems: "center"}} >
<Text style={{fontSize: 15, color: "white", textTransform: "uppercase", fontWeight: "500", }}>0 Bean</Text>
<Text style={{fontSize: 20, color: "white", textTransform: "uppercase", fontWeight: "500", }} >-</Text>
<Text style={{fontSize: 15, color: "white", textTransform: "uppercase", fontWeight: "500", }} >Mới</Text>
</View>
</View>
<Text style={{width: 120, height: 40, lineHeight: 40, textAlign: "center", color: "white", backgroundColor: "transparent", textTransform: "uppercase", fontWeight: "600", position: "absolute", top: 0, right: 5, borderColor: "white", borderWidth: 1}}><Icon1 name="chevron-down" size={25} color="white" /> Tích điểm</Text>
</View>
</View>
</View>
)
}
export default function home() {
const [dataList, setdataList]=useState(DATA1);
const MainHeader=()=>{
return(
<View>
<HeaderFooter/>
<View style={[style.mainHeader]}>
<View style={style.mainHeader1}>
<View style={[style.mainHeader1_item, {borderRightWidth: 1}]}>
<Image style={style.mainHeader1_item_image} source={{uri: "https://cdn.ntlogistics.vn/images/NTX/new_images/danh-gia-shipper-giao-hang-nhanh-qua-viec-dam-bao-an-toan-hang-hoa.jpg"}}/>
<Text style={style.mainHeader1_item_text}>Giao hàng </Text>
</View>
<View style={style.mainHeader1_item}>
<Image style={style.mainHeader1_item_image} source={{uri: "https://cdn.ntlogistics.vn/images/NTX/new_images/danh-gia-shipper-giao-hang-nhanh-qua-viec-dam-bao-an-toan-hang-hoa.jpg"}}/>
<Text style={style.mainHeader1_item_text}>Mang đi</Text>
</View>
</View>
<View style={style.mainHeader2}>
<Swiper style={style.wrapper} showsButtons={true} autoplay={true} autoplayTimeout={3}>
<View style={style.slide}>
<Image style={style.slideImage} source={{uri: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg"}}/>
</View>
<View style={style.slide}>
<Image style={style.slideImage} source={{uri: "https://file.hstatic.net/1000075078/file/tch-hai_ba_trung_398a9c92be4a4c46885d0a7bc2a9c456_1024x1024.jpg"}}/>
</View>
<View style={style.slide}>
<Image style={style.slideImage} source={{uri: "https://file.hstatic.net/1000075078/file/1212-tch-p4_04feaa750de14848b25e19fea8d46135_1024x1024.jpg"}}/>
</View>
<View style={style.slide}>
<Image style={style.slideImage} source={{uri: "https://file.hstatic.net/1000075078/file/3e0a8783_master.jpg"}}/>
</View>
<View style={style.slide}>
<Image style={style.slideImage} source={{uri: "https://image.bnews.vn/MediaUpload/Org/2021/01/23/the-coffee-house2.jpg"}}/>
</View>
</Swiper>
</View>
<Text style={style.mainHeader3_tittle} >Khám phá thêm</Text>
<View style={style.MainHeader4}>
<View style={[style.MainHeader4_item, style.MainHeader4_item_s]} >
<Text style={[style.MainHeader4_item_text, {color: "#ff5e00"}]}>Ưu đãi đặc biệt</Text>
</View>
<View style={style.MainHeader4_item} >
<Text style={style.MainHeader4_item_text} onPress={()=>{
setdataList(DATA2);
}}>Cập nhập từ nhà</Text>
</View>
<View style={style.MainHeader4_item} >
<Text onPress={()=>{
setdataList(DATA3);
}} style={style.MainHeader4_item_text}>#CoffeeLover</Text>
</View>
</View>
</View>
</View>
)
}
return (
<SafeAreaView style={{height: "100%"}}>
<HeaderTop name={"<NAME>"}/>
<View style={style.container}>
<FlatList
data={dataList}
renderItem={renderItem}
keyExtractor={(item) => item.id}
numColumns={2}
ListHeaderComponent={MainHeader}
/>
</View>
</SafeAreaView>
)
}
const style =StyleSheet.create({
container: {
paddingLeft: 10,
paddingRight: 10,
height: "100%",
paddingBottom: 120,
},
// làm phần main header
mainHeader: {
paddingTop: 15,
},
mainHeader1: {
width: "100%",
borderWidth: 1,
borderRadius: 15,
backgroundColor: "white",
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
padding: 15,
},
mainHeader1_item: {
width: "50%",
justifyContent: "center",
alignItems: "center",
},
mainHeader1_item_image: {
width: 70,
height: 50,
resizeMode: "cover",
},
mainHeader1_item_text:{
marginTop: 10,
fontSize: 15,
},
mainHeader2: {
width: "100%",
height: 250,
marginTop: 20,
borderRadius: 10,
},
wrapper: {
borderRadius: 10,
},
slide: {
borderRadius: 20,
},
slideImage: {
width: "100%",
height: 250,
borderRadius: 20,
},
mainHeader3_tittle: {
fontSize: 20,
marginTop: 20,
fontWeight: "bold",
marginBottom: 20,
},
MainHeader4: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
flexWrap: "wrap",
marginBottom: 10,
},
MainHeader4_item: {
width: "31%",
justifyContent: "center",
alignItems: "center",
padding: 5,
},
MainHeader4_item_s: {
borderRadius: 10,
backgroundColor: "#8080804f",
},
MainHeader4_item_text: {
fontSize: 15,
fontWeight: "bold",
},
list_item: {
width: "45%",
margin: 7,
},
list_item_image: {
width: "100%",
height: 100,
},
list_item_text: {
marginTop: 7,
},
list_item_text_tittle: {
fontSize: 17,
fontWeight: "bold",
marginBottom: 7,
},
list_item_text_date: {
fontSize: 13,
color: "gray",
marginLeft: 10,
},
// làm phần headerFooter
HeaderFooter: {
width: "100%",
height: 400,
position: "relative",
},
HeaderFooter_image: {
width: "100%",
height: 400,
},
HeaderFooter_text: {
width: "90%",
height: 300,
position: "absolute",
top: 50,
left: 20,
},
HeaderFooter_text_frame: {
position: "relative",
}
})<file_sep>import React from 'react'
import { View, Text, SafeAreaView, StyleSheet, TouchableOpacity, ScrollView } from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons';
import Icon1 from 'react-native-vector-icons/Feather';
import Header from "./header_1"
export default function diffirent() {
return (
<SafeAreaView>
<Header name={"Khác"}/>
<ScrollView>
<View style={[Style.container, Style.main]}>
<View style={Style.main_item}>
<Text style={[Style.textTittle, Style.main_tittle]}>Tiện tích</Text>
<TouchableOpacity style={Style.main_item_1}>
<Icon style={Style.main_item_icon} name="document-text-outline" size={30} color="orange" />
<Text style={Style.text}>Lịch sử đơn hàng</Text>
</TouchableOpacity>
<View style={Style.row}>
<TouchableOpacity style={[Style.main_item_1, Style.main_item_2]}>
<Icon style={[Style.main_item_icon, Style.main_item_icon_border_music]} name="musical-note" size={30} color="green" />
<Text style={Style.text}>Nhạc đang phát</Text>
</TouchableOpacity>
<TouchableOpacity style={[Style.main_item_1, Style.main_item_2]}>
<Icon style={Style.main_item_icon} name="document-text-outline" size={30} color="purple" />
<Text style={Style.text}>Điều khoản</Text>
</TouchableOpacity>
</View>
</View>
<View style={Style.main_item}>
<Text style={[Style.textTittle, Style.main_tittle]}>Hỗ trợ</Text>
<View style={Style.main_item_3}>
<TouchableOpacity style={[Style.row, Style.main_item_3_border, Style.main_item_3_item]}>
<Text style={[Style.text, Style.main_tittle]}> <Icon name="star-outline" size={20} color="black" /> Đánh giá đơn hàng</Text>
<Icon name="chevron-forward" size={30} color="black" />
</TouchableOpacity>
<TouchableOpacity style={[Style.row,Style.main_item_3_item]}>
<Text style={[Style.text, Style.main_tittle]}> <Icon1 name="message-square" size={20} color="black" /> Liên hệ góp ý</Text>
<Icon name="chevron-forward" size={30} color="black" />
</TouchableOpacity>
</View>
</View>
<View style={Style.main_item}>
<Text style={[Style.textTittle, Style.main_tittle]}>Tiện tích</Text>
<View style={Style.main_item_3}>
<TouchableOpacity style={[Style.row, Style.main_item_3_border, Style.main_item_3_item]}>
<Text style={[Style.text, Style.main_tittle]}> <Icon1 name="user" size={20} color="black" /> Thông tin cá nhân</Text>
<Icon name="chevron-forward" size={30} color="black" />
</TouchableOpacity>
<TouchableOpacity style={[Style.row,Style.main_item_3_item,Style.main_item_3_border]}>
<Text style={[Style.text, Style.main_tittle]}> <Icon name="map-outline" size={20} color="black" /> Địa chỉ đã lưu</Text>
<Icon name="chevron-forward" size={30} color="black" />
</TouchableOpacity>
<TouchableOpacity style={[Style.row,Style.main_item_3_item, Style.main_item_3_border]}>
<Text style={[Style.text, Style.main_tittle]}> <Icon name="settings-outline" size={20} color="black" /> Cài đặt</Text>
<Icon name="chevron-forward" size={30} color="black" />
</TouchableOpacity>
<TouchableOpacity style={[Style.row,Style.main_item_3_item]}>
<Text style={[Style.text, Style.main_tittle]}> <Icon name="log-in-outline" size={20} color="black" /> Đăng nhập</Text>
<Icon name="chevron-forward" size={30} color="black" />
</TouchableOpacity>
</View>
</View>
</View>
</ScrollView>
</SafeAreaView>
)
}
const Style =StyleSheet.create({
container: {
paddingLeft: 10,
paddingRight: 10,
},
textTittle: {
fontSize: 25,
fontWeight: "700",
},
text: {
fontSize: 17,
},
row: {
display: "flex",
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
},
// làm phần main
main: {
backgroundColor: "#80808020",
paddingBottom: 100,
},
main_tittle: {
margin: 7,
},
main_item: {
marginBottom: 20,
},
main_item_1: {
margin: 7,
backgroundColor: "white",
padding: 15,
borderRadius: 10,
},
main_item_icon: {
marginBottom: 20,
},
main_item_2: {
width: "45%",
},
main_item_3: {
backgroundColor: "white",
padding: 15,
borderRadius: 10,
},
main_item_3_border:{
borderBottomWidth:1,
borderColor: "#80808050"
},
main_item_3_item: {
padding: 10,
},
main_item_icon_border_music: {
borderWidth:3,
width: 35,
height: 35,
textAlign: "center",
lineHeight: 35,
borderColor: "green",
}
});
<file_sep>import React, { useState } from 'react'
import { View, Text, Image, TextInput, FlatList, StyleSheet,SafeAreaView, ScrollView, TouchableOpacity } from 'react-native'
import Ionicons from 'react-native-vector-icons/Ionicons';
import Store from "./store"
const Header = () => {
return (
<View style={style.header}>
<View style={style.header1}>
<Image style={style.header1_image} source={{ uri: "https://lh3.googleusercontent.com/iJVlSfvuDXmlijPsWrPLiq7NvrFdEq0Z4b2ljH26UTUIYfURe9kIAQKgS6TKUjS64YmL" }}></Image>
<View style={style.header1_text}>
<Text style={style.header1_text_text}>Giao đến <Ionicons name="chevron-down-sharp" size={20} color="black" /></Text>
<Text style={style.header1_text_text1}>Các sản phẩm sẽ được giao đến địa chỉ của bạn</Text>
</View>
</View>
<View style={style.header2}>
<View style={style.header2_input}>
<TextInput style={style.header2_input_input}></TextInput>
<Ionicons style={style.header2_input_icon} name="chevron-down-sharp" size={20} color="black" />
</View>
<TouchableOpacity style={style.header2_button}>
<Ionicons name="search" size={20} color="black" />
</TouchableOpacity>
<TouchableOpacity style={style.header2_button}>
<Ionicons name="heart-outline" size={20} color="black" />
</TouchableOpacity>
</View>
</View>
)
}
const DATA = [
{
id: '1',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '2',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '3',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '4',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '5',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '6',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '7',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '8',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '9',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '10',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '11',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '12',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '13',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
];
const List1 = [
{
id: '1',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '2',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '3',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '4',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
];
const list3 = [
{
id: '1',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '2',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '3',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '4',
title: 'Thùng 24 Lon Cà Phê Sữa Đá',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
{
id: '5',
title: 'Thùng 24 Lon Cà Phê Sữa Đásvdsfvdfbdfb',
text: "Ưu đãi thùng 24 lon cà phê sữa đá còn 289,000đ....",
price: 336,
image: "https://product.hstatic.net/1000075078/product/lon-park6_9fb70fb05cc44ddabf13ff115bab1ce6_large.jpg"
},
];
const renderItem=({item})=>{
return(
<View style={style.mainItem}>
<Text>{item.id}</Text>
<View style={style.mainItem_text}>
<Text style={style.mainItem_text_tittle}>{item.title}</Text>
<Text style={style.mainItem_text_text}>{item.text}</Text>
<Text style={style.mainItem_text_price}>{item.price}.000đ</Text>
</View>
<Image style={style.mainItem_image} source={{uri: item.image}}></Image>
</View>
)
}
export default function buy() {
return (
<SafeAreaView style={{height: "100%"}}>
<Header />
<View style={style.main}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
style={style.mainList}
/>
</View>
</SafeAreaView>
)
}
const style =StyleSheet.create({
header: {
paddingTop: 7,
},
header1: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 15,
},
header1_image: {
width: "20%",
height: 50,
resizeMode: "contain",
},
header1_text: {
width: "80%",
},
header1_text_text: {
fontSize: 15,
fontWeight: "bold",
},
header1_text_text1: {
fontSize: 15,
opacity: 0.5,
},
header2: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
backgroundColor: "#80808020",
padding: 15,
},
header2_input: {
width: "70%",
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
borderWidth: 1,
borderRadius: 10,
backgroundColor: "#80808045",
borderColor: "#80808045",
height: 50,
paddingLeft: 6,
paddingRight: 6,
},
header2_input_input: {
width: "90%",
},
header2_button: {
width:50,
height: 50,
justifyContent: "center",
alignItems: "center",
borderWidth: 1,
borderColor: "#80808045",
borderRadius: 10,
backgroundColor: "#80808045",
},
// làm phần main
main: {
backgroundColor: "#80808020",
padding: 15,
height: "100%",
flex: 1,
},
mainItem: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 10,
padding: 10,
borderWidth: 1,
borderRadius: 10,
backgroundColor: "white",
},
mainItem_text: {
width: "70%",
},
mainItem_text_tittle: {
fontSize: 17,
fontWeight: "bold",
marginBottom: 10
},
mainItem_text_text: {
fontSize: 15,
opacity: 0.5,
marginBottom: 10,
},
mainItem_text_price: {
fontSize: 15,
},
mainItem_image: {
width: "30%",
height: 100,
}
});
<file_sep>import React from 'react'
import { View, Text } from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome';
import Buy from "./screen/buy"
import Store from "./screen/store"
import Home from "./screen/home"
import Diffirent from './screen/diffirent';
import Login from "./screen/login"
import Tab from "./screen/tab"
import { NavigationContainer } from '@react-navigation/native';
export default function App() {
return (
<NavigationContainer>
<Tab/>
</NavigationContainer>
)
}
<file_sep>import React from 'react'
import { View, Text, SafeAreaView, TextInput, Image, FlatList, StyleSheet} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons';
import Header from "./header_1"
const HeaderStore=()=>{
return (
<View style={{backgroundColor: "white"}}>
<Header name={"Cửa hàng"}/>
<View style={style.container} >
<View style={style.header}>
<View style={style.header_item1}>
<Icon name="search" size={30} color="black" />
<TextInput style={style.header_item1_input} placeholder={"Nhập tên đường, quận...."}></TextInput>
</View>
<Text style={style.header_item2}>Đóng</Text>
</View>
</View>
</View>
)
}
const DATA = [
{
id: "1",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "2",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "3",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "4",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "5",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "6",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "7",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "8",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "9",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "10",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "11",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "12",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "13",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "14",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "15",
title: "86 Cao Thắng, Quận 3, Hồ Chí Minh, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "16",
title: "86 Cao Thắng, Quận 3, <NAME>, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
{
id: "17",
title: "86 Cao Thắng, Quận 3, <NAME>, Viêt Nam",
Image: "https://file.hstatic.net/1000075078/file/hinode_-_img_9322_e733cde7255641d0be8a31afc879b379_1024x1024.jpg",
distance: 15,
},
];
export default function store() {
const List=({item})=>{
return(
<View style={style.listItem}>
<Text>{item.id}</Text>
<Image style={style.listItem_image} source={{uri: item.Image }}></Image>
<View style={style.listItem_text}>
<Text style={style.listItem_text_name_store}>the coffee house</Text>
<Text style={style.listItem_text_tittle}>{item.title}</Text>
<Text style={style.listItem_text_distance}>cách đây: {item.distance} km</Text>
</View>
</View>
)
}
return (
<SafeAreaView style={{height: '100%', borderWidth: 3, borderColor: 'blue'}}>
<HeaderStore/>
<View style={[style.main, {flex: 1,}]}>
<View style={[style.container, {flex: 1,}]}>
<Text style={style.mainTittle}>Các cửa h<NAME></Text>
<FlatList
data={DATA}
renderItem={List}
keyExtractor={(item) => item.id}
/>
</View>
</View>
</SafeAreaView>
)
}
const style=StyleSheet.create({
container: {
paddingLeft: 10,
paddingRight: 10,
borderWidth:3, borderColor: 'green',
},
// làm phần header
header: {
display:"flex",
flexDirection:"row",
justifyContent:"space-around",
alignItems:"center",
marginTop: 10,
padding: 7,
},
header_item1: {
width: "85%",
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
padding: 5,
borderColor: "#80808080",
borderWidth: 1,
borderRadius: 10,
backgroundColor: "#80808080",
},
header_item1_input: {
width: "85%",
fontSize: 17,
},
header_item2: {
fontSize: 17,
color:"red",
width: "15%",
textAlign: "center",
},
// làm phần main
main: {
backgroundColor: "#80808020",
},
mainTittle: {
fontSize: 20,
fontWeight: "700",
marginBottom: 15,
marginTop: 15,
},
listItem: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
margin: 7,
borderWidth: 1,
backgroundColor: "white",
borderRadius: 10,
padding: 5,
},
listItem_image: {
width: "40%",
height: 100,
borderRadius: 10,
},
listItem_text: {
width: "55%",
},
listItem_text_name_store: {
fontSize: 14,
color: "gray",
marginTop: 7,
marginBottom: 5,
textTransform: "uppercase",
},
listItem_text_tittle: {
fontSize: 17,
marginBottom: 7,
},
listItem_text_distance: {
fontSize: 16,
color: "gray",
}
});<file_sep>import React from 'react'
import { View, Text, SafeAreaView, StyleSheet, TouchableOpacity} from 'react-native'
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
export default function header_diffirent(props) {
return (
<SafeAreaView style={Style.header}>
<View style={[Style.container]}>
<View style={Style.row}>
<Text style={Style.textTittle}>{props.name}</Text>
<View style={[Style.row, Style.header_frame]}>
<TouchableOpacity style={Style.header_frame_item}><Icon name="ticket-confirmation-outline" color="black" size={30} /><Text>{props.count}</Text></TouchableOpacity>
<TouchableOpacity style={Style.header_frame_item}><Icon name="bell-outline" color="black" size={30} /></TouchableOpacity>
</View>
</View>
</View>
</SafeAreaView>
)
}
const Style = StyleSheet.create({
container: {
paddingLeft: 10,
paddingRight: 10,
},
textTittle: {
fontSize: 25,
fontWeight: "700",
},
text: {
fontSize: 17,
},
row: {
display: "flex",
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
},
// làm phần header
header: {
padding: 5,
},
header_frame_item: {
width: 60,
height: 45,
borderWidth: 1,
borderRadius: 20,
marginRight: 5,
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
},
});
|
6d59408765212524627f497c39f9e71b24d03f02
|
[
"JavaScript"
] | 6
|
JavaScript
|
NgocVinh31/finalProject
|
10883221d1e01d9b3b9f648352508da8e165c525
|
067ed833bf5085752b0b2c980792e6226e6f8153
|
refs/heads/master
|
<file_sep>#正規表現を受け取って、その文字に合致する
#文字の位置を返却する関数
getIndex <- function(string,reg){
index <- c(unlist(regexpr(reg,string)))
}
#正規表現に合致する文字の個数をカウントして
#その個数を返却する関数
countRemoval <- function(string,character){
count <- 0
while((index <- getIndex(string,character))!=-1){
count <- count + 1
x <- substring(string,0,index-1)
y <- substring(string,index+1,nchar(string))
string <- paste(x,y,sep="")
}
return(count)
}
#連関規則のコンソール出力を保持するオブジェクトを
#連関規則の各ペアを一つの文字列ベクトルに結合する形で
#ベクトルを再構成するぺアリング関数
getPair <- function(vectors){
#ポインタの位置をベクトルの先頭にする。
pointer <- 1
#カウント数を所有する変数。2列以上に行が
#「連関規則」のペアの出力がまたがるときに
#この変数が利用される。
count <- 1
#無限ループを避けるセキュリティカウント
securityCount <- 0
#繰り返し上限
limit <- length(vectors)
#返却用の文字列ベクトル
results <- c()
while(TRUE){
#セキュリティカウント
securityCount <- securityCount + 1
#毎回必ずbufferを初期化する
buffer <- c()
#bufferに暫定的に、文字列を格納する。
#この時にcountの数だけループの回数を変化させる。
for(i in 1:count){
buffer <- paste(vectors[pointer+(1-i)],buffer,sep="")
}
if(countRemoval(buffer,"[[:punct:]]")>= 10){
#bufferが結果の一つのベクトルとして確定した。resultsに格納する。
results <- c(results,buffer)
#一行でだけでも「連関規則」のペアになる場合、あるいは
#複数行でペアが確定した場合にはポインタの位置をずらす
#ことが必要になる。
pointer <- pointer + 1
#カウントの初期化
count <- 1
}else{
#一行では連関規則のペアにならないときのみ、
#countに数値が加算される。
count <- count + 1
#ポインタの位置を後方にずらす
pointer <- pointer + 1
}
#ループの回数が上限を上回る。返却値を返す。
if(pointer > limit){
return(results)
}
#無限ループだと判断したら
if(securityCount > 1000*1000){
break
}
}
}
remake <- function(splitedParts){
result <- ""
times <- length(splitedParts)
for(i in 1:times){
result <- paste(result,splitedParts[i],sep=" ")
}
result <- substring(result,2,nchar(result))
return(result)
}
#新removeBlank関数 input 空白がある文字列 output 不必要な空白のない文字列
removeBlank <- function(string){
splited <- c(unlist(strsplit(string," ")))
splited <- splited[nchar(splited) > 0]
return(remake(splited))
}
removeBlanks <- function(as){
times <- length(as)
for(i in 1:times){
as[i] <- removeBlank(as[i])
}
return(as)
}
getRuleNumber <- function(string){
index <- c(unlist(regexpr(" ",string)))
number <- substring(string,0,index-1)
return(as.numeric(number))
}
getLhs <- function(string){
index1 <- c(unlist(regexpr("[{]",string)))
index2 <- c(unlist(regexpr("[}]",string)))
escape <- 0
result <- substring(string,index1+1,index2-1)
while((removePosition <- c(unlist(regexpr("[[:punct:]]",result))))!=-1){
escape <- escape + 1
x <- substring(result,0,removePosition-1)
y <- substring(result,removePosition+1,nchar(string))
result <- paste(x,y,sep="")
if(escape > 100){
break
}
}
return(result)
}
getRhs <- function(string){
index1 <- c(unlist(regexpr("[{]",string)))
index2 <- c(unlist(regexpr("[}]",string)))
#1個目のlhs以後の文字列の取得
rest <- substring(string,index2+1,nchar(string))
escape <- 0
#そのrestの中でのrhs
index1 <- c(unlist(regexpr("[{]",rest)))
index2 <- c(unlist(regexpr("[}]",rest)))
rest <- substring(rest,index1+1,index2-1)
#カンマなどをrhsから除去するプログラム
while((removePosition <- c(unlist(regexpr("[[:punct:]]",rest))))!=-1){
escape <- escape + 1
x <- substring(rest,0,removePosition-1)
y <- substring(rest,removePosition+1,nchar(rest))
rest <- paste(x,y,sep="")
if(escape > 100){
break
}
}
return(rest)
}
getRealNumbers <- function(string){
index <- c(unlist(regexpr("[}]",string)))
#1個目のlhs以後の文字列の取得
rest <- substring(string,index+1,nchar(string))
index2 <- c(unlist(regexpr("[}]",rest)))
rest <- substring(rest,index2+1,nchar(rest))
rest <- c(unlist(strsplit(rest," ")))
results <- c()
for(i in 1:length(rest)){
if((index <- c(unlist(regexpr("[[:punct:]]",rest[i]))))!=-1){
results <- c(results,rest[i])
}
}
return(results)
}
#文字列を分割した数を返却する。
#文字列を分割した数を返却する。
getNumber <- function(string){
splited <- c(unlist(strsplit(string," ")))
count <- 0
for(i in 1:length(splited)){
if((index <- c(unlist(regexpr("[[:space:]]",splited[i])))) < 0){
count <- count + 1
}
if(splited[i]==""){
count <- count -1
}
}
return(count)
}
makeCSVLine <- function(string){
#返却用変数
line <- c()
num <- getRuleNumber(string)
lhs <- getLhs(string)
rhs <- getRhs(string)
numbers <- getRealNumbers(string)
line <- paste(num,lhs,sep=",")
line <- paste(line,rhs,sep=",")
#実数値4つ
support <- numbers[1]
confidence <- numbers[2]
lconfidence <- numbers[3]
lift <- numbers[4]
line <- paste(line,support,sep=",")
line <- paste(line,confidence,sep=",")
line <- paste(line,lconfidence,sep=",")
line <- paste(line,lift,sep=",")
lhsNumber <- getNumber(lhs)
line <- paste(line,lhsNumber,sep=",")
rhsNumber <- getNumber(rhs)
line <- paste(line,rhsNumber,sep=",")
return(line)
}
makeCSVs <- function(strings){
results <- c()
times <- length(strings)
for(i in 1:times){
results <- c(results,makeCSVLine(strings[i]))
}
return(results)
}
##############
##プログラム##
##############
library(arules)
library(arules)
#連関規則の出力ファイルを引数に指定する
as <- readLines("Desktop.txt")
as <- as[-1]
as <- getPair(as)
as <- removeBlanks(as)
as <- makeCSVs(as)
write(as,file="autoAssociation.csv")
<file_sep>#語彙頻度集計表の文字列ベクトルを作成する
#ワーキングディレクトリにdirという名前のディレクトリが
#存在しないことを確認したのちこのプログラムを実行する。
#ディレクトリの作成
dirname <- "dir"
dirpath <- getwd()
dirpath <- paste(dirpath,"/",sep="")
dirpath <- paste(dirpath,dirname,sep="")
dir.create(dirpath)
#その中に各ブログデータが入っているテキストデータを作成する
allblogs <- readLines("sample-SJIS.txt")
#次にURLのみをブログから除去する関数を変数に追加。
#removeURL関数ダミーデータからURLを削除するプログラム
removeURL <- function(x){
#タブ区切りで分割
splited <- strsplit(x,"\t")
#splitedのベクトル化
Vsplited <- c(unlist(splited))
#タイトル
title <- Vsplited[2]
#本文
content <- Vsplited[3]
#その両方
contents <- paste(title,content,"")
return(contents)
}
#removeURLs関数
removeURLs <- function(x){
for(i in 1:length(x)){
x[i] <- removeURL(x[i])
}
return(x)
}
#URLを削除する
allblogs <- removeURLs(allblogs)
###ここに記号処理のプログラムを挿入する。
#不要語削除の鍵を握るプログラム
#正規表現を第二引数に指定しても機能する
removeCharacter <- function(string,character){
while((index <- c(unlist(regexpr(character,string))))!=-1){
#文章前半
X <- substring(string,0,index-1)
#文章後半
Y <- substring(string,index+1,nchar(string))
#文章の再構成
string <- paste(X,Y,sep="")
}
return(string)
}
#複数の不要語を削除するプログラム
#引数に受け取るブログは1つのみ
removeCharacters <- function(blog){
regs <- c("[[:digit:]]","[[:punct:]]")
unnecessaryWords <- c("★","☆","。","●","○")
for(i in 1:length(regs)){
blog <- removeCharacter(blog,regs[i])
}
for(i in 1:length(unnecessaryWords)){
blog <- removeCharacter(blog,unnecessaryWords[i])
}
return(blog)
}
#複数のブログから不要な数値・記号を取り除く処理を行う。
removeCharactersFromBlogs <- function(allblogs){
times <- length(allblogs)
for(i in 1:times){
allblogs[i] <- removeCharacters(allblogs[i])
}
return(allblogs)
}
#上のremoveCharactersFromBlogs関数の利用
allblogs <- removeCharactersFromBlogs(allblogs)
#ファイルの作成。ブログのデータの個数分
makefiles <- function(allblogs,path){
times <- length(allblogs)
filepath <- paste(path,"/",sep="")
for(i in 1:times){
#ファイル名を作る作業
filename <- "entry"
filename <- paste(filename,i,sep="")
filename <- paste(filename,".txt",sep="")
#ディレクトリと結びつける作業
filepath <- paste(filepath,filename,sep="")
write(allblogs[i],file=filepath)
filepath <- paste(path,"/",sep="")
}
}
#ファイルに各テキストデータを一つ一つ格納していく
#これによってRMeCabライブラリの諸関数を実行することが出来る。
makefiles(allblogs,dirpath)
#先ほど作成した対象ディレクトリのパスを取得する関数
getPath <- function(dirname){
#パスの作成
subjectDir <- getwd()
subjectDir <- paste(subjectDir,"/",sep="")
subjectDir <- paste(subjectDir,dirname,sep="")
print(subjectDir)
}
#悲劇。語彙頻度集計表を作成するにあたり、ディレクトリの新規作成は
#不必要だということが分かった。
#整序された語彙頻度集計表を作成する関数
getPath <- function(dirname){
subjectDir <- getwd()
subjectDir <- paste(subjectDir,"/",sep="")
subjectDir <- paste(subjectDir,dirname,sep="")
return(subjectDir)
}
#パスに指定されたファイルの語彙頻度集計表を整序した形で作成する関数
getSortedWordFreq <- function(filename){
path <- getPath(filename)
wordFreq <- RMeCabFreq(path)
#wordFreqオブジェクトから
#"名詞"・"形容詞"・"動詞"・"助動詞"を取り出して
#かつ、細分類が"非自立"でないもののみを抽出する
wordFreq <- wordFreq[(wordFreq$Info1=="名詞"|
wordFreq$Info1=="形容詞"|
wordFreq$Info1=="動詞"|
wordFreq$Info1=="助動詞")
&(wordFreq$Info2 != "非自立"),]
#テキストデータ全体で少なくとも3回の単語の出現
#がなければ、集計表のリストに載らない
wordFreq <- wordFreq[wordFreq$Freq > 3, ]
#ソート作業
wordFreq <- wordFreq[rev(order(wordFreq$Freq)),]
#結果返却
return(wordFreq)
}
#この中で正規表現でアルファベットのものとパンクチュエーション
#を取り除いた表を作る関数
#さらに、ひとが必要ないと捉える「あれ」「これ」「こと」などを削除
#していく関数が必要になるのでそれを追加する。
<file_sep>import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Filtaration {
public static void main(String[] args) {
try{
test();
}catch(IOException ioe){
System.out.println("Filtaration#IOException!");
}
}
public static void test() throws IOException {
String path = "sample.txt";
String allTexts;
String[] contents;
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path),"UTF-8"));
int result;
int i=0;
while((allTexts = in.readLine()) !=null){
contents = allTexts.split("\t");
if (contents.length < 3) {
continue;
}
System.out.printf("[%3d]", i + 1);
i++;
result = execute(contents[1], contents[2]);
System.out.println(result);
// SearchText st = new SearchText(i + 1, contents[1], contents[2],
// "");
// st.search();
}
in.close();
}
private static int execute(String title, String text) {
AlgorithmInterface alg = new MorphemeAlgorithm(title, text);
alg.preProcess();
alg.process();
alg.postProcess();
alg.print();
return alg.getStandardResult();
/**
* if(alg.isQualified()==true){ //pass return alg.getIntegerResult();
* }else{ //fail return -1; }
**/
}
}<file_sep>import java.io.IOException;
import java.util.*;
public class SearchMorphemes {
private String title;
private String text;
private ArrayList<String> menMorphemes;
private ArrayList<String> womenMorphemes;
private String[] unnecessaryWords;
private ArrayList<String> MenMatchWords = new ArrayList<String>();
private ArrayList<String> WomenMatchWords = new ArrayList<String>();
private ArrayList<Integer> AllIndexs = new ArrayList<Integer>();
private ArrayList<Integer> MenIndexs = new ArrayList<Integer>();
private ArrayList<Integer> WomenIndexs = new ArrayList<Integer>();
private ArrayList<Integer> SexDistinctions = new ArrayList<Integer>();
public SearchMorphemes(String title, String text) {
if(title==null){
this.title = "";
}else{
this.title = title;
}
if(text==null){
this.text = "";
}else{
this.text = text;
}
MorphemeDictionary md = new MorphemeDictionary();
this.menMorphemes = md.getMenWords();
this.womenMorphemes = md.getWomenWords();
this.unnecessaryWords = md.getUnnecessaryWords();
}
public void search() {
searchMenMorphemes();
searchWomenMorphemes();
}
public void searchWomenMorphemes() {
for (String word : womenMorphemes) {
if (title.contains(word)) {
register(word,title.indexOf(word),false);
}
while (0 <= text.indexOf(word)) {
int length = word.length();
int index = text.indexOf(word);
int from = index;
int to = index + length;
register(word, index, false);
String Half_x = text.substring(0, from);
String Half_y = text.substring(to, text.length());
text = Half_x + Half_y;
}
}
}
public void searchMenMorphemes() {
for (String word : menMorphemes) {
if (title.contains(word)) {
register(word, title.indexOf(word), true);
}
while (0 <= text.indexOf(word)) {
int length = word.length();
int index = text.indexOf(word);
int from = index;
int to = index + length;
register(word, index, true);
String Half_x = text.substring(0, from);
String Half_y = text.substring(to, text.length());
text = Half_x + Half_y;
}
}
}
public boolean containsUnnecessaryWord() {
for (String word : unnecessaryWords) {
if (title.contains(word)) {
return true;
}
if (text.contains(word)) {
return true;
}
}
return false;
}
public void register(String word, int index, boolean isMan) {
if (isMan == true) {
registerManMorpheme(word, index);
} else {
registerWomenMorpheme(word, index);
}
}
public void registerManMorpheme(String word, int index) {
MenMatchWords.add(word);
MenIndexs.add(index);
AllIndexs.add(index);
SexDistinctions.add(1);
}
public void registerWomenMorpheme(String word, int index) {
WomenMatchWords.add(word);
WomenIndexs.add(index);
AllIndexs.add(index);
SexDistinctions.add(2);
}
public ArrayList<String> getMenMorphemes() {
return this.MenMatchWords;
}
public ArrayList<String> getWomenMorphemes() {
return this.WomenMatchWords;
}
public ArrayList<Integer> getMenIndexs() {
return this.MenIndexs;
}
public ArrayList<Integer> getWomenIndexs() {
return this.WomenIndexs;
}
public ArrayList<Integer> getAllIndexs() {
return this.AllIndexs;
}
public ArrayList<Integer> getSexDistinctions() {
return this.SexDistinctions;
}
}
<file_sep>library(arules)
library(arules)
od <- read.csv("onsen.csv",header=TRUE,row.names=1)
od
od <- as.matrix(od)
ot <- as(od,"transactions")
inspect(ot)
or <- apriori(ot,parameter=list(maxlen=3,support=0.04,confidence=0.55,ext=TRUE))
inspect(or)
(output <- capture.output(inspect(or)))
<file_sep>import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class MorphemeDictionary {
private final static int MEN = 1;
private final static int WOMEN = 2;
private ArrayList<String> MenMorphemes = new ArrayList<String>();
private ArrayList<String> WomenMorphemes = new ArrayList<String>();
public MorphemeDictionary() {
try {
setDictionary();
} catch (IOException ioe) {
whenIOException();
}catch (NumberFormatException nfe){
whenNumberFormatException();
}catch (ArrayIndexOutOfBoundsException aioobe){
whenArrayIndexOutOfBoundsException();
}
}
public void whenArrayIndexOutOfBoundsException(){
System.out.println("MorphemeDictionary#whenArrayIndexOutOfBoundsException()");
}
public void setDictionary() throws IOException {
String path = "test.csv";
BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(path),"UTF-8"));
String set;
String[] line;
while ((set = input.readLine()) != null) {
line = set.split(",");
int sex = Integer.parseInt(line[0]);
if (sex == MEN) {
MenMorphemes.add(line[1]);
} else if (sex == WOMEN) {
WomenMorphemes.add(line[1]);
} else {
}
}
input.close();
}
public void whenIOException(){
System.out.println("MorphemeDictionary#whenIOException");
}
public void whenNumberFormatException(){
System.out.println("MorphemeDictionary#whenNumberFormatException()");
}
private String[] symbols;
public ArrayList<String> getMenWords() {
return this.MenMorphemes;
}
public ArrayList<String> getWomenWords() {
return this.WomenMorphemes;
}
public String[] getSymbols() {
return this.symbols;
}
public String[] getUnnecessaryWords() {
String[] a = {"test","test2"};
return a;
}
}
<file_sep>#ファイルの入力からCSVファイルの出力まで
library(RMeCab)
library(RMeCab)
#入力ファイルのファイル名
inputpath = "sample-SJIS.txt";
#出力ファイルのファイル名
filename = "onlyMorphemes.csv"
wd <- getwd()
wd <- paste(wd,"/",sep="")
wd <- paste(wd,filename,sep="")
#全てのテキストデータを読み込む
alltexts <- readLines(inputpath)
#不要語削除の鍵を握るプログラム
#正規表現を第二引数に指定しても機能する
removeCharacter <- function(string,character){
while((index <- c(unlist(regexpr(character,string))))!=-1){
#文章前半
X <- substring(string,0,index-1)
#文章後半
Y <- substring(string,index+1,nchar(string))
#文章の再構成
string <- paste(X,Y,sep="")
}
return(string)
}
#複数の不要語を削除するプログラム
#引数に受け取るブログは1つのみ
removeCharacters <- function(blog){
#正規表現
regs <- c("[[:digit:]]","[[:punct:]]")
#不要語をここに記述する
unnecessaryWords <- c("★","☆","。","●","○")
for(i in 1:length(regs)){
blog <- removeCharacter(blog,regs[i])
}
for(i in 1:length(unnecessaryWords)){
blog <- removeCharacter(blog,unnecessaryWords[i])
}
return(blog)
}
#複数のブログから不要な数値・記号を取り除く処理を行う。
removeCharactersFromBlogs <- function(allblogs){
times <- length(allblogs)
for(i in 1:times){
allblogs[i] <- removeCharacters(allblogs[i])
}
return(allblogs)
}
#引数の文字列を形態素解析する関数
#形態素の順番通りに数値を割り振る、この関数に引数の数値を渡すと
#その数値をそのエントリーのブログ番号として各列の先頭としてすべての行
#に追記する。
makeMorphemes <- function(string,number){
#形態素解析の処理
morphemes <- RMeCabC(morphemes)
morphemes <- c(unlist(morphemes))
blogNumber = number
#返却する文字列
result <- ""
times <- length(morphemes)
for(i in 1:times){
number = i
morphemes[i]
line <- paste(blogNumber,number,sep=",")
line <- paste(line,morphemes[i],sep=",")
#各ブログの間に一行空かないようにする
#処理
if(i!=times){
line <- paste(line,"\n",sep="")
}
result <- paste(result,line)
}
return(result)
}
#上のカンマ区切りを利用した関数makeCSV.
#ブログのURLを活用した後に実行しなければならない。
makeCSV <- function(blogs){
for(a in 1:length(blogs)){
blogs[a] <- makeMorphemes(blogs[a],a)
}
return(blogs)
}
#次にURLのみをブログから除去する関数を変数に追加。
#removeURL関数ダミーデータからURLを削除するプログラム
removeURL <- function(x){
#タブ区切りで分割
splited <- strsplit(x,"\t")
#splitedのベクトル化
Vsplited <- c(unlist(splited))
#タイトル
title <- Vsplited[2]
#本文
content <- Vsplited[3]
#その両方
contents <- paste(title,content,"")
return(contents)
}
#removeURLs関数
removeURLs <- function(x){
for(i in 1:length(x)){
x[i] <- removeURL(x[i])
}
return(x)
}
#必要な関数が準備できたので、
#これからコードを記述していく。
alltexts <- removeURLs(alltexts)
alltexts <- removeCharactersFromBlogs(alltexts)
alltexts <- makeCSV(alltexts)
write(alltexts,file=wd)
#事後処理
#このプログラムで作成したオブジェクトすべて削除する
rm(alltexts)
rm(filename)
rm(inputpath)
rm(makeCSV)
rm(removeURLs)
rm(removeURL)
rm(wd)
rm(makeMorphemes)
rm(removeCharactersFromBlogs)
rm(removeCharacters)
rm(removeCharacter)
<file_sep>#kaimon.csvのファイルに合わせておく
kaimon.rule <- apriori(kaimon.tran)
summary(kaimon.rule)
inspect(kaimon.rule)
#↓サポート0.2以上、コンフィデンスは0.7以上に限定したもの。
#信頼度
# 相関の強さ。xに続けてyがおこる割合のパーセント表示。
#支持度
# データベー全体で、その組み合わせが起こる割合。
#リフト値
# xが起こった条件によるyが起こる尤度(確からしさ)の増加を示す。
kaimon.rule <- apriori(kaimon.tran, parameter = list(supp= 0.2, conf=0.7, target="rules"))
summary(kaimon.rule)
inspect(kaimon.rule)
<file_sep>public class SearchText {
private String title;
private String text;
private String word;
private int index = 0;
private int from = 0;
private int to = 0;
private int textNumber;
public SearchText(int textNumber, String title, String text, String word) {
this.textNumber = textNumber;
this.title = title;
this.text = text;
this.word = word;
}
public void search() {
// title
if (title.contains(word)) {
index = title.indexOf(word);
title = title.replaceAll(word, "[**[" + word + "]**]");
from = 0;
to = title.length() - 1;
System.out.printf("[%3d]%s\n", textNumber,
title.substring(from, to));
}
// text
if (text.contains(word)) {
index = text.indexOf(word);
text = text.replaceAll(word, "[**[" + word + "]**]");
// to
if (index + 80 < text.length() - 1) {
to = index + 80;
} else if (index + 70 < text.length() - 1) {
to = index + 70;
} else if (index + 60 < text.length() - 1) {
to = index + 60;
} else if (index + 50 < text.length() - 1) {
to = index + 50;
} else if (index + 40 < text.length() - 1) {
to = index + 40;
} else if (index + 30 < text.length() - 1) {
to = index + 30;
} else if (index + 20 < text.length() - 1) {
to = index + 20;
} else if (index + 10 < text.length() - 1) {
to = index + 10;
} else {
to = index + word.length();
}
// from
if (index - 70 > 0) {
from = index - 70;
} else if (index - 60 > 0) {
from = index - 60;
} else if (index - 50 > 0) {
from = index - 50;
} else if (index - 40 > 0) {
from = index - 40;
} else if (index - 30 > 0) {
from = index - 30;
} else if (index - 20 > 0) {
from = index - 20;
} else if (index - 10 > 0) {
from = index - 10;
} else {
from = 0;
}
if (from <= 0) {
from = 0;
}
if (to >= text.length()) {
to = text.length();
}
System.out
.printf("[%3d]%s\n", textNumber, text.substring(from, to));
}
}
}<file_sep>#不要語削除の鍵を握るプログラム
#正規表現を第二引数に指定しても機能する
removeCharacter <- function(string,character){
while((index <- c(unlist(regexpr(character,string))))!=-1){
#文章前半
X <- substring(string,0,index-1)
#文章後半
Y <- substring(string,index+1,nchar(string))
#文章の再構成
string <- paste(X,Y,sep="")
}
return(string)
}
<file_sep>#正規表現を受け取って、その文字に合致する
#文字の位置を返却する関数
getIndex <- function(string,reg){
index <- c(unlist(regexpr(reg,string)))
}
#正規表現に合致する文字の個数をカウントして
#その個数を返却する関数
countRemoval <- function(string,character){
count <- 0
while((index <- getIndex(string,character))!=-1){
count <- count + 1
x <- substring(string,0,index-1)
y <- substring(string,index+1,nchar(string))
string <- paste(x,y,sep="")
}
return(count)
}
#連関規則のコンソール出力を保持するオブジェクト
#を、連関規則のペアごとに一つのベクトルに格納するように
#再構成する関数。
getPair <- function(vectors){
#ポインタの位置をベクトルの先頭にする。
pointer <- 1
#カウント数を所有する変数。2列以上に行が
#「連関規則」のペアの出力がまたがるときに
#この変数が利用される。
count <- 1
#繰り返し上限
limit <- length(vectors)
#返却用の文字列ベクトル
results <- c()
while(TRUE){
buffer <- c()
#bufferに暫定的に、文字列を格納する。
#この時にcountの数だけループの回数を変化させる。
for(i in 1:count){
buffer <- paste(vectors[pointer+(1-i)],buffer,sep="")
}
if(countRemoval(buffer,"[[:punct:]]")>= 10){
#bufferが結果の一つのベクトルとして確定した。resultsに格納する。
results <- c(results,buffer)
#一行でだけでも「連関規則」のペアになる場合、あるいは
#複数行でペアが確定した場合にはポインタの位置をずらす
#ことが必要になる。
pointer <- pointer + 1
#カウントの初期化
count <- 1
}else{
#一行では連関規則のペアにならないときのみ、
#countに数値が加算される。
count <- count + 1
#ポインタの位置を後方にずらす
pointer <- pointer + 1
}
#ループの回数が上限を上回る。返却値を返す。
if(pointer > limit){
return(results)
}
}
}
#関数テスト
output <- readLines("o.txt")
output <- output[-1]
results <- getPair(output)
as <- readLines("Desktop.txt")
as <- as[-1]
results2 <- getPair(as)
<file_sep>teamCaterpie
============
2013コラマネ
<file_sep>getRuleNumber <- function(string){
index <- c(unlist(regexpr(" ",string)))
print(index)
number <- substring(string,0,index-1)
return(as.numeric(number))
}
getLhs <- function(string){
index1 <- c(unlist(regexpr("[{]",string)))
index2 <- c(unlist(regexpr("[}]",string)))
escape <- 0
result <- substring(string,index1+1,index2-1)
while((removePosition <- c(unlist(regexpr("[[:punct:]]",result))))!=-1){
escape <- escape + 1
x <- substring(string,0,removePosition-1)
y <- substring(string,removePosition+1,nchar(string))
result <- paste(x,y,sep="")
if(escape > 100){
break
}
}
return(result)
}
getRhs <- function(string){
index1 <- c(unlist(regexpr("[{]",string)))
index2 <- c(unlist(regexpr("[}]",string)))
#1個目のlhs以後の文字列の取得
rest <- substring(string,index2+1,nchar(string))
escape <- 0
#そのrestの中でのrhs
index1 <- c(unlist(regexpr("[{]",rest)))
index2 <- c(unlist(regexpr("[}]",rest)))
rest <- substring(rest,index1+1,index2-1)
#カンマなどをrhsから除去するプログラム
while((removePosition <- c(unlist(regexpr("[[:punct:]]",rest))))!=-1){
escape <- escape + 1
x <- substring(rest,0,removePosition-1)
y <- substring(rest,removePosition+1,nchar(rest))
rest <- paste(x,y,sep="")
if(escape > 100){
break
}
}
return(rest)
}
getRealNumbers <- function(string){
index <- c(unlist(regexpr("[}]",string)))
#1個目のlhs以後の文字列の取得
rest <- substring(string,index+1,nchar(string))
index2 <- c(unlist(regexpr("[}]",rest)))
rest <- substring(rest,index2+1,nchar(rest))
rest <- c(unlist(strsplit(rest," ")))
results <- c()
for(i in 1:length(rest)){
if((index <- c(unlist(regexpr("[[:punct:]]",rest[i]))))!=-1){
results <- c(results,rest[i])
}
}
return(results)
}
makeCSVLine <- function(string){
#返却用変数
line <- c()
num <- getRuleNumber(string)
lhs <- getLhs(string)
rhs <- getRhs(string)
numbers <- getRealNumbers(string)
line <- paste(num,lhs,sep=",")
line <- paste(line,rhs,sep=",")
#実数値4つ
one <- numbers[1]
two <- numbers[2]
three <- numbers[3]
four <- numbers[4]
line <- paste(line,one,sep=",")
line <- paste(line,two,sep=",")
line <- paste(line,three,sep=",")
line <- paste(line,four,sep=",")
return(line)
}
|
9329a753d0196777500aecab35098ed9a62b3323
|
[
"Markdown",
"Java",
"R"
] | 13
|
R
|
yuurishibata/teamCaterpie
|
2a4844e12d195b3982e96e2db2fe9193a44571ba
|
943b9e9ab0cab8ae9264b00927c29029363a972a
|
refs/heads/master
|
<repo_name>banshengliuli/springmvcclassdemo<file_sep>/src/cn/smbms/dao/SmbmsAddressMapper.java
package cn.smbms.dao;
import cn.smbms.pojo.SmbmsAddress;
public interface SmbmsAddressMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table smbms_address
*
* @mbggenerated Wed Jun 19 17:39:54 CST 2019
*/
int deleteByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table smbms_address
*
* @mbggenerated Wed Jun 19 17:39:54 CST 2019
*/
int insert(SmbmsAddress record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table smbms_address
*
* @mbggenerated Wed Jun 19 17:39:54 CST 2019
*/
int insertSelective(SmbmsAddress record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table smbms_address
*
* @mbggenerated Wed Jun 19 17:39:54 CST 2019
*/
SmbmsAddress selectByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table smbms_address
*
* @mbggenerated Wed Jun 19 17:39:54 CST 2019
*/
int updateByPrimaryKeySelective(SmbmsAddress record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table smbms_address
*
* @mbggenerated Wed Jun 19 17:39:54 CST 2019
*/
int updateByPrimaryKey(SmbmsAddress record);
}
|
4b4deec95263e35e0fa2cb7f098ac0af41270e15
|
[
"Java"
] | 1
|
Java
|
banshengliuli/springmvcclassdemo
|
c7cfb577d9901a4ee17ecd813efa8fa2b1e03c8b
|
5694b1e4168797aaec11a771142f3f6e45928971
|
refs/heads/main
|
<file_sep>// buat 3 variabel
// variabel express untuk memanggil library express
const express = require('express');
//variabel bodyParser untuk memanggil library body-parser
const bodyParser = require('body-parser');
//menambahkan morgan
var morgan = require('morgan');
// fungsi untuk memanggil expressjs
const app = express();
//parse application/json
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(morgan('dev'));
//mendaftarkan menu routes dari index
app.use('/auth', require('./middleware'));
app.listen(3000, () => {
console.log(`Server started on port 3000`);
});<file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.3
-- https://www.phpmyadmin.net/
--
-- Host: 1172.16.17.32
-- Generation Time: May 26, 2021 at 03:01 PM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.11
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `dbrestapi`
--
-- --------------------------------------------------------
--
-- Table structure for table `barang`
--
CREATE TABLE `barang` (
`id_barang` int(11) NOT NULL,
`namaBarang` varchar(255) NOT NULL,
`hargaBarang` varchar(255) NOT NULL,
`stokBarang` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `barang`
--
INSERT INTO `barang` (`id_barang`, `namaBarang`, `hargaBarang`, `stokBarang`) VALUES
(1, '<NAME>', '54700', '120'),
(2, 'Sunlight S<NAME>', '8000', '98'),
(3, 'TRESemme SHP Care Shampo', '35700', '278'),
(4, 'Ultramilk Susu', '5000', '500'),
(5, 'Roma Kelapa Biskuit', '7000', '435'),
(7, '<NAME>', '31900', '67');
-- --------------------------------------------------------
--
-- Table structure for table `pembeli`
--
CREATE TABLE `pembeli` (
`id_pembeli` int(11) NOT NULL,
`namaPembeli` varchar(255) NOT NULL,
`noTelpon` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `pembeli`
--
INSERT INTO `pembeli` (`id_pembeli`, `namaPembeli`, `noTelpon`) VALUES
(1, 'Aria', '0817345763'),
(2, 'Psyche', '0817347271'),
(3, 'Claude', '0833561268'),
(4, 'Ushijima', '0318745677'),
(5, 'Sakusa', '0837587700');
-- --------------------------------------------------------
--
-- Table structure for table `transaksi`
--
CREATE TABLE `transaksi` (
`id_transaksi` int(11) NOT NULL,
`tgl_transaksi` date NOT NULL,
`id_barang` int(11) NOT NULL,
`id_pembeli` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `transaksi`
--
INSERT INTO `transaksi` (`id_transaksi`, `tgl_transaksi`, `id_barang`, `id_pembeli`) VALUES
(1, '2020-09-04', 1, 1),
(2, '2020-04-10', 4, 1),
(3, '2021-03-01', 2, 2),
(4, '2021-03-05', 7, 3),
(5, '2020-11-11', 5, 4),
(6, '2021-01-01', 2, 5),
(7, '2020-09-02', 1, 2);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `barang`
--
ALTER TABLE `barang`
ADD PRIMARY KEY (`id_barang`);
--
-- Indexes for table `pembeli`
--
ALTER TABLE `pembeli`
ADD PRIMARY KEY (`id_pembeli`);
--
-- Indexes for table `transaksi`
--
ALTER TABLE `transaksi`
ADD PRIMARY KEY (`id_transaksi`),
ADD KEY `id_barang` (`id_barang`),
ADD KEY `id_pembeli` (`id_pembeli`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `barang`
--
ALTER TABLE `barang`
MODIFY `id_barang` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `pembeli`
--
ALTER TABLE `pembeli`
MODIFY `id_pembeli` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `transaksi`
--
ALTER TABLE `transaksi`
MODIFY `id_transaksi` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `transaksi`
--
ALTER TABLE `transaksi`
ADD CONSTRAINT `transaksi_ibfk_1` FOREIGN KEY (`id_barang`) REFERENCES `barang` (`id_barang`) ON DELETE CASCADE,
ADD CONSTRAINT `transaksi_ibfk_2` FOREIGN KEY (`id_pembeli`) REFERENCES `pembeli` (`id_pembeli`) ON DELETE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
836f80643f08720f87fdecb361b3b75c1f6388c5
|
[
"JavaScript",
"SQL"
] | 2
|
JavaScript
|
asiyahhanifah/barangku
|
dadb377beb6ca17db4d9560e458505000643f5b0
|
61411ef0bd6a14b2af1c2bf4b636085f5016d8ae
|
refs/heads/master
|
<repo_name>MoraBoop/form-email-validate-js<file_sep>/js/app.js
const email = document.getElementById('email');
const asunto = document.getElementById('asunto');
const mensaje = document.getElementById('mensaje');
const btnEnviar = document.getElementById('enviar');
const formularioEnviar = document.getElementById('enviar-mail');
const btnReset = document.getElementById('resetBtn');
eventListener();
// eventos
function eventListener() {
document.addEventListener('DOMContentLoaded', incioApp);
email.addEventListener('blur', validarCampo);
asunto.addEventListener('blur', validarCampo);
mensaje.addEventListener('blur', validarCampo);
formularioEnviar.addEventListener('submit', enviarEmail);
btnReset.addEventListener('click', borrarContentForm);
}
// funciones
function incioApp() {
btnEnviar.disabled = true;
}
function validarCampo() {
//console.log("Dentro del input");
validarLongitud(this);
//validar email
if (this.type === 'email') {
validarEmail(this);
}
let errores = document.querySelectorAll('.error')
if (email.value !== '' && asunto.value !== '' && mensaje.value !== '') {
if (errores.length === 0) {
btnEnviar.disabled = false;
}
}
}
// cuando se envia el correo
function enviarEmail(e) {
e.preventDefault();
//console.log('mail enviado');
const spinner = document.querySelector('#spinner');
spinner.style.display = 'block';
// que acabe el spinn
const msjEnviado = document.createElement('img');
msjEnviado.src = 'img/mail.gif';
msjEnviado.style.display = 'block';
// borrar spin y colocar img msj enviado
setTimeout(()=>{
spinner.style.display = 'none';
document.querySelector('#loaders').appendChild(msjEnviado);
setTimeout(()=>{
msjEnviado.remove();
formularioEnviar.reset();
}, 3000);
}, 3000);
}
function validarLongitud(campo) {
// vemos que nos retorna el elemento
// console.log(campo);
// retornar la longitud
console.log(campo.value.length)
if (campo.value.length > 0 ) {
campo.style.borderBottomColor = 'green';
campo.classList.remove('error')
} else {
campo.style.borderBottomColor = 'red';
campo.classList.add('error')
}
}
function validarEmail(elemento) {
// console.log(elemento);
const mensaje = elemento.value;
if (mensaje.indexOf('@') !== -1) {
elemento.style.borderBottomColor = 'green';
elemento.classList.remove('error');
} else {
elemento.style.borderBottomColor = 'red';
elemento.classList.add('error');
}
}
function borrarContentForm(e) {
e.preventDefault();
formularioEnviar.reset();
}
|
6f35170c9853767615c7311c6a0e9f6819deea28
|
[
"JavaScript"
] | 1
|
JavaScript
|
MoraBoop/form-email-validate-js
|
f390c1a888a59c75268aeeb6e3170ed75ffb4eaa
|
c8385e326727d6ab04e160db55e87ee1f1387311
|
refs/heads/master
|
<repo_name>nathakits/spottie-figma-plugin<file_sep>/code.ts
// This plugin enables users to search for artists and tracks
// and insert images for design using the Spotify API.
// Credit to Spotify for the API.
// This file holds the main code for the plugins. It has access to the *document*.
// You can access browser APIs in the <script> tag inside "ui.html" which has a
// full browser environment (see documentation).
// This shows the HTML page in "ui.html".
figma.showUI(__html__, { width: 450, height: 650 });
// Calls to "parent.postMessage" from within the HTML page will trigger this
// callback. The callback will be passed the "pluginMessage" property of the
// posted message.
figma.ui.onmessage = msg => {
// One way of distinguishing between different types of messages sent from
// your HTML page is to use an object with a "type" property like this.
if (msg.type === 'create-image') {
// get current selection
var currentSel = figma.currentPage.selection
// if selection has an object
if (currentSel.length > 0) {
// loop nodes to check type
currentSel.forEach(node => {
if (
node.type === 'FRAME' ||
node.type === 'ELLIPSE' ||
node.type === 'POLYGON' ||
node.type === 'RECTANGLE' ||
node.type === 'STAR' ||
node.type === 'VECTOR'
) {
// insert fill to node
var buffer = msg.buffer
var hash = figma.createImage(buffer).hash
node.fills = [
{ type: 'IMAGE', scaleMode: 'FILL', imageHash: hash }
];
}
else {
figma.notify(`Please select a fillable object`)
}
});
}
// else create a new rectangle and add to page
else if (currentSel.length === 0) {
// image
var buffer = msg.buffer
var hash = figma.createImage(buffer).hash
// viewport
var viewport = figma.viewport.center
// create rectangle and set image fill
const rect = figma.createRectangle();
// set x and y coordinates with viewport values
rect.x = viewport.x
rect.y = viewport.y
rect.resize(msg.size.width, msg.size.height)
// set type to IMAGE and set fill with image hash data
rect.fills = [
{ type: 'IMAGE', scaleMode: 'FILL', imageHash: hash }
];
// add image to Figma
figma.currentPage.appendChild(rect);
}
}
if (msg.type === 'create-image-array') {
// get current selection
var currentSel = figma.currentPage.selection
// if selection has an object
if (currentSel.length > 0) {
// loop nodes to check type
currentSel.forEach((node, i) => {
if (
node.type === 'FRAME' ||
node.type === 'ELLIPSE' ||
node.type === 'POLYGON' ||
node.type === 'RECTANGLE' ||
node.type === 'STAR' ||
node.type === 'VECTOR'
) {
try {
// insert fill to node
var thumbs = msg.array
var buffer = thumbs[i]
var hash = figma.createImage(buffer).hash
node.fills = [
{ type: 'IMAGE', scaleMode: 'FILL', imageHash: hash }
];
} catch (error) {
// if number of selected objects is more than the images
// then no buffer to add
var pluralize = `image${ thumbs.length > 1 ? 's' : ''}`
var message = `Only added ${thumbs.length} ${pluralize} to selection. Please select more thumbnails.`
var noti = figma.notify(message)
setTimeout(() => {
noti.cancel()
}, 3000);
}
}
else {
figma.notify(`Please select a fillable object`)
}
});
}
else if (currentSel.length === 0) {
var nodes = []
// viewport
var viewport = figma.viewport.center
// create rectangle and set image fill
msg.array.forEach((buffer, i) => {
var hash = figma.createImage(buffer).hash
var rect = figma.createRectangle();
rect.x = viewport.x + (i * msg.size.width)
rect.y = viewport.y
// hard code rect size
rect.resize(msg.size.width, msg.size.height)
rect.fills = [
{ type: 'IMAGE', scaleMode: 'FILL', imageHash: hash }
];
figma.currentPage.appendChild(rect)
nodes.push(rect)
});
}
}
if (msg.type === 'msg') {
figma.notify(msg.message, msg.timeout)
}
};
<file_sep>/UI/test.js
const axios = require('axios');
const qs = require('qs');
require('dotenv').config()
var data = qs.stringify({
'grant_type': 'client_credentials'
});
const auth = process.env.VUE_APP_SPOTIFY_AUTH_BASIC
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
data: data,
headers: {
'Authorization': `Basic ${auth}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
}).then(response => {
console.log(`PASS`)
console.log(`Valid Key`)
}).catch(error => {
process.exit(1)
})<file_sep>/UI/src/store/store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
title: "Figma Plugin Vue Sample",
playing: false,
longpress: false,
arraySel: [],
size: {
width: 800,
height: 800
},
},
mutations: {
title: (state, value) => {
state.title = value
},
playing: (state, value) => {
state.playing = value
},
longpress: (state, value) => {
state.longpress = value
},
arraySel: (state, value) => {
state.arraySel = value
},
size: (state, value) => {
state.size = {
width: value.width,
height: value.height
}
}
},
actions: {},
getters: {
title: state => {
return state.title
},
playing: state => {
return state.playing
},
longpress: state => {
return state.longpress
},
arraySel: state => {
return state.arraySel
},
size: state => {
return state.size
}
},
});<file_sep>/README.md
<h1 align="center">
<a href="https://github.com/nathakits/spottie-figma-plugin">
<img src="assets/plugin-file-cover.jpg" alt="Spottie"/>
</a>
</h1>
<h4 align="center">
Spottie is a Figma plugin for inserting album, artist and track covers directly into your designs using Spotify API
</h4>
<p align="center">
Figma plugin built with Vue.js and Tailwind
</p>
<div align="center">
<a href="https://www.producthunt.com/posts/spottie?utm_source=badge-featured&utm_medium=badge&utm_souce=badge-spottie" target="_blank">
<img src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=290475&theme=light" alt="Spottie - Insert album and track covers from Spotify to Figma | Product Hunt" style="width: 250px; height: 54px;" width="250" height="54" />
</a>
<a href="https://github.com/nathakits/spottie-figma-plugin/actions/workflows/node.js.yml">
<img src="https://github.com/nathakits/spottie-figma-plugin/actions/workflows/node.js.yml/badge.svg?branch=master" alt="Node.js CI">
</a>
</div>
<br>
## Download
Install in Figma
https://www.figma.com/community/plugin/946462676168136646/Spottie
## Basic Usage
In Figma select main menu -> Plugins -> Spottie
- Browse or search for album, artist and track covers
- Click on the image to insert
## Features
- New releases on plugin start up
- Search album, artist and track covers
- Insert single image with single click
- Long press on an image to enable multi-select mode
- Selected object(s) in the canvas will get replaced with the inserted image(s)
- Browser-level image lazy-loading
- Bonus! In the Tracks tab, double-click on any thumbnail to listen to the preview track!
## Coming soon
- Search Podcast covers
- Random image insert
## Installation and build setup
The project is separated into 2 sections. The main Figma code and the UI which is based on Vue and Tailwind.
### Spotify
This project uses Spotify API so you need to get a Spotify developer account.
Create a new Spotify app and get the `Client ID` and `Secret Key` to generate the access token.
#### For main Figma code
```bash
# install dependencies
$ npm install
# serve in watch mode
$ npm run watch
# build for production
$ npm run build
```
#### For UI
```bash
# install dependencies
$ npm install
# serve with hot reload at localhost:8080
$ npm run serve
# build for production
$ npm run build
```
## [UI Setup](UI/README.md)
Check out [instruction to setup Figma Plugin UI](UI/README.md)
## Figma setup guide
You can find instructions at: https://www.figma.com/plugin-docs/setup/
## Contributing
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
## License
MIT [](LICENSE)
<file_sep>/UI/README.md
# Figma plugin using Vue
## UI (HTML) for Figma Plugin
`UI` is Vue SPA. Since Figma Plugin supports a single HTML file so SPA is recommended for better experience and configuration. Write the Figma Plugin User Interface using the power of Vuejs.
`UI` has its configuration, follow the readme file and you will get your sample code running.
`src` will hold all the `component`, `assets`, `stores` etc... related to the Figma Plugin UI
---
This plugin sample contains almost everything needed to create a simple Figma Plugin using Vuejs.
---
## Project setup
```BASH
npm install
```
### Compiles and hot-reloads for development
```BASH
npm run serve
```
**Note:** This command will not generate `index.html` file to be used in Figma Plugin. `serve` will spin the localhost to run the app on browser for faster development of the UI side of the plugin.
### Compiles and minifies for production
```BASH
npm run build
```
`build` will create `/dist` directory containing `index.html` this is the file to use as a value of `UI` in plugin's `menifest.json`
---
### Compiles and minifies for production with hot-reloads
```BASH
npm run build-watch
```
Does the work of `build` but with watching the file changes to build again automatically.
If you want to test the UI directly into the Figma Plugin then you need to run `build-watch`
---
**Info:** Have any suggestions, fixes, or another workaround to build better? please, do let me know.
---<file_sep>/UI/src/main.js
import Vue from 'vue'
import App from './App.vue'
import { store } from './store/store';
import "tailwindcss/tailwind.css"
import "./assets/css/index.css"
import { longClickDirective } from 'vue-long-click'
const longClickInstance = longClickDirective({ delay: 400, interval: 0 })
Vue.directive('longclick', longClickInstance)
Vue.config.productionTip = false
new Vue({
store,
render: h => h(App),
}).$mount('#app')
<file_sep>/code.js
// This plugin enables users to search for artists and tracks
// and insert images for design using the Spotify API.
// Credit to Spotify for the API.
// This file holds the main code for the plugins. It has access to the *document*.
// You can access browser APIs in the <script> tag inside "ui.html" which has a
// full browser environment (see documentation).
// This shows the HTML page in "ui.html".
figma.showUI(__html__, { width: 450, height: 650 });
// Calls to "parent.postMessage" from within the HTML page will trigger this
// callback. The callback will be passed the "pluginMessage" property of the
// posted message.
figma.ui.onmessage = msg => {
// One way of distinguishing between different types of messages sent from
// your HTML page is to use an object with a "type" property like this.
if (msg.type === 'create-image') {
// get current selection
var currentSel = figma.currentPage.selection;
// if selection has an object
if (currentSel.length > 0) {
// loop nodes to check type
currentSel.forEach(node => {
if (node.type === 'FRAME' ||
node.type === 'ELLIPSE' ||
node.type === 'POLYGON' ||
node.type === 'RECTANGLE' ||
node.type === 'STAR' ||
node.type === 'VECTOR') {
// insert fill to node
var buffer = msg.buffer;
var hash = figma.createImage(buffer).hash;
node.fills = [
{ type: 'IMAGE', scaleMode: 'FILL', imageHash: hash }
];
}
else {
figma.notify(`Please select a fillable object`);
}
});
}
// else create a new rectangle and add to page
else if (currentSel.length === 0) {
// image
var buffer = msg.buffer;
var hash = figma.createImage(buffer).hash;
// viewport
var viewport = figma.viewport.center;
// create rectangle and set image fill
const rect = figma.createRectangle();
// set x and y coordinates with viewport values
rect.x = viewport.x;
rect.y = viewport.y;
rect.resize(msg.size.width, msg.size.height);
// set type to IMAGE and set fill with image hash data
rect.fills = [
{ type: 'IMAGE', scaleMode: 'FILL', imageHash: hash }
];
// add image to Figma
figma.currentPage.appendChild(rect);
}
}
if (msg.type === 'create-image-array') {
// get current selection
var currentSel = figma.currentPage.selection;
// if selection has an object
if (currentSel.length > 0) {
// loop nodes to check type
currentSel.forEach((node, i) => {
if (node.type === 'FRAME' ||
node.type === 'ELLIPSE' ||
node.type === 'POLYGON' ||
node.type === 'RECTANGLE' ||
node.type === 'STAR' ||
node.type === 'VECTOR') {
try {
// insert fill to node
var thumbs = msg.array;
var buffer = thumbs[i];
var hash = figma.createImage(buffer).hash;
node.fills = [
{ type: 'IMAGE', scaleMode: 'FILL', imageHash: hash }
];
}
catch (error) {
// if number of selected objects is more than the images
// then no buffer to add
var pluralize = `image${thumbs.length > 1 ? 's' : ''}`;
var message = `Only added ${thumbs.length} ${pluralize} to selection. Please select more thumbnails.`;
var noti = figma.notify(message);
setTimeout(() => {
noti.cancel();
}, 3000);
}
}
else {
figma.notify(`Please select a fillable object`);
}
});
}
else if (currentSel.length === 0) {
var nodes = [];
// viewport
var viewport = figma.viewport.center;
// create rectangle and set image fill
msg.array.forEach((buffer, i) => {
var hash = figma.createImage(buffer).hash;
var rect = figma.createRectangle();
rect.x = viewport.x + (i * msg.size.width);
rect.y = viewport.y;
// hard code rect size
rect.resize(msg.size.width, msg.size.height);
rect.fills = [
{ type: 'IMAGE', scaleMode: 'FILL', imageHash: hash }
];
figma.currentPage.appendChild(rect);
nodes.push(rect);
});
}
}
if (msg.type === 'msg') {
figma.notify(msg.message, msg.timeout);
}
};
|
6879503f136a893b763be2fce24007a6829779f3
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 7
|
TypeScript
|
nathakits/spottie-figma-plugin
|
879f8041a4fd69605a5ec31f430fc9f02c452e94
|
6cd5879547c0da59d29d9626f7511e392eb08283
|
refs/heads/master
|
<file_sep>from django.contrib import admin
from goodsapp import models
class TypeInfoAdmin(admin.ModelAdmin):
list_display = ['id', 'ttitle']
class GoodsInfoAdmin(admin.ModelAdmin):
list_per_page = 15
list_display = ['id', 'gtitle', 'gprice', 'gunit', 'gclick', 'gstock', 'gcontent', 'gtype']
admin.site.register(models.TypeInfo, TypeInfoAdmin)
admin.site.register(models.GoodsInfo, GoodsInfoAdmin)
<file_sep>from django.shortcuts import render, redirect, HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.http import JsonResponse
from django.core.paginator import Paginator
import hashlib, json
from userapp import models
from goodsapp.models import GoodsInfo
from orderapp.models import OrderInfo
from cartapp.models import Cart
def auth_login(func):
def warper(request, *args, **kwargs):
# 两种可选
# login_status = request.session.get('is_login')
login_status = request.session.has_key('user_id')
print("状态:", login_status)
if not login_status:
ret = redirect('/user/login/')
# print("path:", request.path)
# print("get_full_path:", request.get_full_path())
# print("get_full_path_info:", request.get_full_path_info())
# 仅适用于在被迫登录情况下获取登录前的url
ret.set_cookie('url', request.get_full_path())
return ret
# uname = request.session.get('username')
return func(request, *args, **kwargs)
return warper
# @auth_login ==> uinfo = auth_login(uinfo) ==>uinfo = warper()
# def index(request):
# if request.method == 'GET':
# return render(request, 'userinfo/index.html')
def register(request):
if request.method == "GET":
# autourl = reverse('user:register')
# print(autourl)
return render(request, "userinfo/register.html", {'title': "注册"})
elif request.method == "POST":
post = request.POST
uname = post.get('user_name')
upwd = post.get('pwd')
ucpwd = post.get('cpwd')
uemail = post.get('email')
if ucpwd != upwd:
return redirect('/user/register')
m = hashlib.md5()
m.update(upwd.encode('utf-8'))
upwd = m.hexdigest()
userobj = models.UserInfo.objects.create(uname=uname, upwd=upwd, uemail=uemail)
models.Adress.objects.create(uaddrs_id=userobj.id, ushipaddrs_id=userobj.id)
return redirect('/user/login')
def register_exist(request):
if request.method == 'GET':
uname = request.GET.get('uname')
print(uname)
name_exist = models.UserInfo.objects.filter(uname=uname).count() # 我们不关心用户的其他字段信息,获取个数即可
data = {'name_exist': name_exist}
return JsonResponse(data)
# 第一种方式可选(非本次使用的方式)
def login(request):
if request.method == 'GET':
print("method",request.method)
username = request.COOKIES.get('username', '')
username2 = request.session.get('username', '') # 仅做测试
# 用于记住用户名,显示在表单上
content = {'title': '登录', 'error_name':0, 'error_pwd': 0, 'uname': username or username2}
ret = render(request, 'userinfo/login.html', content)
if len(request.get_full_path()) > len(request.path_info):
url = request.get_full_path().split('=')[1]
ret.set_cookie('url', url)
return ret
elif request.method == 'POST':
print("method:",request.method)
post = request.POST
username = post.get('username', None)
pwd = post.get('pwd', None)
m = hashlib.md5()
m.update(pwd.encode('utf-8'))
pwd = m.hexdigest()
content = {'title': '登录', 'error_name':0, 'error_pwd': 0, 'uname': username}
if username:
userobj = models.UserInfo.objects.filter(uname=username).first()
# print("userobj", userobj, userobj.upwd)
if userobj:
# 用户名正确
if userobj.upwd == pwd:
rmb_uname = post.get('rmb_uname', 0)
prev_url = request.COOKIES.get('url', '/')
print("prev_url:", prev_url)
ret = HttpResponseRedirect(prev_url) # 跳转到登录前的页面
# 记住用户名
if rmb_uname:
ret.set_cookie('username', username)
else:
ret.set_cookie('username', username, max_age=10) # -1:立即失效
request.session['is_login'] = True
request.session['user_id'] = userobj.id
return ret
content['error_pwd'] = 1
return render(request, 'userinfo/login.html', content)
content['error_name'] = 1
return render(request, 'userinfo/login.html', content)
# if userobj.upwd == pwd:
# rmb_uname = post.get('rmb_uname')
# # print("记住密码:", rmb_uname, type(rmb_uname))
# if rmb_uname:
# request.session['username'] = username
# request.session['is_login'] = True
# return redirect('/user/uinfo/')
return redirect('/user/login/')
# 第二种方式可选(ajax)
def login_check(request):
if request.method == 'POST':
username = request.POST.get('username')
print("username>>", username)
if username:
userobj = models.UserInfo.objects.filter(uname=username).first()
print("userobj1", userobj)
if not userobj:
response = {'title': '登录', 'error_name': 1, 'error_pwd': 0, 'uname': username}
return HttpResponse(json.dumps(response))
pwd = request.POST.get('pwd')
m = hashlib.md5()
m.update(pwd.encode('utf-8'))
pwd = m.hexdigest()
if userobj.upwd == pwd:
response = {'title': '登录', 'error_name': 0, 'error_pwd': 0, 'uname': username}
return HttpResponse(json.dumps(response))
response = {'title': '登录', 'error_name': 0, 'error_pwd': 1, 'uname': username}
return HttpResponse(json.dumps(response))
return redirect('/user/login/')
def login_check2(request):
if request.method == 'POST':
username = request.POST.get('username')
pwd = request.POST.get('pwd')
m = hashlib.md5()
m.update(pwd.encode('utf-8'))
pwd = m.hexdigest()
userobj = models.UserInfo.objects.filter(uname=username).first()
if userobj:
if userobj.upwd == pwd:
rmb_uname = request.POST.get('rmb_uname', 0)
url = request.COOKIES.get('url', '/')
print("prev_url:", url)
ret = HttpResponseRedirect(url) # 跳转到登录前的页面
if rmb_uname:
ret.set_cookie('username', username) # 这里用cookie就可以了,是保存在用户浏览器端的
request.session['is_login'] = True
request.session['user_id'] = userobj.id
request.session['username'] = username
# return render(request, 'userinfo/login.html', {'status': True}) ajax提交,不能跳转的
return ret # 通过任意表单方式实现提交
# return render(request, 'userinfo/login.html', {'status': True}) ajax提交,不能跳转的
return redirect('/user/login')
def logout(request):
if request.method == 'GET':
request.session.flush()
return JsonResponse({'status': True})
@auth_login
def uinfo(request):
if request.method == 'GET':
userobj = models.UserInfo.objects.get(id=request.session['user_id'])
content = {'title': '用户中心',
'contact': userobj.uphone,
'uname': request.session.get('username'),
'email': userobj.uemail,
}
# 获取最近浏览的商品
goodids = request.COOKIES.get('lately_goodids', '') # ==>'6,4,3,8'
goodid_list = goodids.split(',')
# 根据id获取商品对象
goodobj_list = []
print("goodid_list", type(goodid_list), goodid_list)
for goodid in goodid_list:
if goodid:
goodobj = GoodsInfo.objects.filter(id=int(goodid)).first()
if goodobj:
goodobj_list.append(goodobj) # 严格按照列表顺序获取对象
content['goodobj_list'] = goodobj_list
return render(request, 'userinfo/user_center_info.html', content)
@auth_login
def uinfo_order(request):
if request.method == 'GET':
uid = request.session.get('user_id')
# 获取该用户所有的订单信息
order_objs = OrderInfo.objects.filter(user_id=uid).order_by('pk')
# 再获取每个订单中的多个商品信息(即获取详单信息)==》user/uinfo_order/,由此决定设置怎么样的模型类
# 分页操作
# 1、创建Paginator对象
pobj = Paginator(order_objs, 2)
# 2、创建page对象
pIndex = int(request.GET.get('pindex', '1'))
order_objs = pobj.page(pIndex)
print(order_objs.number)
# 3、创建页码列表
pagelist = pobj.page_range
content = {
'title': '全部订单',
'order_objs': order_objs,
'pagelist': pagelist,
}
return render(request, 'userinfo/user_center_order.html', content)
@auth_login
def uinfo_site(request):
if request.method == 'GET':
userobj = models.UserInfo.objects.filter(id=request.session['user_id'])
content = {'addressee': userobj[0].recver, 'postal': userobj[0].upostal, 'phone': userobj[0].uphone}
addr = userobj.values('uaddrs__pro')
content['detailAddr'] = addr[0]['uaddrs__pro']
content['title'] = '用户中心'
return render(request, 'userinfo/user_center_site.html', content)
elif request.method == 'POST':
''' 第一种方式ajax
userobj = models.UserInfo.objects.get(id=request.session['user_id'])
post = request.POST
addressee = post.get('addressee')
detailAddr = post.get('detailAddr')
postal = post.get('postal')
phone = post.get('phone')
models.Adress.objects.update(pro=detailAddr, uaddrs_id=userobj.id, ushipaddrs_id=userobj.id)
dict = {'recver': addressee, 'upostal': postal, 'uphone': phone}
models.UserInfo.objects.values().update(**dict)
data = {'status': True}
return HttpResponse(json.dumps(data)) # 记得dumps一下
'''
# 第二种方式
userobj = models.UserInfo.objects.get(id=request.session['user_id'])
post = request.POST
userobj.recver = post.get('addressee')
detailAddr = post.get('detailAddr')
userobj.upostal = post.get('postal')
userobj.uphone = post.get('phone')
userobj.save()
models.Adress.objects.filter(uaddrs_id=userobj.id).update(pro=detailAddr)
return redirect('/user/uinfo_site') # 可以把userobj传到前端,get/post简化
<file_sep>from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from cartapp import models
from userapp.models import UserInfo
from userapp.views import auth_login
from django.db.models import Count
@auth_login
def cart(request):
uid = request.session.get('user_id')
# 一个用户uid对应着多个商品数据gid,所以获取到的是一个第三张表cart的对象列表
cartobj_list = models.Cart.objects.filter(user_id=uid)
content = {'title': '购物车', 'page_name': 1, 'page_char': '购物车',
'cartobj_list': cartobj_list,}
if request.is_ajax():
count = request.GET.get('count')
print("count:", count)
gid = int(request.GET.get('gid'))
cartobj = models.Cart.objects.get(user_id=uid, good_id=gid)
cartobj.count = count
cartobj.save()
return JsonResponse({'status': True})
return render(request, 'cartinfo/cart.html', content)
@auth_login
def addcart(request, gid, cid): # cid: 数量
gid = int(gid)
cid = int(cid)
uid = request.session.get('user_id')
if request.method == 'GET':
cartobj_list = models.Cart.objects.filter(user_id=uid, good_id=gid)
if len(cartobj_list) >= 1: # 该用户已存在该商品id
cartobj = cartobj_list[0]
cartobj.count = cartobj.count + cid
else:
cartobj = models.Cart() # 没有数据,创建一条
cartobj.user_id = uid
cartobj.good_id = gid
cartobj.count = cid
cartobj.save()
# 如果是ajax请求,就执行:
if request.is_ajax():
# count = models.Cart.objects.filter(user_id=uid).aggregate(Count('count'))
count = models.Cart.objects.filter(user_id=uid).count()
return JsonResponse({'count': count})
return redirect('/cart/')
def delcart(request, gid, cid):
if request.method == 'GET':
gid, cid = int(gid), int(cid)
uid = request.session.get('user_id')
cartobj = models.Cart.objects.get(user_id=uid, good_id=gid)
if cartobj:
cartobj.delete()
ret = redirect('/cart/')
return ret
# 第二种删除不刷新的方式
def delete(request, ctid):
print(request.method)
if request.method == 'GET':
if request.is_ajax():
try:
print(type(ctid))
cartobj = models.Cart.objects.get(pk=ctid)
cartobj.delete()
data = {'status': True}
except Exception as e:
print(e)
data = {'status': False}
return JsonResponse(data)
return HttpResponse('ok')
@auth_login
def post_order(request):
if request.method == 'GET':
uid = request.session.get('user_id')
cartobj_list = models.Cart.objects.filter(user_id=uid)
userobj = UserInfo.objects.get(pk=uid)
addr_dic = userobj.uaddrs.values('pro').first() # 不可以接着写.get('pro'),这是在userobj对象下
# print(addr_dic.get('pro'))
content = {'title': '提交订单页', 'page_name': 1, 'page_char': '提交订单',
'cartobj_list': cartobj_list, 'addr': addr_dic.get('pro'),}
return render(request, 'cartinfo/place_order.html', content)<file_sep>from django.test import TestCase
s = 'uson'
s.split(',')
# print(s)
li = [12,3]
dic = {}
# li = 'cohui'
for i in li:
print(i)
dic['li'] = li
# print(dic)
gstock = 432
count = 2
gstock -= count
print(gstock)<file_sep># Generated by Django 2.2.4 on 2019-10-31 12:38
from django.db import migrations, models
import django.db.models.deletion
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('goodsapp', '0003_auto_20191030_1922'),
]
operations = [
migrations.AlterField(
model_name='goodsinfo',
name='gbrief',
field=models.CharField(max_length=100, verbose_name='商品简介'),
),
migrations.AlterField(
model_name='goodsinfo',
name='gclick',
field=models.IntegerField(verbose_name='商品人气'),
),
migrations.AlterField(
model_name='goodsinfo',
name='gcontent',
field=tinymce.models.HTMLField(verbose_name='详情内容'),
),
migrations.AlterField(
model_name='goodsinfo',
name='gpic',
field=models.ImageField(upload_to='goodsPic', verbose_name='商品图片'),
),
migrations.AlterField(
model_name='goodsinfo',
name='gprice',
field=models.DecimalField(decimal_places=2, max_digits=7, verbose_name='商品价格'),
),
migrations.AlterField(
model_name='goodsinfo',
name='gstock',
field=models.IntegerField(verbose_name='商品库存'),
),
migrations.AlterField(
model_name='goodsinfo',
name='gtitle',
field=models.CharField(max_length=20, verbose_name='商品标题'),
),
migrations.AlterField(
model_name='goodsinfo',
name='gtype',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='goodsapp.TypeInfo', verbose_name='商品类型'),
),
migrations.AlterField(
model_name='goodsinfo',
name='gunit',
field=models.CharField(default='500g', max_length=10, verbose_name='单位'),
),
migrations.AlterField(
model_name='goodsinfo',
name='isDelete',
field=models.BooleanField(default=False, verbose_name='是否删除'),
),
migrations.AlterField(
model_name='typeinfo',
name='isDelete',
field=models.BooleanField(default=False, verbose_name='是否删除'),
),
migrations.AlterField(
model_name='typeinfo',
name='ttitle',
field=models.CharField(max_length=10, verbose_name='商品类型'),
),
]
<file_sep>from django.db import models
# 用户和商品:1对多
# 商品和用户:1对多
# 双向一对多就是多对多
# 从购物车页面可以看到:需要存着一个用户和商品以及购买数量的关系
class Cart(models.Model): # 第三张表
user = models.ForeignKey('userapp.UserInfo', on_delete=models.CASCADE) # 跨app引入模型类可以用符号.
good = models.ForeignKey('goodsapp.GoodsInfo', on_delete=models.CASCADE)
# 增加一个数量字段
count = models.IntegerField()<file_sep>from django.db import models
class OrderInfo(models.Model):
# 订单id
oid = models.AutoField(max_length=20, primary_key=True)
# 用户信息
user = models.ForeignKey('userapp.UserInfo', on_delete=models.CASCADE)
# 是否支付
oIsPay = models.BooleanField(default=False)
# 收货地址
oaddress = models.CharField(max_length=100)
# 下单时间
odate = models.DateField(auto_now=True)
# 支付总金额支持:最大6位,包括小数2位
ototal = models.DecimalField(max_digits=6, decimal_places=2)
class OrderDetailInfo(models.Model):
# 结算商品详细信息
goods = models.ForeignKey('goodsapp.GoodsInfo', on_delete=models.CASCADE)
# 结算商品单价
price = models.DecimalField(max_digits=5, decimal_places=2)
# 结算商品数量
count = models.IntegerField()
# 其他订单信息
order = models.ForeignKey('OrderInfo', on_delete=models.CASCADE)<file_sep># Generated by Django 2.2.4 on 2019-10-30 10:54
from django.db import migrations, models
import django.db.models.deletion
import tinymce.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='TypeInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ttitle', models.CharField(max_length=10)),
('isDelete', models.BooleanField(default=False)),
],
),
migrations.CreateModel(
name='GoodsInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('gtitle', models.CharField(max_length=20)),
('gpic', models.ImageField(upload_to='goodsPic')),
('gprice', models.DecimalField(decimal_places=2, max_digits=7)),
('isDelete', models.BooleanField(default=False)),
('gunit', models.CharField(default='500g', max_length=10)),
('gclick', models.IntegerField()),
('gbrief', models.CharField(max_length=100)),
('gstock', models.IntegerField()),
('gcount', tinymce.models.HTMLField()),
('gtype', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='goodsapp.GoodsInfo')),
],
),
]
<file_sep>{% extends 'goodsinfo/base.html' %}
{% block list_detail2 %}
<div class="r_wrap fr clearfix">
<div class="sort_bar">
<a href="/list{{ tid }}_1_1/"
{% if oid == '1' %}
class="active"
{% endif %}
>默认</a>
<a href="/list{{ tid }}_1_2/"
{% if oid == '2' %}
class="active"
{% endif %}
>价格</a>
<a href="/list{{ tid }}_1_3/"
{% if oid == '3' %}
class="active"
{% endif %}
>人气</a>
</div>
<ul class="goods_type_list clearfix">
{% for good in pageobjs %}
<li>
<a href="/detail_{{ good.id }}/"><img src="/static/media/{{ good.gpic }}"></a>
<h4><a href="/detail_{{ good.id }}/">{{ good.gtitle }}</a></h4>
<div class="operate">
<span class="prize">¥{{ good.gprice }}</span>
<span class="unit">{{ good.gprice }}/{{ good.gunit }}</span>
<a href="/cart/add_{{ good.id }}_1/" class="add_goods" title="加入购物车"></a>
</div>
</li>
{% endfor %}
</ul>
<div class="pagenation">
{% if pageobjs.has_previous %}
<a href="/list{{ tid }}_{{ pageobjs.previous_page_number }}_{{ oid }}">上一页<</a>
{% endif %}
{% for pindex in pageobjs.paginator.page_range %}
{% if pindex == pageobjs.number %}
<a href="/list{{ tid }}_{{ pindex }}_{{ oid }}/" class="active">{{ pindex }}</a>
{% else %}
<a href="/list{{ tid }}_{{ pindex }}_{{ oid }}/">{{ pindex }}</a>
{% endif %}
{% endfor %}
{% if pageobjs.has_next %}
<a href="/list{{ tid }}_{{ pageobjs.next_page_number }}_{{ oid }}">下一页></a>
{% endif %}
</div>
</div>
{% endblock %}
{% block content %}
{% endblock %}<file_sep>#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Uson
from django import template
register = template.Library()
@register.filter
def uson_pay(state, ispay):
if ispay == 'ispay':
if state:
return '已支付'
else:
return '未支付'
elif ispay == 'ispay_do':
if state:
return '已付款'
else:
return '未付款'
elif ispay == 'ispay_go':
if state:
return '查看物流'
else:
return '去付款'<file_sep>from django.db import models
from tinymce.models import HTMLField
class TypeInfo(models.Model):
ttitle = models.CharField(max_length=10, verbose_name='商品类型')
isDelete = models.BooleanField(default=False, verbose_name='是否删除')
def __str__(self):
return self.ttitle
class GoodsInfo(models.Model):
gtitle = models.CharField(max_length=20, verbose_name='商品标题')
gpic = models.ImageField(upload_to='goodsPic', verbose_name='商品图片')
gprice = models.DecimalField(max_digits=7, decimal_places=2, verbose_name='商品价格')
isDelete = models.BooleanField(default=False, verbose_name='是否删除')
gunit = models.CharField(max_length=10, default='500g', verbose_name='单位')
gclick = models.IntegerField(verbose_name='商品人气')
gbrief = models.CharField(max_length=100, verbose_name='商品简介')
gstock = models.IntegerField(verbose_name='商品库存') # 库存
gcontent = HTMLField(verbose_name='详情内容')
gtype = models.ForeignKey('TypeInfo', on_delete=models.CASCADE, verbose_name='商品类型')
<file_sep># Generated by Django 2.2.4 on 2019-11-03 04:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orderapp', '0002_auto_20191103_1125'),
]
operations = [
migrations.AlterField(
model_name='orderinfo',
name='odate',
field=models.DateField(auto_now=True),
),
]
<file_sep>from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from orderapp import models
from goodsapp.views import auth_login
from cartapp.models import Cart
from userapp.models import UserInfo
from django.db import transaction
from datetime import datetime
from decimal import Decimal
@auth_login
def order(request):
if request.method == 'GET':
uid = request.session.get('user_id')
userobj = UserInfo.objects.get(pk=uid)
addr_dic = userobj.uaddrs.values('pro').first()
# print(addr_dic)
cids = request.GET.getlist('cid')
# print(cids)
# orderobj_list = models.OrderInfo.objects.filter(user_id=uid)
cartobj_list = []
for cid in cids:
cartobj_list.append(Cart.objects.filter(pk=int(cid)).first())
# print(cid, cartobj_list)
content = {'title': '提交订单页', 'page_name': 1, 'page_char': '提交订单',
'cartobj_list': cartobj_list, 'addr': addr_dic.get('pro')}
return render(request, 'orderinfo/order.html', content)
'''
事务:一旦操作失败,则全部回退
from django.db import transaction
1、创建订单对象
2、判断商品库存
3、创建详单对象
4、修改商品库存
5、删除购物车
'''
if request.method == 'POST':
# 开始设置事务操作
tran_id = transaction.savepoint()
# 接收购物车编号
cids = request.POST.get('cids')
cid_list = cids.split(',')
print("cid_list>>", cid_list)
addr = request.POST.get('address')
total = request.POST.get('total')
print(addr, total)
# 创建订单对象
try:
orderobj = models.OrderInfo()
now_time = datetime.now()
uid = request.session.get('user_id')
orderobj.oid = '%s%d'%(now_time.strftime('%Y%m%d%H%M%S'), uid)
orderobj.user_id = uid
orderobj.odate = now_time
orderobj.oaddress = addr
orderobj.ototal = Decimal(total)
orderobj.save()
for cid in cid_list:
# 创建详单对象
oderdetailobj = models.OrderDetailInfo()
cobj = Cart.objects.get(pk=int(cid))
# 判断商品库存
good = cobj.good
if good.gstock >= cobj.count:
# 减少商品库存
good.gstock -= cobj.count
good.save()
oderdetailobj.goods_id = cobj.good_id
oderdetailobj.count = cobj.count
oderdetailobj.price = cobj.good.gprice
oderdetailobj.order_id = orderobj.oid
oderdetailobj.save()
# 删除购物车
cobj.delete()
else:
transaction.savepoint_rollback(tran_id)
data = {'status': False}
return JsonResponse(data)
orderobj.oIsPay = True
orderobj.save()
transaction.savepoint_commit(tran_id)
except Exception as e:
print(e)
transaction.savepoint_rollback(tran_id)
data = {'status': False}
return JsonResponse(data)
data = {'status': True}
return JsonResponse(data)<file_sep><div class="header_con">
<div class="header">
<div class="welcome fl">欢迎来到天天生鲜!</div>
<div class="fr">
{% if request.session.username|default:'' != '' %} {# 如果用户名不为空,往下执行 #}
<div class="login_info fl">
欢迎您:<em>{{ request.session.username }}</em>
<span>|</span>
<a onclick="return logOut();" href="/user/logout/">退出</a>
{# <a class="logout" href="javascript:;">退出</a>#}
</div>
{% else %}
<div class="login_btn fl">
<a href="/user/login/?next={{ request.path_info }}">登录</a>
<span>|</span>
<a href="/user/register/">注册</a>
</div>
{% endif %}
<div class="user_link fl">
<span>|</span>
<a href="{% url 'user:uinfo' %}">用户中心</a>
<span>|</span>
<a href="{% url 'cart:cart' %}">我的购物车</a>
<span>|</span>
<a href="{% url 'user:uinfo_order' %}">我的订单</a>
</div>
</div>
</div>
</div>
{% comment %}
$('.logout').click(function () {
console.log(123);
$.get('/user/logout/', function (data) {
if(data.status){
location.reload();
}
return false;
});
})
{% endcomment %}<file_sep>from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from userapp import views
app_name = 'userapp'
urlpatterns = [
# path('admin/', admin.site.urls),
# url(r'^$', views.index),
url(r'^register/$', views.register, name='register'),
url(r'^register_exist', views.register_exist, name='register_exist'),
url(r'^login_check/$', views.login_check, name='login_check'),
url(r'^login_check2/$', views.login_check2, name='login_check2'),
url(r'^login/$', views.login, name='login'),
url(r'^logout/$', views.logout, name='logout'),
url(r'^uinfo/$', views.uinfo, name='uinfo'),
url(r'^uinfo_order/', views.uinfo_order, name='uinfo_order'),
url(r'^uinfo_site/$', views.uinfo_site, name='uinfo_site'),
]<file_sep># Generated by Django 2.2.4 on 2019-10-30 11:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('goodsapp', '0002_auto_20191030_1912'),
]
operations = [
migrations.AlterField(
model_name='goodsinfo',
name='gtype',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='goodsapp.TypeInfo'),
),
]
<file_sep># Generated by Django 2.2.4 on 2019-10-30 07:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userapp', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='adress',
name='city',
field=models.CharField(default=None, max_length=20, null=True),
),
migrations.AlterField(
model_name='adress',
name='street',
field=models.CharField(default=None, max_length=20, null=True),
),
]
<file_sep>from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from goodsapp import views
app_name = 'goodsapp'
urlpatterns = [
# path('admin/', admin.site.urls),
url(r'^$', views.index, name='index'),
url(r'^list(?P<tid>\d+)_(?P<pid>\d+)_(?P<oid>\d+)/$', views.list, name='list'),
url(r'^detail_(?P<gid>\d+)/$', views.detail, name='detail'),
# 搜索
url(r'^search/', views.FacetedSearchView(), name='search_view'),
]<file_sep>from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from orderapp import views
app_name = 'orderinfo'
urlpatterns = [
url(r'^$', views.order, name='order'),
]<file_sep># Generated by Django 2.2.4 on 2019-11-03 03:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orderapp', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='orderinfo',
name='odate',
field=models.DateTimeField(auto_now=True),
),
]
<file_sep># Generated by Django 2.2.4 on 2019-10-30 06:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='UserInfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uname', models.CharField(max_length=20, unique=True)),
('upwd', models.CharField(max_length=20)),
('uemail', models.EmailField(max_length=30)),
('recver', models.CharField(max_length=10, null=True)),
('upostal', models.CharField(max_length=6, null=True)),
('uphone', models.CharField(max_length=11, null=True)),
],
),
migrations.CreateModel(
name='Adress',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('pro', models.CharField(max_length=20, null=True)),
('city', models.CharField(max_length=20, null=True)),
('street', models.CharField(max_length=20, null=True)),
('uaddrs', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='uaddrs', to='userapp.UserInfo')),
('ushipaddrs', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ushipaddrs', to='userapp.UserInfo')),
],
),
]
<file_sep>$(function () {
$('.add').click(function () {
var $count = $('.num_show');
$count.val(parseInt($count.val()) + 1);
$count.blur();
});
$('.minus').click(function () {
var $count = $('.num_show');
if($count.val() <= 1){
$count.val(1)
}else{
$count.val(parseInt($count.val()) - 1);
}
$count.blur();
});
$('.num_show, .stock_show').blur(function () {
var num = parseInt($(this).val());
$(this).val(num);
var price = $('.gprice').text();
$('.totalPrice').text((num * parseFloat(price)).toFixed(2) + '元');
})
});<file_sep>function logOut(){
$.get('/user/logout/', function (data) {
if(data.status){
location.reload();
}
});
return false;
}<file_sep>from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from cartapp import views
app_name = 'cartapp'
urlpatterns = [
# path('admin/', admin.site.urls),
url(r'^$', views.cart, name='cart'),
url(r'^add_(?P<gid>\d+)_(?P<cid>\d+)/$', views.addcart, name='addcart'),
# 第一种方式
url(r'^del_(?P<gid>\d+)_(?P<cid>\d+)/$', views.delcart, name='delcart'),
# Ajax方式删除操作(这是第二种方式)
url(r'^delete_(?P<ctid>\d+)/$', views.delete, name='delete'),
# 已移步至orderapp模型设计中,停用
url(r'^post_order/$', views.post_order, name='post_order'),
]<file_sep>from django.shortcuts import render, HttpResponse
from goodsapp import models
from django.core.paginator import Paginator
from userapp.views import auth_login # 仅做页面登录跳转测试
from django.views import defaults
from cartapp.models import Cart
dic404 = {
'guest_cart': 1,
'title': '您访问的页面早已飞到地球之外'
}
def index(request):
if request.method == 'GET':
typelist = models.TypeInfo.objects.all()
countobjs = Cart.objects.filter(user_id=request.session.get('user_id'))
content = {'guest_cart': 1, 'index_clasify': 1, 'countobjs': countobjs}
for i in range(len(typelist)):
content['type' + str(i)] = typelist[0].goodsinfo_set.order_by('-id')[0:4]
content['type' + str(i)*2] = typelist[0].goodsinfo_set.order_by('-gclick')[0:4]
# print(content['type00'][0].id)
content['title'] = '首页'
return render(request, 'goodsinfo/index.html', content)
def list(request, tid, pid, oid):
if request.method == 'GET':
try:
typeobj = models.TypeInfo.objects.get(id = int(tid))
except Exception as e:
print(e)
# return defaults.bad_request(request, e, template_name='404.html')
return render(request, '404.html', dic404)
newgoods = typeobj.goodsinfo_set.order_by('-id')[0:2]
if oid == '1': # 默认根据最新排序
goodslist = models.GoodsInfo.objects.filter(gtype_id=int(tid)).order_by('-id')
elif oid == '2': # 根据价格排序
goodslist = models.GoodsInfo.objects.filter(gtype_id=int(tid)).order_by('-gprice')
elif oid == '3': # 根据点击量排序
goodslist = models.GoodsInfo.objects.filter(gtype_id=int(tid)).order_by('-gclick')
else:
goodslist = models.GoodsInfo.objects.filter(gtype_id=int(tid)).order_by('-id')
paginator = Paginator(goodslist, 1) # 把本页商品对象列表传给分页对象实例化
pageobjs = paginator.page(int(pid)) # 本页所有的商品对象列表
content = {'guest_cart': 1,
'title': typeobj.ttitle+'商品列表页',
'extend_clasify': 1,
'extend_bread': 1,
'recomment': 1,
'newgoods': newgoods,
# 'goods': goodslist, 不用再传了
'pageobjs': pageobjs,
'tid': tid,
'oid': oid,}
countobjs = Cart.objects.filter(user_id=request.session.get('user_id'))
content['countobjs'] = countobjs
return render(request, 'goodsinfo/list.html', content)
# @auth_login
def detail(request, gid):
if request.method == 'GET':
try:
goodobj = models.GoodsInfo.objects.get(id=gid)
except Exception as e:
print(e)
return render(request, '404.html', dic404)
newgoods = goodobj.gtype.goodsinfo_set.order_by('-id')[0:2]
countobjs = Cart.objects.filter(user_id=request.session.get('user_id'))
# 商品点击次数加1
goodobj.gclick = goodobj.gclick + 1
goodobj.save()
content = {#'title': goodobj.gtype.ttitle+'商品详情页',
'title': goodobj.gtitle + '详情页',
'recomment': 1, 'extend_bread': 1, 'extend_clasify': 1,
'guest_cart': 1, 'detail_bread': 1,
'newgoods': newgoods,
'goodobj': goodobj,
'countobjs': countobjs,}
ret = render(request, 'goodsinfo/detail.html', content)
# 新增:实现最近浏览的商品,用于用户中心
goodids = request.COOKIES.get('lately_goodids', '') # 获取lately_goodids字符串
goodobj_id = '%d'%goodobj.id # 把商品id转成字符串
if goodids != '':
# 先将字符串用符号分割成列表,用于统计重复浏览的商品
goodids_list = goodids.split(',')
if goodids_list.count(goodobj_id) >= 1:
goodids_list.remove(goodobj_id) # 删除原先的浏览商品id,更新本次id
goodids_list.insert(0, goodobj_id)
if len(goodids_list) >= 6:
goodids_list.pop(5)
goodids = ','.join(goodids_list)
else:
# 获取到的是空字符串
goodids = goodobj_id # 把当前浏览的商品id给cookie
ret.set_cookie('lately_goodids', goodids)
return ret
# 全文检索
from haystack.views import SearchView
class FacetedSearchView(SearchView):
def extra_context(self):
content = super(FacetedSearchView, self).extra_context()
content['guest_cart'] = 1
content['extend_clasify'] = 1
content['title'] = '天天生鲜网站搜索页'
# 购物车数量更新
countobjs = Cart.objects.filter(user_id=self.request.session.get('user_id'))
content['countobjs'] = countobjs
return content<file_sep># Generated by Django 2.2.4 on 2019-10-30 11:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('goodsapp', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='goodsinfo',
old_name='gcount',
new_name='gcontent',
),
]
<file_sep>from django.db import models
class UserInfo(models.Model):
uname = models.CharField(max_length=20, unique=True)
upwd = models.CharField(max_length=20)
uemail = models.EmailField(max_length=30)
recver = models.CharField(max_length=10, null=True)
upostal = models.CharField(max_length=6, null=True)
uphone = models.CharField(max_length=11, null=True)
class Adress(models.Model):
pro = models.CharField(max_length=20, null=True)
city = models.CharField(max_length=20, null=True, default=None)
street = models.CharField(max_length=20, null=True, default=None)
uaddrs = models.ForeignKey(to='UserInfo', on_delete=models.CASCADE, related_name='uaddrs')
ushipaddrs = models.ForeignKey(to='UserInfo', on_delete=models.CASCADE, related_name='ushipaddrs')
def __str__(self):
return '%s,%s,%s'%(self.pro, self.city, self.street)
|
861e83a14198f8d1452857902a3d2382f2bb79da
|
[
"JavaScript",
"Python",
"HTML"
] | 27
|
Python
|
UsonHo/ttsx
|
3db2ff5524f9b994f8627c88e19b2fecd31d0da4
|
03a0a96d091a2fa86a17e96554d7a31df68b8fe0
|
refs/heads/master
|
<file_sep>package dev.elvir.morecommunication.ui.splas_screen
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import dev.elvir.morecommunication.R
import ua.naiksoftware.stomp.Stomp
import ua.naiksoftware.stomp.StompClient
import ua.naiksoftware.stomp.dto.LifecycleEvent
class SplashScreenActivity : AppCompatActivity() {
lateinit var stompClient: StompClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.act_splash_screen)
createWebSocketClient();
// Handler().postDelayed({
// startActivity(Intent(this, SignInActivity::class.java))
// }, 800)
}
private fun createWebSocketClient() {
stompClient = Stomp.over(
Stomp.ConnectionProvider.OKHTTP,
"ws://192.168.43.244:9090/example-endpoint/websocket"
)
stompClient.connect()
stompClient.lifecycle().subscribe {
when (it.type) {
LifecycleEvent.Type.OPENED -> {
Log.i("WebSocket", "Stomp connection opened");
}
LifecycleEvent.Type.CLOSED -> {
Log.i("WebSocket", "Stomp connection closed");
}
LifecycleEvent.Type.ERROR -> {
Log.i("WebSocket", "Stomp connection error");
it.exception.printStackTrace()
}
}
}
stompClient.topic("/topic/greetings")
.subscribe({
Log.i("WebSocket", "recieved ${it.payload}")
})
stompClient.send("/topic/hello-msg-mapping", "My first STOMP message!").subscribe { }
}
}
class Chat {
var chatId : Long = 123
var chatName : String = "undefined"
var memberSize : Int = 0
var memberId: ArrayList<Long> = arrayListOf(1,2,3)
var lastMessage : String = ""
}
<file_sep>package dev.elvir.morecommunication.ui.sign_in
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import dev.elvir.morecommunication.R
import dev.elvir.morecommunication.ui.main_menu_screen.MainMenuActivity
import kotlinx.android.synthetic.main.act_sign_in_screen.*
class SignInActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.act_sign_in_screen)
btn_enter.setOnClickListener {
startActivity(Intent(this, MainMenuActivity::class.java))
}
}
}<file_sep>package dev.elvir.morecommunication.ui.news_list_screen
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import dev.elvir.morecommunication.R
import dev.elvir.morecommunication.data.model.User
class NewsListAdapter(
val listUser: MutableList<User>
) : RecyclerView.Adapter<NewsListViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsListViewHolder =
NewsListViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.list_item_news_list, parent, false)
)
override fun getItemCount(): Int = listUser.size
override fun onBindViewHolder(holder: NewsListViewHolder, position: Int) {
}
}<file_sep>package dev.elvir.morecommunication.data.model
data class User(
var userName : String = ""
)<file_sep>package dev.elvir.morecommunication.ui.chat
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import dev.elvir.morecommunication.R
import dev.elvir.morecommunication.data.model.Message
import dev.elvir.morecommunication.data.model.MessageType
import kotlinx.android.synthetic.main.fmt_chat_screen.*
class ChatScreenFragment : Fragment() {
var listMessage: MutableList<Message> = mutableListOf()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fmt_chat_screen, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
addMessageList()
rv_chat.layoutManager = LinearLayoutManager(context!!)
rv_chat.adapter = MessageAdapter(listMessage)
}
private fun addMessageList() {
listMessage.add(Message("hello", MessageType.OUTCOMING))
listMessage.add(Message("How are you, bro ?", MessageType.OUTCOMING))
listMessage.add(Message("hey :)", MessageType.INCOMING))
listMessage.add(Message("I am fine.Are you ?", MessageType.INCOMING))
listMessage.add(Message("what did you do yesterday ?", MessageType.OUTCOMING))
}
fun newInstance() = ChatScreenFragment()
}<file_sep>package dev.elvir.morecommunication.ui.chat
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import dev.elvir.morecommunication.data.model.Message
import kotlinx.android.synthetic.main.list_item_outcoming_massage.view.*
class OutcomingMessageViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
fun bind(message: Message) {
val text = view.tv_outcoming_message
text.text = message.text
}
}<file_sep>package dev.elvir.morecommunication.ui.chat_list_screen
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.list_item_chat_list.view.*
class ChatListViewHolder(view: View) : RecyclerView.ViewHolder(view){
val userName = view.tv_user_name
}<file_sep>package dev.elvir.morecommunication.data.model
data class Message (
val text: String = "",
val messageType: MessageType
)
enum class MessageType{
INCOMING,OUTCOMING
}<file_sep>package dev.elvir.morecommunication.ui.chat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import dev.elvir.morecommunication.R
import dev.elvir.morecommunication.data.model.Message
import dev.elvir.morecommunication.data.model.MessageType
class MessageAdapter(
var listMessage: MutableList<Message>
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val VIEW_TYPE_MESSAGE_INCOMING = 1
private val VIEW_TYPE_MESSAGE_OUTCOMING = 2
override fun getItemViewType(position: Int): Int {
return when (listMessage[position].messageType) {
MessageType.INCOMING -> { VIEW_TYPE_MESSAGE_INCOMING }
MessageType.OUTCOMING -> { VIEW_TYPE_MESSAGE_OUTCOMING }
else -> throw RuntimeException("Message view type not found")
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
var view: View
return when (viewType) {
VIEW_TYPE_MESSAGE_INCOMING -> {
IncomingMessageViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.list_item_incoming_massage, parent, false)
)
}
VIEW_TYPE_MESSAGE_OUTCOMING -> {
OutcomingMessageViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.list_item_outcoming_massage, parent, false)
)
}
else -> throw RuntimeException("Message view holder type not found")
}
}
override fun getItemCount(): Int = listMessage.size
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
var message = listMessage[position]
when (holder.itemViewType) {
VIEW_TYPE_MESSAGE_INCOMING -> {
(holder as IncomingMessageViewHolder).bind(message)
}
VIEW_TYPE_MESSAGE_OUTCOMING -> {
(holder as OutcomingMessageViewHolder).bind(message)
}
}
}
}<file_sep>package dev.elvir.morecommunication.data.model
data class ChatList(
var userList : MutableList<User>?,
var messageList: MutableList<Message>?
)<file_sep>package dev.elvir.morecommunication.ui.news_list_screen
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.list_item_chat_list.view.*
class NewsListViewHolder(view: View) : RecyclerView.ViewHolder(view){
}<file_sep>package dev.elvir.morecommunication.ui.chat
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import dev.elvir.morecommunication.data.model.Message
import kotlinx.android.synthetic.main.list_item_incoming_massage.view.*
class IncomingMessageViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
fun bind(message: Message) {
val text = view.tv_incoming_message
text.text = message.text
}
}<file_sep>package dev.elvir.morecommunication.ui.chat_list_screen
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import dev.elvir.morecommunication.R
import dev.elvir.morecommunication.data.model.User
class ChatListAdapter(
val listUser: MutableList<User>
) : RecyclerView.Adapter<ChatListViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatListViewHolder =
ChatListViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.list_item_chat_list, parent, false)
)
override fun getItemCount(): Int = listUser.size
override fun onBindViewHolder(holder: ChatListViewHolder, position: Int) {
holder.userName.text = listUser[position].userName
}
}<file_sep>package dev.elvir.morecommunication.ui.main_menu_screen
import android.os.Bundle
import androidx.annotation.IdRes
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.etebarian.meowbottomnavigation.MeowBottomNavigation
import dev.elvir.morecommunication.R
import dev.elvir.morecommunication.ui.chat_list_screen.ChatListScreenFragment
import dev.elvir.morecommunication.ui.news_list_screen.NewsListScreenFragment
import kotlinx.android.synthetic.main.act_main_menu_screen.*
class MainMenuActivity : AppCompatActivity() {
private var fragmentChatList = ChatListScreenFragment.newInstance()
private var fragmentNewsList = NewsListScreenFragment.newInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.act_main_menu_screen)
bn_main_navigation.add(MeowBottomNavigation.Model(1, R.drawable.ic_chat))
bn_main_navigation.add(MeowBottomNavigation.Model(2, R.drawable.ic_newspaper))
bn_main_navigation.add(MeowBottomNavigation.Model(3, R.drawable.ic_screen_player))
bn_main_navigation.add(MeowBottomNavigation.Model(4, R.drawable.ic_user))
bn_main_navigation.setOnClickMenuListener { handlerBottomMenuNavigation(it.id) }
bn_main_navigation.show(1)
addFragment(R.id.rootContainer, fragmentChatList, "")
addFragment(R.id.rootContainer, fragmentNewsList, "")
supportFragmentManager.beginTransaction().hide(fragmentNewsList).commit()
}
private fun handlerBottomMenuNavigation(id: Int) {
when (id) {
1 -> {
if (fragmentChatList.isHidden) {
supportFragmentManager.beginTransaction()
.show(fragmentChatList)
.commit()
supportFragmentManager.beginTransaction().hide(fragmentNewsList).commit()
}
}
2 -> {
if (fragmentNewsList.isHidden) {
supportFragmentManager.beginTransaction()
.show(fragmentNewsList)
.commit()
supportFragmentManager.beginTransaction().hide(fragmentChatList).commit()
}
}
else -> {
}
}
}
public fun addFragment(
@IdRes containerViewId: Int,
fragment: Fragment,
fragmentTag: String
) {
supportFragmentManager
.beginTransaction()
.add(containerViewId, fragment, fragmentTag)
.disallowAddToBackStack()
.commit()
}
public fun replaceFragment(
@IdRes containerViewId: Int,
fragment: Fragment,
fragmentTag: String,
@Nullable backStackStateName: String?
) {
supportFragmentManager
.beginTransaction()
.replace(containerViewId, fragment, fragmentTag)
.addToBackStack(backStackStateName)
.commit()
}
}<file_sep>rootProject.name='MoreCommunication'
include ':app'
<file_sep>package dev.elvir.morecommunication.ui.news_list_screen
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import dev.elvir.morecommunication.R
import dev.elvir.morecommunication.data.model.User
import dev.elvir.morecommunication.ui.chat.ChatScreenFragment
import dev.elvir.morecommunication.ui.chat_list_screen.ChatListAdapter
import dev.elvir.morecommunication.ui.main_menu_screen.MainMenuActivity
import kotlinx.android.synthetic.main.fmt_chat_list_screen.*
import kotlinx.android.synthetic.main.fmt_news_list_screen.*
class NewsListScreenFragment : Fragment(){
var listUser : MutableList<User> = mutableListOf()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fmt_news_list_screen,container,false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
addChatList()
rv_news_list.layoutManager = LinearLayoutManager(context!!)
rv_news_list.adapter = NewsListAdapter(listUser)
}
fun addChatList(){
listUser.add(User("<NAME>"))
listUser.add(User("<NAME> "))
listUser.add(User("<NAME>"))
listUser.add(User("<NAME>"))
}
companion object {
fun newInstance() = NewsListScreenFragment()
}
}<file_sep>package dev.elvir.morecommunication.ui.chat_list_screen
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import dev.elvir.morecommunication.R
import dev.elvir.morecommunication.data.model.User
import dev.elvir.morecommunication.ui.chat.ChatScreenFragment
import dev.elvir.morecommunication.ui.main_menu_screen.MainMenuActivity
import kotlinx.android.synthetic.main.fmt_chat_list_screen.*
class ChatListScreenFragment : Fragment(){
var listUser : MutableList<User> = mutableListOf()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fmt_chat_list_screen,container,false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
addChatList()
rv_chat_list.layoutManager = LinearLayoutManager(context!!)
rv_chat_list.adapter = ChatListAdapter(listUser)
}
fun addChatList(){
listUser.add(User("<NAME>"))
listUser.add(User("<NAME> "))
listUser.add(User("<NAME>"))
listUser.add(User("<NAME>"))
}
companion object {
fun newInstance() = ChatListScreenFragment()
}
}
|
b8f7862daee032a810d3612594408fd04aeebbd5
|
[
"Kotlin",
"Gradle"
] | 17
|
Kotlin
|
raullek/android-more
|
b39fd10b31512bf7762324a588a3eefbd0cd54d8
|
cc23c6b47b65ff69eeec0cf7146c753ce1b0ad3a
|
refs/heads/master
|
<repo_name>Upjaka/quaternion<file_sep>/src/test/java/QuaternionTest.java
import org.junit.jupiter.api.Test;
import Work1.Quaternion;
import Work1.Vector;
import static java.lang.Math.*;
import static org.junit.jupiter.api.Assertions.*;
import static junit.framework.TestCase.fail;
class QuaternionTest {
private Quaternion q1 = new Quaternion(1, 2, 3, 4);
private Quaternion q2 = new Quaternion(4, 3, 2, 1);
private Quaternion q3 = new Quaternion(2, 2, 2, 2);
private Quaternion q0 = new Quaternion(0, 0, 0, 0);
@Test
void plus() {
assertEquals(q1.plus(q2), new Quaternion(5, 5, 5, 5));
}
@Test
void minus() {
assertEquals(q1.minus(q2), new Quaternion(-3, -1, 1, 3));
}
@Test
void multiply() {
assertEquals(q1.multiply(8), new Quaternion(8, 16, 24, 32 ));
assertEquals(q1.multiply(q3), new Quaternion(-16, 4, 12, 8));
assertEquals(q1.multiply(q0), q0);
}
@Test
void interfacing() {
assertEquals(q1.interfacing(), new Quaternion(1, -2, -3, -4));
}
@Test
void abs() {
assertEquals(q3.abs(), 4);
}
@Test
void division() {
assertEquals(q1.division(new Quaternion(0.125, -0.125, -0.125, -0.125)),
new Quaternion(-16, 4, 12, 8));
try {
q1.division(q0);
fail();
} catch (IllegalArgumentException e) {
assertTrue(true);
}
}
@Test
void scalar() {
assertEquals(q1.scalar(), 1);
}
@Test
void vector() {
assertEquals(q1.vector(), new Work1.Vector(2, 3, 4));
}
@Test
void normalise() {
assertEquals(new Quaternion(4, 4, 4, 4).normalise(),
new Quaternion(0.5, 0.5, 0.5, 0.5));
try {
q0.normalise();
fail();
} catch (IllegalArgumentException e) {
assertTrue(true);
}
}
@Test
void getAngle() {
Quaternion q5 = new Quaternion(1, 0, 0, 0);
double angle = PI / 2;
Vector axis = new Vector(1 / sqrt(3), 1 / sqrt(3), 1 / sqrt(3));
assertEquals(new Quaternion(angle, axis).getAngle(), PI / 2);
try {
q5.getAngle();
fail();
} catch (IllegalArgumentException e) {
assertTrue(true);
}
}
@Test
void getAxis() {
Quaternion q5 = new Quaternion(1, 0, 0, 0);
double angle = PI / 3;
Vector axis = new Vector(1 / sqrt(3), 1 / sqrt(3), 1 / sqrt(3));
assertEquals(new Quaternion(angle, axis).getAxis(), axis);
try {
q5.getAxis();
fail();
} catch (IllegalArgumentException e) {
assertTrue(true);
}
}
@Test
void equals() {
Quaternion q4 = q1;
assertEquals(q1.equals(1.5), false);
assertEquals(q1.equals(q4), true);
assertEquals(q1.equals(new Quaternion(2, 3, 4, 5)), false);
}
@Test
void Quaternion() {
double angle = PI / 3;
Vector axis = new Vector(1 / sqrt(3), 1 / sqrt(3), 1 / sqrt(3));
assertEquals(new Quaternion(angle, axis),
new Quaternion(cos(angle / 2), axis.multiply(sin(angle / 2)).x,
axis.multiply(sin(angle / 2)).y, axis.multiply(sin(angle / 2)).z));
try {
new Quaternion(angle, axis.multiply(2));
fail();
} catch(IllegalArgumentException e) {
assertTrue(true);
}
}
}<file_sep>/src/main/java/work1/Vector.java
package Work1;
import static java.lang.Math.sqrt;
import static java.lang.Math.ulp;
/** Вспомогательный класс, реализующий векторы в трехмерном евклидовом пространстве */
public class Vector {
public double x;
public double y;
public double z;
public Vector(double a, double b, double c) {
this.x = a;
this.y = b;
this.z = c;
}
/**
* Модуль вектора
*/
public double abs() {
return sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
}
/**
* Умножение вектора на число
*/
public Vector multiply(double number) {
return new Vector(this.x * number, this.y * number, this.z * number);
}
/**
* Перееопределение метода equals
*/
@Override
public boolean equals(Object obj) {
double eps = ulp(1.0);
if (obj == null || obj.getClass() != this.getClass())
return false;
else if (this == obj)
return true;
else {
Vector other = (Vector) obj;
return ((Math.abs(x - other.x) < eps) &&
(Math.abs(y - other.y) < eps) &&
(Math.abs(z - other.z) < eps));
}
}
@Override
public String toString() {
return String.format("(%f, %f, %f)", this.x, this.y, this.z);
}
}<file_sep>/src/main/java/work1/Quaternion.java
package Work1;
import static java.lang.Math.*;
public class Quaternion {
private double a;
private double b;
private double c;
private double d;
public Quaternion(double a, double b, double c, double d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
public Quaternion(double angle, Vector axisOf) {
if ((axisOf.abs() != 1) || (angle == 0)) throw new IllegalArgumentException();
this.a = cos(angle / 2);
this.b = axisOf.x * sin(angle / 2);
this.c = axisOf.y * sin(angle / 2);
this.d = axisOf.z * sin(angle / 2);
}
/**
* Сложение
*/
public Quaternion plus(Quaternion q) {
return new Quaternion(this.a + q.a, this.b + q.b,
this.c + q.c, this.d + q.d);
}
/**
* Вычитание
*/
public Quaternion minus(Quaternion q) {
return new Quaternion(this.a - q.a, this.b - q.b,
this.c - q.c, this.d - q.d);
}
/**
* Умножение на вещественное число
*/
public Quaternion multiply(double number) {
return new Quaternion(this.a * number, this.b * number, this.c * number, this.d * number);
}
/**
* Сопржение
*/
public Quaternion interfacing() {
return new Quaternion(this.a, -this.b, -this.c, -this.d);
}
/**
* Модуль
*/
public double abs() {
return sqrt(this.a * this.a + this.b * this.b + this.c * this.c + this.d * this.d);
}
/**
* Умножение на кватернион
*/
public Quaternion multiply(Quaternion q) {
double a = this.a * q.a - this.b * q.b - this.c * q.c - this.d * q.d;
double b = this.a * q.b + this.b * q.a + this.c * q.d - this.d * q.c;
double c = this.a * q.c + this.c * q.a + this.d * q.b - this.b * q.d;
double d = this.a * q.d + this.d * q.a + this.b * q.c - this.c * q.b;
return new Quaternion(a, b, c, d);
}
/**
* Деление
*/
public Quaternion division(Quaternion q) {
if (q.abs() == 0) throw new IllegalArgumentException();
else {
Quaternion backQuaternion = q.interfacing().multiply(1 / pow(q.abs(), 2));
return this.multiply(backQuaternion);
}
}
/**
* Выделение скалярной части
*/
public double scalar() {
return this.a;
}
/**
* Выделение векторной части
*/
public Vector vector() {
return new Vector(this.b, this.c, this.d);
}
/**
* Нормализация
*/
public Quaternion normalise() {
if (this.abs() == 0) throw new IllegalArgumentException();
else {
return this.multiply(1 / this.abs());
}
}
/**
* Определение оси поворота
*/
public Vector getAxis()
{
if (sin(this.getAngle() / 2) == 0) throw new IllegalArgumentException();
else {
if ((this.abs() != 1) && (this.multiply(1 / sin(this.getAngle() / 2)).vector().abs() != 1))
throw new IllegalArgumentException();
else return this.multiply(1 / sin(this.getAngle() / 2)).vector();
}
}
/**
* Определение угла поворта
*/
public double getAngle() {
if ((this.abs() != 1) || (this.vector().abs() == 0))
throw new IllegalArgumentException();
else return acos(this.a) * 2;
}
/**
* Перееопределение метода equals
*/
@Override
public boolean equals(Object obj) {
double eps = ulp(1.0);
if (obj == null || obj.getClass() != this.getClass())
return false;
else if (this == obj)
return true;
else {
Quaternion other = (Quaternion) obj;
return ((Math.abs(a - other.a) < eps) &&
(Math.abs(b - other.b) < eps) &&
(Math.abs(c - other.c) < eps) &&
(Math.abs(d - other.d) < eps));
}
}
/**
* Переопределение метода toString (для собственного удобства)
*/
@Override
public String toString() {
return String.format("(%f, %f, %f, %f)", this.a, this.b, this.c, this.d);
}
}
|
f23c174317c8f1d5aa0a799c4284416870f389ea
|
[
"Java"
] | 3
|
Java
|
Upjaka/quaternion
|
bd24441b042e856d82634c6fed9ac303f49db1e9
|
d4ddbde219c968be5ad329c9a4b623b3b335df56
|
refs/heads/main
|
<repo_name>Fil/d3-geo-voronoi<file_sep>/src/cartesian.js
import { asin, atan2, cos, sin, sqrt } from "./math.js";
export function spherical(cartesian) {
return [atan2(cartesian[1], cartesian[0]), asin(cartesian[2])];
}
export function cartesian(spherical) {
const lambda = spherical[0],
phi = spherical[1],
cosPhi = cos(phi);
return [cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)];
}
export function cartesianDot(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
export function cartesianCross(a, b) {
return [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
}
// TODO return a
export function cartesianAddInPlace(a, b) {
(a[0] += b[0]), (a[1] += b[1]), (a[2] += b[2]);
}
export function cartesianAdd(a, b) {
return [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
}
export function cartesianScale(vector, k) {
return [vector[0] * k, vector[1] * k, vector[2] * k];
}
// TODO return d
export function cartesianNormalizeInPlace(d) {
var l = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
(d[0] /= l), (d[1] /= l), (d[2] /= l);
}
export function cartesianNormalize(d) {
var l = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
return [d[0] / l, d[1] / l, d[2] / l];
}
<file_sep>/src/delaunay.js
import { Delaunay } from "d3-delaunay";
import { geoRotation, geoStereographic } from "d3-geo";
import { extent } from "d3-array";
import {
asin,
atan2,
cos,
degrees,
max,
min,
radians,
sign,
sin,
sqrt,
} from "./math.js";
import {
cartesianNormalize as normalize,
cartesianCross as cross,
cartesianDot as dot,
cartesianAdd,
} from "./cartesian.js";
// Converts 3D Cartesian to spherical coordinates (degrees).
function spherical(cartesian) {
return [
atan2(cartesian[1], cartesian[0]) * degrees,
asin(max(-1, min(1, cartesian[2]))) * degrees,
];
}
// Converts spherical coordinates (degrees) to 3D Cartesian.
function cartesian(coordinates) {
const lambda = coordinates[0] * radians,
phi = coordinates[1] * radians,
cosphi = cos(phi);
return [cosphi * cos(lambda), cosphi * sin(lambda), sin(phi)];
}
// Spherical excess of a triangle (in spherical coordinates)
export function excess(triangle) {
triangle = triangle.map((p) => cartesian(p));
return dot(triangle[0], cross(triangle[2], triangle[1]));
}
export function geoDelaunay(points) {
const delaunay = geo_delaunay_from(points),
triangles = geo_triangles(delaunay),
edges = geo_edges(triangles, points),
neighbors = geo_neighbors(triangles, points.length),
find = geo_find(neighbors, points),
// Voronoi ; could take a center function as an argument
circumcenters = geo_circumcenters(triangles, points),
{ polygons, centers } = geo_polygons(circumcenters, triangles, points),
mesh = geo_mesh(polygons),
hull = geo_hull(triangles, points),
// Urquhart ; returns a function that takes a distance array as argument.
urquhart = geo_urquhart(edges, triangles);
return {
delaunay,
edges,
triangles,
centers,
neighbors,
polygons,
mesh,
hull,
urquhart,
find,
};
}
function geo_find(neighbors, points) {
function distance2(a, b) {
let x = a[0] - b[0],
y = a[1] - b[1],
z = a[2] - b[2];
return x * x + y * y + z * z;
}
return function find(x, y, next) {
if (next === undefined) next = 0;
let cell,
dist,
found = next;
const xyz = cartesian([x, y]);
do {
cell = next;
next = null;
dist = distance2(xyz, cartesian(points[cell]));
neighbors[cell].forEach((i) => {
let ndist = distance2(xyz, cartesian(points[i]));
if (ndist < dist) {
dist = ndist;
next = i;
found = i;
return;
}
});
} while (next !== null);
return found;
};
}
function geo_delaunay_from(points) {
if (points.length < 2) return {};
// find a valid point to send to infinity
let pivot = 0;
while (isNaN(points[pivot][0] + points[pivot][1]) && pivot++ < points.length);
const r = geoRotation(points[pivot]),
projection = geoStereographic()
.translate([0, 0])
.scale(1)
.rotate(r.invert([180, 0]));
points = points.map(projection);
const zeros = [];
let max2 = 1;
for (let i = 0, n = points.length; i < n; i++) {
let m = points[i][0] ** 2 + points[i][1] ** 2;
if (!isFinite(m) || m > 1e32) zeros.push(i);
else if (m > max2) max2 = m;
}
const FAR = 1e6 * sqrt(max2);
zeros.forEach((i) => (points[i] = [FAR, 0]));
// Add infinite horizon points
points.push([0, FAR]);
points.push([-FAR, 0]);
points.push([0, -FAR]);
const delaunay = Delaunay.from(points);
delaunay.projection = projection;
// clean up the triangulation
const { triangles, halfedges, inedges } = delaunay;
const degenerate = [];
for (let i = 0, l = halfedges.length; i < l; i++) {
if (halfedges[i] < 0) {
const j = i % 3 == 2 ? i - 2 : i + 1;
const k = i % 3 == 0 ? i + 2 : i - 1;
const a = halfedges[j];
const b = halfedges[k];
halfedges[a] = b;
halfedges[b] = a;
halfedges[j] = halfedges[k] = -1;
triangles[i] = triangles[j] = triangles[k] = pivot;
inedges[triangles[a]] = a % 3 == 0 ? a + 2 : a - 1;
inedges[triangles[b]] = b % 3 == 0 ? b + 2 : b - 1;
degenerate.push(Math.min(i, j, k));
i += 2 - (i % 3);
} else if (triangles[i] > points.length - 3 - 1) {
triangles[i] = pivot;
}
}
// there should always be 4 degenerate triangles
// console.warn(degenerate);
return delaunay;
}
function geo_edges(triangles, points) {
const _index = new Set();
if (points.length === 2) return [[0, 1]];
triangles.forEach((tri) => {
if (tri[0] === tri[1]) return;
if (excess(tri.map((i) => points[i])) < 0) return;
for (let i = 0, j; i < 3; i++) {
j = (i + 1) % 3;
_index.add(extent([tri[i], tri[j]]).join("-"));
}
});
return Array.from(_index, (d) => d.split("-").map(Number));
}
function geo_triangles(delaunay) {
const { triangles } = delaunay;
if (!triangles) return [];
const geo_triangles = [];
for (let i = 0, n = triangles.length / 3; i < n; i++) {
const a = triangles[3 * i],
b = triangles[3 * i + 1],
c = triangles[3 * i + 2];
if (a !== b && b !== c) {
geo_triangles.push([a, c, b]);
}
}
return geo_triangles;
}
function geo_circumcenters(triangles, points) {
// if (!use_centroids) {
return triangles.map((tri) => {
const c = tri.map((i) => points[i]).map(cartesian),
V = cartesianAdd(
cartesianAdd(cross(c[1], c[0]), cross(c[2], c[1])),
cross(c[0], c[2])
);
return spherical(normalize(V));
});
/*} else {
return triangles.map(tri => {
return d3.geoCentroid({
type: "MultiPoint",
coordinates: tri.map(i => points[i])
});
});
}*/
}
function geo_neighbors(triangles, npoints) {
const neighbors = [];
triangles.forEach((tri) => {
for (let j = 0; j < 3; j++) {
const a = tri[j],
b = tri[(j + 1) % 3];
neighbors[a] = neighbors[a] || [];
neighbors[a].push(b);
}
});
// degenerate cases
if (triangles.length === 0) {
if (npoints === 2) (neighbors[0] = [1]), (neighbors[1] = [0]);
else if (npoints === 1) neighbors[0] = [];
}
return neighbors;
}
function geo_polygons(circumcenters, triangles, points) {
const polygons = [];
const centers = circumcenters.slice();
if (triangles.length === 0) {
if (points.length < 2) return { polygons, centers };
if (points.length === 2) {
// two hemispheres
const a = cartesian(points[0]),
b = cartesian(points[1]),
m = normalize(cartesianAdd(a, b)),
d = normalize(cross(a, b)),
c = cross(m, d);
const poly = [
m,
cross(m, c),
cross(cross(m, c), c),
cross(cross(cross(m, c), c), c),
]
.map(spherical)
.map(supplement);
return (
polygons.push(poly),
polygons.push(poly.slice().reverse()),
{ polygons, centers }
);
}
}
triangles.forEach((tri, t) => {
for (let j = 0; j < 3; j++) {
const a = tri[j],
b = tri[(j + 1) % 3],
c = tri[(j + 2) % 3];
polygons[a] = polygons[a] || [];
polygons[a].push([b, c, t, [a, b, c]]);
}
});
// reorder each polygon
const reordered = polygons.map((poly) => {
const p = [poly[0][2]]; // t
let k = poly[0][1]; // k = c
for (let i = 1; i < poly.length; i++) {
// look for b = k
for (let j = 0; j < poly.length; j++) {
if (poly[j][0] == k) {
k = poly[j][1];
p.push(poly[j][2]);
break;
}
}
}
if (p.length > 2) {
return p;
} else if (p.length == 2) {
const R0 = o_midpoint(
points[poly[0][3][0]],
points[poly[0][3][1]],
centers[p[0]]
),
R1 = o_midpoint(
points[poly[0][3][2]],
points[poly[0][3][0]],
centers[p[0]]
);
const i0 = supplement(R0),
i1 = supplement(R1);
return [p[0], i1, p[1], i0];
}
});
function supplement(point) {
let f = -1;
centers.slice(triangles.length, Infinity).forEach((p, i) => {
if (p[0] === point[0] && p[1] === point[1]) f = i + triangles.length;
});
if (f < 0) (f = centers.length), centers.push(point);
return f;
}
return { polygons: reordered, centers };
}
function o_midpoint(a, b, c) {
a = cartesian(a);
b = cartesian(b);
c = cartesian(c);
const s = sign(dot(cross(b, a), c));
return spherical(normalize(cartesianAdd(a, b)).map((d) => s * d));
}
function geo_mesh(polygons) {
const mesh = [];
polygons.forEach((poly) => {
if (!poly) return;
let p = poly[poly.length - 1];
for (let q of poly) {
if (q > p) mesh.push([p, q]);
p = q;
}
});
return mesh;
}
function geo_urquhart(edges, triangles) {
return function (distances) {
const _lengths = new Map(),
_urquhart = new Map();
edges.forEach((edge, i) => {
const u = edge.join("-");
_lengths.set(u, distances[i]);
_urquhart.set(u, true);
});
triangles.forEach((tri) => {
let l = 0,
remove = -1;
for (let j = 0; j < 3; j++) {
let u = extent([tri[j], tri[(j + 1) % 3]]).join("-");
if (_lengths.get(u) > l) {
l = _lengths.get(u);
remove = u;
}
}
_urquhart.set(remove, false);
});
return edges.map((edge) => _urquhart.get(edge.join("-")));
};
}
function geo_hull(triangles, points) {
const _hull = new Set(),
hull = [];
triangles.map((tri) => {
if (excess(tri.map((i) => points[i > points.length ? 0 : i])) > 1e-12)
return;
for (let i = 0; i < 3; i++) {
let e = [tri[i], tri[(i + 1) % 3]],
code = `${e[0]}-${e[1]}`;
if (_hull.has(code)) _hull.delete(code);
else _hull.add(`${e[1]}-${e[0]}`);
}
});
const _index = new Map();
let start;
_hull.forEach((e) => {
e = e.split("-").map(Number);
_index.set(e[0], e[1]);
start = e[0];
});
if (start === undefined) return hull;
let next = start;
do {
hull.push(next);
let n = _index.get(next);
_index.set(next, -1);
next = n;
} while (next > -1 && next !== start);
return hull;
}
<file_sep>/src/index.js
export { geoDelaunay } from "./delaunay.js";
export { geoVoronoi } from "./voronoi.js";
export { geoContour } from "./contour.js";
<file_sep>/src/math.js
export const epsilon = 1e-6;
export const epsilon2 = 1e-12;
export const pi = Math.PI;
export const halfPi = pi / 2;
export const quarterPi = pi / 4;
export const tau = pi * 2;
export const degrees = 180 / pi;
export const radians = pi / 180;
export const abs = Math.abs;
export const atan = Math.atan;
export const atan2 = Math.atan2;
export const cos = Math.cos;
export const ceil = Math.ceil;
export const exp = Math.exp;
export const floor = Math.floor;
export const log = Math.log;
export const max = Math.max;
export const min = Math.min;
export const pow = Math.pow;
export const sin = Math.sin;
export const sign =
Math.sign ||
function (x) {
return x > 0 ? 1 : x < 0 ? -1 : 0;
};
export const sqrt = Math.sqrt;
export const tan = Math.tan;
export function acos(x) {
return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);
}
export function asin(x) {
return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);
}
export function haversin(x) {
return (x = sin(x / 2)) * x;
}
<file_sep>/test/geo-voronoi-test.js
import assert from "assert";
import { promises as fs } from "fs";
import * as path from "path";
import * as geoVoronoi from "../src/index.js";
const sites = [
[0, 0],
[10, 0],
[0, 10],
];
it("geoVoronoi() returns a Diagram.", () => {
assert.strictEqual(typeof geoVoronoi, "object");
assert.strictEqual(typeof geoVoronoi.geoVoronoi, "function");
assert.strictEqual(typeof geoVoronoi.geoVoronoi(), "function");
assert.strictEqual(typeof geoVoronoi.geoVoronoi([]), "function");
assert.strictEqual(typeof geoVoronoi.geoVoronoi().links, "function");
assert.strictEqual(typeof geoVoronoi.geoVoronoi().links([]), "object");
assert.strictEqual(typeof geoVoronoi.geoVoronoi().polygons, "function");
assert.strictEqual(typeof geoVoronoi.geoVoronoi().polygons([]), "object");
assert.strictEqual(typeof geoVoronoi.geoVoronoi().triangles, "function");
assert.strictEqual(typeof geoVoronoi.geoVoronoi().triangles([]), "object");
});
it("geoVoronoi.polygons(sites) hemisphere test", () => {
const two_sites = [
[-20, -20],
[20, 20],
];
const polygons = geoVoronoi.geoVoronoi(two_sites).polygons();
assert.deepStrictEqual(polygons.features[0].geometry, {
type: "Polygon",
coordinates: [
[
[0, 0],
[90, -43.21917889371418],
[180, -0],
[-90, 43.21917889371418],
[0, 0],
],
],
});
assert.deepStrictEqual(polygons.features[1].geometry, {
type: "Polygon",
coordinates: [
[
[-90, 43.21917889371418],
[180, -0],
[90, -43.21917889371418],
[0, 0],
[-90, 43.21917889371418],
],
],
});
});
it("geoVoronoi.polygons(sites) returns polygons.", () => {
const u = geoVoronoi.geoVoronoi(sites).polygons().features[0].geometry
.coordinates[0][0],
v = [-175, -4.981069];
assert(Math.abs(u[0] - v[0]) < 1e-6 && Math.abs(u[1] - v[1]) < 1e-6);
});
it("geoVoronoi.polygons(sites) tolerates NaN.", () => {
//const u = geoVoronoi.geoVoronoi().polygons(sites)[0][0], v = [ 5, 4.981069 ];
//assert( (Math.abs(u[0]-v[0]) < 1e-6) && (Math.abs(u[1]-v[1]) < 1e-6) );
const sites = [
[0, 0],
[2, 1],
[NaN, -1],
[4, NaN],
[5, 10],
];
const u = geoVoronoi.geoVoronoi(sites).polygons();
assert(u);
});
it("geoVoronoi.polygons([no valid site]) returns an empty collection.", () => {
const sites = [
[NaN, -1],
[4, NaN],
[Infinity, 10],
];
const u = geoVoronoi.geoVoronoi(sites).polygons();
assert.deepStrictEqual(u.features, []);
});
it("geoVoronoi.polygons([1 site]) returns a Sphere.", () => {
const sites = [
[NaN, -1],
[4, NaN],
[5, 10],
];
const u = geoVoronoi.geoVoronoi(sites).polygons();
assert.strictEqual(u.features[0].type, "Feature");
assert.strictEqual(u.features[0].geometry.type, "Sphere");
});
it("geoVoronoi.links() returns urquhart.", () => {
assert.deepStrictEqual(
geoVoronoi
.geoVoronoi()
.links(sites)
.features.map(function (d) {
return d.properties.urquhart;
}),
[false, true, true]
);
});
it("geoVoronoi.x() changes accessor.", () => {
const sites = [
{ lon: 10, lat: 0 },
{ lon: 3, lat: 5 },
{ lon: -2, lat: 5 },
];
assert.deepStrictEqual(
geoVoronoi
.geoVoronoi()
.x((d) => +d.lon)
.y((d) => +d.lat)(sites).points,
[
[10, 0],
[3, 5],
[-2, 5],
]
);
});
it("geoVoronoi.hull() computes the hull.", () => {
const sites = [
[10, 0],
[10, 10],
[3, 5],
[-2, 5],
[0, 0],
];
assert.deepStrictEqual(geoVoronoi.geoVoronoi().hull(sites), {
type: "Polygon",
coordinates: [
[
[10, 0],
[0, 0],
[-2, 5],
[10, 10],
[10, 0],
],
],
});
});
it("geoVoronoi.mesh() computes the Delaunay mesh.", () => {
const sites = [
[10, 0],
[10, 10],
[3, 5],
[-2, 5],
[0, 0],
];
assert.deepStrictEqual(geoVoronoi.geoVoronoi().mesh(sites), {
type: "MultiLineString",
coordinates: [
[
[3, 5],
[-2, 5],
],
[
[3, 5],
[0, 0],
],
[
[-2, 5],
[0, 0],
],
[
[10, 10],
[-2, 5],
],
[
[10, 10],
[3, 5],
],
[
[10, 0],
[3, 5],
],
[
[10, 0],
[0, 0],
],
[
[10, 0],
[10, 10],
],
],
});
});
it("geoVoronoi.cellMesh() computes the Polygons mesh.", () => {
const sites = [
[10, 0],
[10, 10],
[3, 5],
[-2, 5],
[0, 0],
];
const cellMesh = geoVoronoi.geoVoronoi().cellMesh(sites),
coords = cellMesh.coordinates
.map((d) =>
d
.map((e) => e.map(Math.round).join(" "))
.sort()
.join("/")
)
.sort();
assert.deepStrictEqual(coords, [
"-175 -5/-175 -5",
"-175 -5/0 3",
"-175 -5/1 15",
"-175 -5/5 0",
"-175 -5/8 5",
"0 3/1 15",
"0 3/5 0",
"1 15/8 5",
"5 0/8 5",
]);
});
it("geoVoronoi.find() finds p", () => {
const sites = [
[10, 0],
[10, 10],
[3, 5],
[-2, 5],
[0, 0],
],
voro = geoVoronoi.geoVoronoi(sites);
assert.strictEqual(voro.find(1, 1), 4);
assert.strictEqual(voro.find(1, 1, 4), 4);
});
it("geoVoronoi.links(sites) returns links.", () => {
assert.deepStrictEqual(
geoVoronoi
.geoVoronoi()
.links(sites)
.features.map(function (d) {
return d.properties.source[0];
}),
[10, 0, 0]
);
});
it("geoVoronoi.triangles(sites) returns geojson.", () => {
const tri = geoVoronoi.geoVoronoi().triangles(sites);
assert.strictEqual(tri.type, "FeatureCollection");
assert.strictEqual(tri.features.length, 1);
});
it("geoVoronoi.links(sites) returns urquhart graph.", () => {
assert.deepStrictEqual(
geoVoronoi
.geoVoronoi()
.links(sites)
.features.map(function (d) {
return d.properties.urquhart;
}),
[false, true, true]
);
});
it("geoVoronoi.triangles(sites) returns circumcenters.", () => {
const u = geoVoronoi.geoVoronoi().triangles(sites).features[0]
.properties.circumcenter,
v = [5, 4.981069],
w = [-180 + v[0], -v[1]];
assert(
(Math.abs(u[0] - v[0]) < 1e-6 && Math.abs(u[1] - v[1]) < 1e-6) ||
(Math.abs(u[0] - w[0]) < 1e-6 && Math.abs(u[1] - w[1]) < 1e-6)
);
});
it("geoVoronoi’s delaunay does not list fake points in its triangles", () => {
const u = geoVoronoi.geoVoronoi()(sites);
assert.strictEqual(
Math.max(...u.delaunay.delaunay.triangles),
sites.length - 1
);
});
it("geoVoronoi.hull does not break on difficult polygons", async () => {
for (const t of [
"poly1",
"poly2",
"poly3",
"poly4",
"poly5",
"poly6",
"poly7",
]) {
const { points, hull } = JSON.parse(
await fs.readFile(path.resolve("test/data", `${t}.json`), "utf8")
);
assert.deepStrictEqual(hull, geoVoronoi.geoVoronoi(points).hull());
}
});
<file_sep>/src/voronoi.js
import { geoCentroid, geoDistance } from "d3-geo";
import { geoDelaunay, excess } from "./delaunay.js";
export function geoVoronoi(data) {
const v = function (data) {
v.delaunay = null;
v._data = data;
if (typeof v._data === "object" && v._data.type === "FeatureCollection") {
v._data = v._data.features;
}
if (typeof v._data === "object") {
const temp = v._data
.map((d) => [v._vx(d), v._vy(d), d])
.filter((d) => isFinite(d[0] + d[1]));
v.points = temp.map((d) => [d[0], d[1]]);
v.valid = temp.map((d) => d[2]);
v.delaunay = geoDelaunay(v.points);
}
return v;
};
v._vx = function (d) {
if (typeof d == "object" && "type" in d) {
return geoCentroid(d)[0];
}
if (0 in d) return d[0];
};
v._vy = function (d) {
if (typeof d == "object" && "type" in d) {
return geoCentroid(d)[1];
}
if (1 in d) return d[1];
};
v.x = function (f) {
if (!f) return v._vx;
v._vx = f;
return v;
};
v.y = function (f) {
if (!f) return v._vy;
v._vy = f;
return v;
};
v.polygons = function (data) {
if (data !== undefined) {
v(data);
}
if (!v.delaunay) return false;
const coll = {
type: "FeatureCollection",
features: [],
};
if (v.valid.length === 0) return coll;
v.delaunay.polygons.forEach((poly, i) =>
coll.features.push({
type: "Feature",
geometry: !poly
? null
: {
type: "Polygon",
coordinates: [
[...poly, poly[0]].map((i) => v.delaunay.centers[i]),
],
},
properties: {
site: v.valid[i],
sitecoordinates: v.points[i],
neighbours: v.delaunay.neighbors[i], // not part of the public API
},
})
);
if (v.valid.length === 1)
coll.features.push({
type: "Feature",
geometry: { type: "Sphere" },
properties: {
site: v.valid[0],
sitecoordinates: v.points[0],
neighbours: [],
},
});
return coll;
};
v.triangles = function (data) {
if (data !== undefined) {
v(data);
}
if (!v.delaunay) return false;
return {
type: "FeatureCollection",
features: v.delaunay.triangles
.map((tri, index) => {
tri = tri.map((i) => v.points[i]);
tri.center = v.delaunay.centers[index];
return tri;
})
.filter((tri) => excess(tri) > 0)
.map((tri) => ({
type: "Feature",
properties: {
circumcenter: tri.center,
},
geometry: {
type: "Polygon",
coordinates: [[...tri, tri[0]]],
},
})),
};
};
v.links = function (data) {
if (data !== undefined) {
v(data);
}
if (!v.delaunay) return false;
const _distances = v.delaunay.edges.map((e) =>
geoDistance(v.points[e[0]], v.points[e[1]])
),
_urquart = v.delaunay.urquhart(_distances);
return {
type: "FeatureCollection",
features: v.delaunay.edges.map((e, i) => ({
type: "Feature",
properties: {
source: v.valid[e[0]],
target: v.valid[e[1]],
length: _distances[i],
urquhart: !!_urquart[i],
},
geometry: {
type: "LineString",
coordinates: [v.points[e[0]], v.points[e[1]]],
},
})),
};
};
v.mesh = function (data) {
if (data !== undefined) {
v(data);
}
if (!v.delaunay) return false;
return {
type: "MultiLineString",
coordinates: v.delaunay.edges.map((e) => [
v.points[e[0]],
v.points[e[1]],
]),
};
};
v.cellMesh = function (data) {
if (data !== undefined) {
v(data);
}
if (!v.delaunay) return false;
const { centers, polygons } = v.delaunay;
const coordinates = [];
for (const p of polygons) {
if (!p) continue;
for (
let n = p.length, p0 = p[n - 1], p1 = p[0], i = 0;
i < n;
p0 = p1, p1 = p[++i]
) {
if (p1 > p0) {
coordinates.push([centers[p0], centers[p1]]);
}
}
}
return {
type: "MultiLineString",
coordinates,
};
};
v._found = undefined;
v.find = function (x, y, radius) {
v._found = v.delaunay.find(x, y, v._found);
if (!radius || geoDistance([x, y], v.points[v._found]) < radius)
return v._found;
};
v.hull = function (data) {
if (data !== undefined) {
v(data);
}
const hull = v.delaunay.hull,
points = v.points;
return hull.length === 0
? null
: {
type: "Polygon",
coordinates: [[...hull.map((i) => points[i]), points[hull[0]]]],
};
};
return data ? v(data) : v;
}
<file_sep>/README.md
# d3-geo-voronoi
This module adapts [d3-delaunay](https://github.com/d3/d3-delaunay) for spherical data. Given a set of objects in spherical coordinates, it computes their Delaunay triangulation and its dual, the Voronoi diagram.
In addition, it offers convenience methods to extract the convex hull, the Urquhart graph, the circumcenters of the Delaunay triangles, and to find the cell that contains any given point on the sphere.
The module offers two APIs.
The GeoJSON API is the most convenient for drawing the results on a map. It follows as closely as possible the API of the [d3-voronoi](https://github.com/d3/d3-voronoi/) module. It is available with *d3.geoVoronoi()*.
A lighter API is available with *d3.geoDelaunay()*. It offers the same contents, but with a different presentation, where every vertex, edge, polygon… is referenced by an id rather than by its coordinates. This allows a more compact representation in memory and eases topology computations.
## Installing
If you use npm, `npm install d3-geo-voronoi`. You can also download the [latest release on GitHub](https://github.com/d3/d3-geo-voronoi/releases/latest). For vanilla HTML in modern browsers, import d3-geo-voronoi from Skypack:
```html
<script type="module">
import {geoDelaunay} from "https://cdn.skypack.dev/d3-geo-voronoi@2";
</script>
```
For legacy environments, you can load d3-geo-voronoi’s UMD bundle from an npm-based CDN such as jsDelivr; a `d3` global is exported:
```html
<script src="https://cdn.jsdelivr.net/npm/d3-geo-voronoi@2"></script>
<script>
d3.geoContour();
</script>
```
## API Reference
* [Delaunay](#delaunay)
* [Voronoi](#voronoi)
* [Contours](#contours)
### Delaunay
This API is a similar to [d3-delaunay](https://github.com/d3/d3-delaunay)’s API. It provides information on the Delaunay triangulation (edges, triangles, neighbors, Voronoi cells, etc) as indices in two arrays — the array of points, and the array of circumcenters. It facilitates topological computations. To draw the actual triangles, Voronoi cells etc, the [Voronoi](#Voronoi) API described in the next section will often be easier to use.
<a href="#geo-delaunay" name="geo-delaunay">#</a> d3.<b>geoDelaunay</b>([data])
· [Source](https://github.com/Fil/d3-geo-voronoi/blob/main/src/delaunay.js)
Creates a new *spherical* Delaunay layout. _data_ must be passed as an array of [lon, lat] coordinates.
<a href="#geo_delaunay_find" name="geo_delaunay_find">#</a> <i>delaunay</i>.<b>find</b>(*lon*, *lat*[, *node*])
Returns the closest point to [lon, lat]; optionally starting the search at *node* to boost the performance.
<a href="#geo_delaunay_urquhart" name="geo_delaunay_urquhart">#</a> <i>delaunay</i>.<b>urquhart</b>([*distances*])
Given a vector of distances (in the same order as the <a href="#geo_delaunay_edges">edges</a> list), returns a vector of boolean values: true if the edge belongs to the Urquhart graph, false otherwise.
[<img src="https://raw.githubusercontent.com/Fil/d3-geo-voronoi/main/img/geodelaunay-urquhart.png" alt="urquhart" width="320">](https://observablehq.com/@fil/world-cities-urquhart)
<a href="#geo_delaunay_hull" name="geo_delaunay_hull">#</a> <i>delaunay</i>.<b>hull</b>()
Returns an array of indices of points on the hull. The array is empty if the points cover more than a hemisphere.
<a href="#geo_delaunay_edges" name="geo_delaunay_edges">#</a> <i>delaunay</i>.<b>edges</b>
An array of edges as indices of points [from, to].
[<img src="https://raw.githubusercontent.com/Fil/d3-geo-voronoi/main/img/geodelaunay-edges.png" alt="edges" width="320">](https://observablehq.com/@manzt/world-airports-voronoi-in-vega-lite)
<a href="#geo_delaunay_triangles" name="geo_delaunay_triangles">#</a> <i>delaunay</i>.<b>triangles</b>
An array of the triangles, as indices of points [a, b, c]. The triangles are orientated in a clockwise manner, triangles that span more than the hemisphere are removed.
<a href="#geo_delaunay_centers" name="geo_delaunay_centers">#</a> <i>delaunay</i>.<b>centers</b>
The array of centers in spherical coordinates; the first *t* centers are the *t* triangles’s circumcenters. More centers might be listed in order to build the Voronoi diagram for smaller number of points (n≤3).
<a href="#geo_delaunay_neighbors" name="geo_delaunay_neighbors">#</a> <i>delaunay</i>.<b>neighbors</b>
The array of neighbors indices for each vertex.
[<img src="https://raw.githubusercontent.com/Fil/d3-geo-voronoi/main/img/geodelaunay-neighbors.jpg" alt="edges" width="320">](https://observablehq.com/@mbostock/spherical-voronoi-coloring)
<a href="#geo_delaunay_polygons" name="geo_delaunay_polygons">#</a> <i>delaunay</i>.<b>polygons</b>
Array of Voronoi cells for each vertex. Each cell is an array of centers ordered in a clockwise manner.
<a href="#geo_delaunay_mesh" name="geo_delaunay_mesh">#</a> <i>delaunay</i>.<b>mesh</b>
An array containing all the edges of the Voronoi polygons.
### Voronoi
This API is a wrapper around the <a href="#Delaunay">Delaunay</a> API, with inputs and outputs in GeoJSON, ready to draw on a map.
<a href="#geo-voronoi" name="geo-voronoi">#</a> d3.<b>geoVoronoi</b>([data])
· [Source](https://github.com/Fil/d3-geo-voronoi/blob/main/src/voronoi.js), [Examples](https://bl.ocks.org/Fil/74295d9ffe097ae4e3c93d7d00377d45)
Creates a new *spherical* Voronoi layout. _data_ can be passed as an array of [lon, lat] coordinates, an array of GeoJSON features, or a GeoJSON FeatureCollection.
The following methods are similar to [d3-voronoi](https://github.com/d3/d3-voronoi/)'s methods:
<a href="#geo_voronoi_delaunay" name="geo_voronoi_delaunay">#</a> <i>voronoi</i>.<b>delaunay</b>
The geoDelaunay object used to compute this diagram.
<a href="#geo_voronoi_x" name="geo_voronoi_x">#</a> <i>voronoi</i>.<b>x</b>([<i>x</i>])
Sets or returns the _x_ accessor. The default _x_ and _y_ accessors are smart enough to recognize GeoJSON objects and return the geoCentroid of each feature.
<a href="#geo_voronoi_y" name="geo_voronoi_y">#</a> <i>voronoi</i>.<b>y</b>([<i>y</i>])
Sets or returns the _y_ accessor.
[](https://bl.ocks.org/Fil/74295d9ffe097ae4e3c93d7d00377d45)
<a href="#geo_voronoi_polygons" name="geo_voronoi_polygons">#</a> <i>voronoi</i>.<b>polygons</b>(<i>[data]</i>) · [Source](https://github.com/Fil/d3-geo-voronoi/blob/main/src/voronoi.js), [Examples](https://bl.ocks.org/Fil/a9ba8d0d023752aa580bd95480b7de60)
Returns the Voronoi tessellation of the data as a GeoJSON collection of polygons. (If there is only one data point, returns the Sphere). Each polygon exposes its datum in its properties.
[](https://bl.ocks.org/Fil/a9ba8d0d023752aa580bd95480b7de60)
<a href="#geo_voronoi_cellMesh" name="geo_voronoi_cellMesh">#</a> <i>voronoi</i>.<b>cellMesh</b>(<i>[data]</i>) · [Source](https://github.com/Fil/d3-geo-voronoi/blob/main/src/voronoi.js)
Returns the Voronoi tessellation as a GeoJSON mesh (MultiLineString).
<a href="#geo_voronoi_triangles" name="geo_voronoi_triangles">#</a> <i>voronoi</i>.<b>triangles</b>(<i>[data]</i>) · [Source](https://github.com/Fil/d3-geo-voronoi/blob/main/src/voronoi.js), [Examples](https://bl.ocks.org/Fil/b1ef96e4bc991eb274f8d3a0a08932f9)
Returns the Voronoi tessellation of the data as a GeoJSON collection of polygons. Each triangle exposes in its properties the three sites, its spherical area (in steradians), and its circumcenter.
[](https://bl.ocks.org/Fil/b1ef96e4bc991eb274f8d3a0a08932f9)
[](https://bl.ocks.org/Fil/955da86d6a935b26d3599ca5e344fb38)
<a href="#geo_voronoi_mesh" name="geo_voronoi_mesh">#</a> <i>voronoi</i>.<b>mesh</b>(<i>[data]</i>) · [Source](https://github.com/Fil/d3-geo-voronoi/blob/main/src/voronoi.js), [Examples](https://bl.ocks.org/Fil/fbaf391e1ae252461741ccf401af5a10)
Returns the Delaunay edges [as a GeoJSON mesh](https://bl.ocks.org/Fil/fbaf391e1ae252461741ccf401af5a10) (MultiLineString).
<a href="#geo_voronoi_links" name="geo_voronoi_links">#</a> <i>voronoi</i>.<b>links</b>(<i>[data]</i>) · [Source](https://github.com/Fil/d3-geo-voronoi/blob/main/src/voronoi.js), [Examples](https://bl.ocks.org/Fil/1a78acf8b9b40fe8ecbae7b5035acf2b)
Returns the Delaunay links of the data as a GeoJSON collection of lines. Each line exposes its source and target in its properties, but also its length (in radians), and a boolean flag for links that belong to the [Urquhart graph](https://en.wikipedia.org/wiki/Urquhart_graph).
[](https://bl.ocks.org/Fil/1a78acf8b9b40fe8ecbae7b5035acf2b)
[](https://bl.ocks.org/Fil/79b9f17979c4070dee3cbba1c5283502)
[](https://bl.ocks.org/Fil/1c2f954201523af16280db018ddd90cc)
<i>voronoi</i>.<b>extent</b>(<i>[extent]</i>) and <i>voronoi</i>.<b>size</b>(<i>[size]</i>) are not implemented.
Indeed, defining the “paper extent” of the geoVoronoi polygons can be quite tricky, [as this block demonstrates](https://bl.ocks.org/Fil/6128aae082c04eef06422f953d0f593f).
<a name="geo_voronoi_find" href="#geo_voronoi_find">#</a> <i>voronoi</i>.<b>find</b>(<i>x,y,[angle]</i>) · [Source](https://github.com/Fil/d3-geo-voronoi/blob/main/src/voronoi.js), [Examples](https://bl.ocks.org/Fil/e94fc45f5ed4dbcc989be1e52b797fdd)
Finds the closest site to point *x,y*, i.e. the Voronoi polygon that contains it. Optionally, return null if the distance between the point and the site is larger than *angle* degrees.
[](https://bl.ocks.org/Fil/e94fc45f5ed4dbcc989be1e52b797fdd)
<a name="geo_voronoi_hull" href="#geo_voronoi_hull">#</a> <i>voronoi</i>.<b>hull</b>(<i>data</i>) · [Source](https://github.com/Fil/d3-geo-voronoi/blob/main/src/voronoi.js), [Examples](https://bl.ocks.org/Fil/6a1ed09f6e5648a5451cb130f2b13d20)
Returns the spherical convex hull of the *data* array, as a GeoJSON polygon. Returns null if the dataset spans more than a hemisphere. Equivalent to:
```js
voronoi(data).hull();
```
[](https://bl.ocks.org/Fil/6a1ed09f6e5648a5451cb130f2b13d20)
### Contours
Create *spherical* contours for non-gridded data.
The API of geoContour is similar to that of [d3-contour](https://github.com/d3/d3-contour) and [d3-tricontour](https://github.com/Fil/d3-tricontour):
<a href="#geocontour" name="geocontour">#</a> d3.<b>geoContour</b>()
· [Source](https://github.com/Fil/d3-geo-voronoi/blob/main/src/contour.js), [Examples](https://observablehq.com/collection/@fil/tricontours)
Constructs a new geocontour generator with the default settings.
[<img src="https://raw.githubusercontent.com/Fil/d3-geo-voronoi/main/img/geocontour.jpg" alt="geoContour" width="320">](https://observablehq.com/@fil/spherical-contours)
<a href="#_geocontour" name="_geocontour">#</a> _geocontour_(_data_) · [Examples](https://observablehq.com/@fil/tricontours)
Returns an array of contours, one for each threshold. The contours are MultiPolygons in GeoJSON format, that contain all the points with a value larger than the threshold. The value is indicated as _geometry_.value.
The _data_ is passed as an array of points, by default with the format [lon, lat, value].
<a href="#contour" name="contour">#</a> _geocontour_.<b>contour</b>(_data_[, _threshold_])
Returns a contour, as a MultiPolygon in GeoJSON format, containing all points with a value larger or equal to _threshold_. The threshold is indicated as _geometry_.value
<a href="#contours" name="contours">#</a> _geocontour_.<b>contours</b>(_data_)
Returns an iterable over the contours.
[<img src="https://raw.githubusercontent.com/Fil/d3-geo-voronoi/main/img/geocontour-iterator.jpg" alt="geoContour iterator" width="320">](https://observablehq.com/@fil/spherical-contours-iterator)
<a href="#isobands" name="isobands">#</a> _geocontour_.<b>isobands</b>(_data_)
Returns an iterable over the isobands: contours between pairs of consecutive threshold values _v0_ (inclusive) and _v1_ (exclusive). _geometry_.value is equal to _v0_, _geometry_.valueMax to _v1_.
[<img src="https://raw.githubusercontent.com/Fil/d3-geo-voronoi/main/img/geocontour-isobands.jpg" alt="geoContour isobands" width="320">](https://observablehq.com/@fil/spherical-isobands)
<a href="#x" name="x">#</a> _geocontour_.<b>x</b>([_x_])
Sets the *x* (longitude) accessor. Defaults to \`d => d[0]\`. If _x_ is not given, returns the current x accessor.
<a href="#y" name="y">#</a> _geocontour_.<b>y</b>([_y_])
Sets the *y* (latitude) accessor. Defaults to \`d => d[1]\`. If _y_ is not given, returns the current y accessor.
<a href="#value" name="value">#</a> _geocontour_.<b>value</b>([_value_])
Sets the *value* accessor. Defaults to \`d => d[2]\`. Values must be defined and finite. If _value_ is not given, returns the current value accessor.
[<img src="https://raw.githubusercontent.com/Fil/d3-geo-voronoi/main/img/geocontour-blurry.jpg" alt="Blurry geoContours" width="320">](https://observablehq.com/@fil/blurry-contours)
[<img src="https://raw.githubusercontent.com/Fil/d3-geo-voronoi/main/img/geocontour-h3.jpg" alt="geoContour and H3" width="320">](https://observablehq.com/@fil/h3-hexagons-geocontours)
<a href="#thresholds" name="thresholds">#</a> _geocontour_.<b>thresholds</b>([_thresholds_])
Sets the thresholds, either explicitly as an array of values, or as a count that will be passed to d3.ticks. If empty, returns the current thresholds.
_Note:_ d3.geoContour uses the experimental API of d3-tricontour: [triangulate](https://github.com/Fil/d3-tricontour/blob/main/README.md#triangulate), [pointInterpolate](https://github.com/Fil/d3-tricontour/blob/main/README.md#pointInterpolate) and [ringsort](https://github.com/Fil/d3-tricontour/blob/main/README.md#ringsort).
### Other tools & projections
There is no reason to limit the display of Voronoi cells to the orthographic projection. The example below displays the Urquhart graph of top container ports on a Winkel tripel map.
[](https://bl.ocks.org/Fil/24d5ee71f09ba72893323d803242c38a)
[Geo_triangulate](https://jessihamel.github.io/geo_triangulate/) converts GeoJSON to triangles for 3d rendering.
### Comparison with planar Voronoi Diagrams
- the Delaunay/Voronoi topology is quite different on the sphere and on the plane. This module deals with these differences by first projecting the points with a stereographic projection, then stitching the geometries that are near the singularity of the projection (the “infinite horizon” on the plane is one point on the sphere).
- geoVoronoi returns GeoJSON objects, which are often `FeatureCollections`. By consequence, you will have to change `.data(voronoi.polygons())` to `.data(geovoronoi.polygons().features)`, and so on.
- geoVoronoi is built on [d3-delaunay](https://github.com/d3/d3-delaunay), which is also exposed as d3.geoDelaunay in this library. If you want to have the fastest results, you should try to use d3.geoDelaunay directly (see the examples).
- geoVoronoi and geoDelaunay offer methods to compute the spherical [convex hull](#geo_voronoi_hull) and the [Urquhart graph](#geo_voronoi_links) of the data set. These can be achieved with the planar Voronoi ([hull](https://bl.ocks.org/mbostock/6f14f7b7f267a85f7cdc), [Urquhart](https://bl.ocks.org/Fil/df20827f817abd161c768fa18dcafcf5)), but are not part of d3-voronoi or d3-delaunay.
|
ffc1f0fa78afe4e6e6cf0f90e90b271169c6501c
|
[
"JavaScript",
"Markdown"
] | 7
|
JavaScript
|
Fil/d3-geo-voronoi
|
ab135d798ebd1aff693d4790839e9482aec9d2d7
|
599b03dcb282f72143b740df74cfda5d62e73aca
|
refs/heads/master
|
<repo_name>MichaelPanW/Dcard_php_reptile<file_sep>/Dcard/Trade/Controller/IndexController.class.php
<?php
namespace Trade\Controller;
use Think\Controller;
class IndexController extends GlobalController {
function _initialize()
{
parent::_initialize();
}
public function index()
{
if($_GET['title']!=""){
$where.="title like '%".utf8_encode($_GET['title'])."%' and ";
}
if($_GET['class']!=""){
$where.="classif='".$_GET['class']."' and ";
}
if($_GET['hidd']!=""){
$where.="hidd='".$_GET['hidd']."' and ";
}
//dump($where);
$count = D("article")->where($where."status=1")->count();
$pagwAllA = new \Think\Page($count, 30);
$pagwAllA->setConfig('prev',"上頁");
$pagwAllA->setConfig('next',"下頁");
$pagwAllA->setConfig('theme',"%UP_PAGE% %LINK_PAGE% %DOWN_PAGE%");
$pageShowA = $pagwAllA->show();
$article=D("article")->where($where."status=1")->limit($pagwAllA->firstRow,$pagwAllA->listRows)->order("alike DESC")->select();
foreach ($article as $key => $value) {
$article[$key]['url']=utf8_decode($value['url']);
$article[$key]['title']=utf8_decode($value['title']);
$article[$key]['title']=strip_tags($article[$key]['title']);
$article[$key]['content']=utf8_decode($value['content']);
$article[$key]['content']=strip_tags($article[$key]['content']);
# code...
}
//dump($article);
$this->assign('article',$article);
$this->assign('pageShowA',$pageShowA);
$this->display();
}
public function show(){
$article=D("article")->where("id='".$_GET['id']."'")->find();
if(!$article){
$this->redirect("Index/index");
}
$article['title']=utf8_decode($article['title']);
$article['url']=utf8_decode($article['url']);
$article['content']=utf8_decode($article['content']);
$article['content']=str_replace('href="/', 'href="https://www.dcard.tw/', $article['content']);
$this->assign('article',$article);
$this->assign('title',"Ccard - ".$article['title']);
$this->display();
}
public function amp(){
$article=D("article")->where("id='".$_GET['id']."'")->find();
if(!$article){
$this->redirect("Index/index");
}
$article['title']=utf8_decode($article['title']);
$article['url']=utf8_decode($article['url']);
$article['content']=utf8_decode($article['content']);
$article['content']=str_replace("img", "amp-img", $article['content']);
$article['content']=str_replace("style=", "class=", $article['content']);
$amp='
<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>';
$this->assign('amp',$amp);
$this->assign('article',$article);
$this->assign('title',"Ccard - ".$article['title']);
$this->display();
}
} <file_sep>/Dcard/Trade/Controller/GlobalController.class.php
<?php
namespace Trade\Controller;
use Think\Controller;
class GlobalController extends Controller
{
function _initialize()
{
$classif=D("classif")->where("status=1")->select();
$title="Ccard - 找回已消失的文章";
$this->assign('classif',$classif);
$this->assign('title',$title);
}
}
?>
|
240946bcd9b75e74391b647b20a596447ed03740
|
[
"PHP"
] | 2
|
PHP
|
MichaelPanW/Dcard_php_reptile
|
adc18ea90fa5ea0301ec1bafb1684693323a6990
|
d2d988c9eb540dad184a5fd005927a3769864498
|
refs/heads/master
|
<file_sep>const express = require("express");
var app = express();
app.get("/", (req, res) => {
res.send("Welcome to Djay Node Server");
});
app.get("/hc", (req, res) => {
res.send("Health");
});
module.exports = app;
<file_sep>const request = require("supertest");
describe("Sample Test", () => {
it("should test that true === true", () => {
expect(true).toBe(true);
});
const app = require("../app");
it("should send health back", (done) => {
request(app)
.get("/hc")
.expect(200, (err, res) => {
if (err) {
done();
}
expect(res.text.includes("Health")).toBe(true);
done();
});
});
it("should get main message", (done) => {
request(app)
.get("/")
.expect(200, (err, res) => {
expect(res.text.includes("Djay Node Server")).toBe(true);
done();
});
});
});
|
8ce95ef0ffc984bffc6944f0b76bd6ab0a70ce9a
|
[
"JavaScript"
] | 2
|
JavaScript
|
digvijaypanwar/node-web-server
|
2cc5d3f7fd1e19dcf943c9651e62ca180696f0b8
|
3ac90d92894e7311ec0f4649095a21ddf89da2a3
|
refs/heads/master
|
<repo_name>anhuiwj/ChineseChess<file_sep>/src/com/wyf/cgq/ServerAgentThread.java
package com.wyf.cgq;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Vector;
import com.dao.QzDao;
public class ServerAgentThread extends Thread {
Server father;// 声明Server的引用
Socket sc;// 声明Socket的引用
DataInputStream din;// 声明数据输入流与输出流的引用
DataOutputStream dout;
boolean flag = true;// 控制线程的标志位
public ServerAgentThread(Server father, Socket sc) {
this.father = father;
this.sc = sc;
try {
din = new DataInputStream(sc.getInputStream());// 创建数据输入流
dout = new DataOutputStream(sc.getOutputStream());// 创建数据输出流
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
while (flag) {
try {
String msg = din.readUTF().trim();// 接收客户端传来的信息
if (msg.startsWith("<#NICK_NAME#>"))// 收到新用户的信息
{
this.nick_name(msg);
} else if (msg.startsWith("<#CLIENT_LEAVE#>")) {// 收到用户离开的信息
this.client_leave(msg);
} else if (msg.startsWith("<#TIAO_ZHAN#>")) {// 收到用户发出的挑战信息
this.tiao_zhan(msg);
} else if (msg.startsWith("<#TONG_YI#>")) {// 受到接受挑战的信息
this.tong_yi(msg);
} else if (msg.startsWith("<#BUTONG_YI#>")) {// 受到拒绝挑战的信息
this.butong_yi(msg);
} else if (msg.startsWith("<#BUSY#>")) {// 收到被挑战者忙的信息
this.busy(msg);
} else if (msg.startsWith("<#MOVE#>")) {// 收到走棋的信息
this.move(msg);
} else if (msg.startsWith("<#RENSHU#>")) {// 收到某用户认输的信息
this.renshu(msg);
} else if (msg.startsWith("<#SEND_MSG#>")) {// 收到用户发送的信息
this.sendMsg(msg);
} else if (msg.startsWith("<#MOVE_QIZI#>")) {// 收到用户发生移到位置
this.MOVE_QIZI(msg);
} else if (msg.startsWith("<#RETURN_MOVE#>")) {// 悔棋
this.returnMove(msg);
} else if (msg.startsWith("<#IS_ALLOW_RETURN#>")) {// 是否同意悔棋
this.isAllowReturn(msg);
} else if (msg.startsWith("<#IS_ALLOW#>")) {// 同意悔棋
this.isAllow(msg);
} else if (msg.startsWith("<#DIAO_XIAN#>")) {
this.diaoxian(msg);// 掉线
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void nick_name(String msg) {
try {
String name = msg.substring(13);// 获得用户的昵称
this.setName(name);// 用该昵称给该线程取名
Vector v = father.onlineList;// 获得在线用户列表
boolean isChongMing = false;
int size = v.size();// 获得用户列表的大小
for (int i = 0; i < size; i++) {// 遍历列表,查看是否已经有该用户名
ServerAgentThread tempSat = (ServerAgentThread) v.get(i);
if (tempSat.getName().equals(name)) {
isChongMing = true;// 有重名,将标志位设为true
break;
}
}
if (isChongMing == true)// 如果重名
{
dout.writeUTF("<#NAME_CHONGMING#>");// 将重名信息发送给客户端
din.close();// 关闭数据输入流
dout.close();// 关闭数据输出流
sc.close();// 关闭Socket
flag = false;// 终止该服务器代理线程
} else// 如果不重名
{
v.add(this);// 将该线程添加到在线列表
father.refreshList();// 刷新服务器在线信息列表
String nickListMsg = "";
size = v.size();// 获得在线列表大小
for (int i = 0; i < size; i++) {
ServerAgentThread tempSat = (ServerAgentThread) v.get(i);
nickListMsg = nickListMsg + "|" + tempSat.getName();
} // 将在线列表内容住组织成字符串
nickListMsg = "<#NICK_LIST#>" + nickListMsg;
Vector tempv = father.onlineList;
size = tempv.size();
for (int i = 0; i < size; i++) {// 遍历在线列表
ServerAgentThread satTemp = (ServerAgentThread) tempv.get(i);
satTemp.dout.writeUTF(nickListMsg);// 将最新的列表信息发送到各个客户端
if (satTemp != this) {// 给其他客户端发送新用户上线的信息
satTemp.dout.writeUTF("<#MSG#>" + this.getName() + "上线了...");
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void client_leave(String msg) {
try {
Vector tempv = father.onlineList;// 获得在线列表
tempv.remove(this);// 移除该用户
int size = tempv.size();
String nl = "<#NICK_LIST#>";
for (int i = 0; i < size; i++) {// 遍历在线列表
ServerAgentThread satTemp = (ServerAgentThread) tempv.get(i);
// 向各个客户端发送用户离线信息
satTemp.dout.writeUTF("<#MSG#>" + this.getName() + "离线了...");
// 组织信息的在线用户列表
nl = nl + "|" + satTemp.getName();
}
for (int i = 0; i < size; i++) {// 将最新的列表信息发送到各个客户端
ServerAgentThread satTemp = (ServerAgentThread) tempv.get(i);
satTemp.dout.writeUTF(nl);
}
this.flag = false;// 终止该服务器代理线程
father.refreshList();// 更新服务器在线用户列表
} catch (IOException e) {
e.printStackTrace();
}
}
public void tiao_zhan(String msg) {
try {
String name1 = this.getName();// 获得发出挑战信息用户的名字
String name2 = msg.substring(13);// 获得被挑战的用户名字
Vector v = father.onlineList;// 获得在线用户列表
int size = v.size();// 获得在线用户列表的大小
for (int i = 0; i < size; i++) {// 遍历列表,搜索被挑战的用户
ServerAgentThread satTemp = (ServerAgentThread) v.get(i);
if (satTemp.getName().equals(name2)) {// 向该用户发送挑战信息,附带提出挑战用户的名字
satTemp.dout.writeUTF("<#TIAO_ZHAN#>" + name1);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void tong_yi(String msg) {
try {
String name = msg.substring(11);// 获得提出挑战的用户的名字
Vector v = father.onlineList;// 获得在线用户列表
int size = v.size();// 获得在线用户列表的大小
for (int i = 0; i < size; i++) {// 遍历列表,搜索提出挑战的用户
ServerAgentThread satTemp = (ServerAgentThread) v.get(i);
if (satTemp.getName().equals(name)) {// 向该用户发送对方接受挑战的信息
satTemp.dout.writeUTF("<#TONG_YI#>");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void butong_yi(String msg) {
try {
String name = msg.substring(13);// 获得提出挑战的用户的名字
Vector v = father.onlineList;// 获得在线用户列表
int size = v.size();// 获得在线用户列表的大小
for (int i = 0; i < size; i++) {// 遍历列表,搜索提出挑战的用户
ServerAgentThread satTemp = (ServerAgentThread) v.get(i);
if (satTemp.getName().equals(name)) {// 向该用户发送对方拒绝挑战的信息
satTemp.dout.writeUTF("<#BUTONG_YI#>");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void busy(String msg) {
try {
String name = msg.substring(8);// 获得提出挑战的用户的名字
Vector v = father.onlineList;// 获得在线用户列表
int size = v.size();// 获得在线用户列表的大小
for (int i = 0; i < size; i++) {// 遍历列表,搜索提出挑战的用户
ServerAgentThread satTemp = (ServerAgentThread) v.get(i);
if (satTemp.getName().equals(name)) {// 向该用户发送对方正在忙的信息
satTemp.dout.writeUTF("<#BUSY#>");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* <#MOVE#>,tiaoZhanZhe,startI,startJ,endI,endJ,tagetName,tagetI,tagetJ,createBy
* <#MOVE#>admin1234
*
* @param msg
*/
public void move(String msg) {
try {
String name = msg.substring(8, msg.length() - 4);// 获得接收方的名字
Vector v = father.onlineList;// 获得在线用户列表
int size = v.size();// 获得在线用户列表的大小
for (int i = 0; i < size; i++) {// 遍历列表,搜索接收方
ServerAgentThread satTemp = (ServerAgentThread) v.get(i);
if (satTemp.getName().equals(name)) {// 将该信息转发给接收方
satTemp.dout.writeUTF(msg);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void renshu(String msg) {
try {
String name = msg.substring(10);// 获得接收方的名字
Vector v = father.onlineList;// 获得在线用户列表
int size = v.size();// 获得在线用户列表的大小
for (int i = 0; i < size; i++) {// 遍历列表,搜索接收方
ServerAgentThread satTemp = (ServerAgentThread) v.get(i);
if (satTemp.getName().equals(name)) {// 将该信息转发给接收方
satTemp.dout.writeUTF(msg);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMsg(String msg) {
try {
String name = msg.substring(12);// 获得接收方的名字
Vector v = father.onlineList;// 获得在线用户列表
String[] msgs = msg.split("&&");
StringBuffer newmsg = new StringBuffer();
int size = v.size();// 获得在线用户列表的大小
for (int i = 0; i < size; i++) {// 遍历列表,搜索接收方
ServerAgentThread satTemp = (ServerAgentThread) v.get(i);
if (msgs.length > 1 && satTemp.getName().equals(msgs[1])) {// 将该信息转发给接收方
if (msgs.length > 1) {
msgs[1] = msgs[msgs.length - 1];
newmsg.append("<#SEND_MSG#>");
for (int k = 1; k < msgs.length - 1; k++) {
newmsg.append(msgs[k]);
newmsg.append("&&");
}
}
satTemp.dout.writeUTF(newmsg.toString());
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void returnMove(String msg) {
}
/**
* <#IS_ALLOW_RETURN#>target
*
* @param msg
*/
public void isAllowReturn(String msg) {
try {
String name = msg.substring(19, msg.length());// 获得接收方的名字
Vector v = father.onlineList;// 获得在线用户列表
int size = v.size();// 获得在线用户列表的大小
for (int i = 0; i < size; i++) {// 遍历列表,搜索接收方
ServerAgentThread satTemp = (ServerAgentThread) v.get(i);
if (satTemp.getName().equals(name)) {// 将该信息转发给接收方
satTemp.dout.writeUTF(msg);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* <#IS_ALLOW#>admin0
*
* @param msg
*/
public void isAllow(String msg) {
// 选中“是”返回0,选中“否”返回1。
try {
String name = msg.substring(12, msg.length() - 1);// 获得接收方的名字
Vector v = father.onlineList;// 获得在线用户列表
int size = v.size();// 获得在线用户列表的大小
for (int i = 0; i < size; i++) {// 遍历列表,搜索接收方
ServerAgentThread satTemp = (ServerAgentThread) v.get(i);
if (satTemp.getName().equals(name)) {// 将该信息转发给接收方
satTemp.dout.writeUTF(msg);
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 保存移到位置
* <#MOVE#>,tiaoZhanZhe,startI,startJ,endI,endJ,tagetName,tagetColor,tagetI,tagetJ,createBy
* <#MOVE_QIZI#>,admin,4,2,4,6,卒,,4,6,jie
*
* @param msg
*/
public void MOVE_QIZI(String msg) {
String[] res = msg.split(",");
QzDao qzdao = new QzDao();
qzdao.insert(res[1] + res[10], "", res[2] + "," + res[3] + "," + res[4] + "," + res[5], res[6],
res[8] + "," + res[9], res[7], res[10]);
}
/**
* 调线
*/
public void diaoxian(String msg) {
}
}<file_sep>/db/chinesechess.sql
/*
Navicat MySQL Data Transfer
Source Server : mjs
Source Server Version : 50624
Source Host : localhost:3306
Source Database : chinesechess
Target Server Type : MYSQL
Target Server Version : 50624
File Encoding : 65001
Date: 2017-03-29 10:05:38
*/
CREATE DATABASE IF NOT EXISTS chinesechess default charset utf8 COLLATE utf8_general_ci;
use chinesechess;
-- ----------------------------
-- Table structure for `chess`
-- ----------------------------
DROP TABLE IF EXISTS `chess`;
CREATE TABLE `chess` (
`id` varchar(32) NOT NULL COMMENT '当前旗子',
`dqqzi` varchar(32) NOT NULL,
`dqlocation` varchar(32) NOT NULL COMMENT '当前棋子',
`targetName` varchar(32) DEFAULT NULL COMMENT '目标旗子',
`targeColor` varchar(32) DEFAULT NULL,
`targetLocation` varchar(32) DEFAULT NULL COMMENT '目标坐标',
`createDate` datetime NOT NULL,
`createBy` varchar(32) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of chess
-- ----------------------------
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` varchar(32) NOT NULL,
`user_name` varchar(32) NOT NULL,
`password` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'admin', '123');
INSERT INTO `user` VALUES ('1490348750673', 'jiejie', '123');
|
2d12e37b1bc6cf884b123bea9a0c51eabc3dfc43
|
[
"Java",
"SQL"
] | 2
|
Java
|
anhuiwj/ChineseChess
|
376d2e5cfad88c73845de52e7e09a4b345e9d7ff
|
3b057ee46c287adb3638cd6740c34807a811dda8
|
refs/heads/master
|
<file_sep>package com.example.krzysiekbielicki.mylapplication.kuba.recyclerview;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.krzysiekbielicki.mylapplication.R;
import java.util.ArrayList;
import java.util.Arrays;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class ExampleAdapter extends BaseRecyclerViewAdapter<String, ExampleAdapter.ViewHolder> {
private final LayoutInflater layoutInflater;
private RecyclerViewClickListener<ViewHolder> listener;
private int layoutResourceId;
public ExampleAdapter(Context context, String[] dataset, boolean useCardLayout) {
super(new ArrayList<String>(Arrays.asList(dataset)));
layoutInflater = LayoutInflater.from(context);
layoutResourceId = useCardLayout ? R.layout.card_collection_item : R.layout.collection_item;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int position) {
View view = layoutInflater.inflate(layoutResourceId, parent, false);
view.setClipToOutline(true);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
viewHolder.image.setImageResource(R.drawable.ic_launcher);
viewHolder.text.setText(getItem(position));
}
public void setListener(RecyclerViewClickListener<ViewHolder> listener) {
this.listener = listener;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
@InjectView(R.id.image)
public ImageView image;
@InjectView(R.id.text)
public TextView text;
public ViewHolder(View view) {
super(view);
view.setOnClickListener(this);
ButterKnife.inject(this, view);
}
@Override
public void onClick(View view) {
listener.onItemClick(getPosition(), this, getItemId());
}
}
}
<file_sep>package com.example.krzysiekbielicki.mylapplication;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class WishlistFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
@InjectView(R.id.recyclerView)
RecyclerView recyclerView;
public static WishlistFragment newInstance(int sectionNumber) {
WishlistFragment fragment = new WishlistFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public WishlistFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_collection, container, false);
ButterKnife.inject(this, rootView);
LinearLayoutManager layoutManager = new LinearLayoutManager(container.getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
return rootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView.setHasFixedSize(true);
recyclerView.setLongClickable(true);
recyclerView.setAdapter(new BricksAdapter(getActivity()));
}
}
<file_sep>package com.example.krzysiekbielicki.mylapplication.kuba.transitions;
import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.transition.Explode;
import android.util.Pair;
import android.view.View;
import com.example.krzysiekbielicki.mylapplication.R;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
public class TransitionsSmallGalleryActivity extends Activity {
@InjectView(R.id.imageSmall1)
View smallImage1;
@InjectView(R.id.imageSmall2)
View smallImage2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setEnterTransition(new Explode());
getWindow().setAllowExitTransitionOverlap(true);
setContentView(R.layout.activity_transitions_a);
ButterKnife.inject(this);
}
@OnClick(R.id.bigGallery)
void onBigGalleryButtonClick() {
startActivity(new Intent(this, TransitionsBigGalleryActivity.class));
}
@OnClick(R.id.imagesPanel)
void onImagesPanelClicked() {
Intent intent = new Intent(this, TransitionsBigGalleryActivity.class);
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(this,
Pair.create(smallImage1, smallImage1.getViewName()), Pair.create(smallImage2, smallImage2.getViewName()));
// or: options = ActivityOptions.makeSceneTransitionAnimation(this, smallImage1, smallImage1.getViewName());
startActivity(intent, options.toBundle());
}
}
<file_sep>package com.example.krzysiekbielicki.mylapplication;
import android.app.ActivityOptions;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class BricksFragment extends Fragment implements BricksAdapter.RecyclerViewClickListener {
private static final String ARG_SECTION_NUMBER = "section_number";
@InjectView(R.id.recyclerView)
RecyclerView recyclerView;
public static BricksFragment newInstance(int sectionNumber) {
BricksFragment fragment = new BricksFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public BricksFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_collection, container, false);
ButterKnife.inject(this, rootView);
LinearLayoutManager layoutManager = new LinearLayoutManager(container.getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
return rootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView.setHasFixedSize(true);
recyclerView.setLongClickable(true);
BricksAdapter adapter = new BricksAdapter(getActivity());
adapter.setListener(this);
recyclerView.setAdapter(adapter);
}
@Override
public void onItemClick(int position, BricksAdapter.ItemViewHolder viewHolder, long itemId) {
Intent intent = new Intent(getActivity(), DetailsActivity.class);
viewHolder.image.setViewName("image");
ActivityOptions options = ActivityOptions
.makeSceneTransitionAnimation(getActivity(), viewHolder.image, "image");
startActivity(intent, options.toBundle());
}
}
<file_sep>package me.tatarka.recyclerviewtest.itemanimator;
import android.support.v7.widget.RecyclerView;
/**
* Created by evan on 6/28/14.
*/
abstract class PendingAnimator {
RecyclerView.ViewHolder viewHolder;
public PendingAnimator(RecyclerView.ViewHolder viewHolder) {
this.viewHolder = viewHolder;
}
abstract void animate(BaseItemAnimator.OnAnimatorEnd callback);
abstract void cancel();
public static abstract class Add extends PendingAnimator {
public Add(RecyclerView.ViewHolder viewHolder) {
super(viewHolder);
}
}
public static abstract class Remove extends PendingAnimator {
public Remove(RecyclerView.ViewHolder viewHolder) {
super(viewHolder);
}
}
public static abstract class Move extends PendingAnimator {
public Move(RecyclerView.ViewHolder viewHolder) {
super(viewHolder);
}
}
}
|
ebc568a46d4b5cda2d8851f07f7e3155e825f963
|
[
"Java"
] | 5
|
Java
|
krzysiekbielicki/MaterialDesign-demo
|
062a09af79a15a89337a20dfc52c1fdececf9198
|
b70f31d7a538a9c242c626b552787fa4833eb926
|
refs/heads/master
|
<file_sep># Array-dan-Sting
Array dan String C++
<file_sep>#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char input[100], kopi[100], kopi2[100];
int kounter; int vokal=0; int konsonan=0;int besar=0;int kecil=0;int gang=0, offset, gantine;
cout<<"Input User = ";
cin.getline(input, 100);
kopi==strcpy(kopi, input);
cout<<"Original = "<<input<<endl;
cout<<"Reserved = "<<strrev(kopi)<<endl;
kopi==strcpy(kopi, input);
cout<<endl;
cout<<"Uppercase = "<<strupr(kopi)<<endl;
cout<<"Lowercase = "<<strlwr(kopi)<<endl;
for(kounter=0; kounter<strlen(input); kounter++){
if(input[kounter]>='A' && input[kounter]<='Z'){
besar++;
}
else if(input[kounter]==' '){
gang=0;
}
else{
kecil++;
}
}
cout<<endl;
cout<<"Ucase total = "<<besar<<endl;
cout<<"Lcase total = "<<kecil<<endl;
kopi==strcpy(kopi, input);
kopi2==strcpy(kopi2, input);
for(kounter=0; kounter<strlen(input); kounter++){
if(input[kounter]=='a' || input[kounter]=='i' || input[kounter]=='u' ||
input[kounter]=='e' || input[kounter]=='o' || input[kounter]=='A' ||
input[kounter]=='I' || input[kounter]=='U' || input[kounter]=='E' || input[kounter]=='O'){
vokal++;
kopi[kounter]=' ';//Menghilang Huruf Vokal;
}
else if(input[kounter]==' '){
gang++;
}
else{
konsonan++;
kopi2[kounter]=' ';//Menghilangkan Huruf Bukan Vokal
}
}
cout<<endl;
cout<<"Vocals = "<<vokal<<endl;
cout<<"!Vocals = "<<konsonan<<endl;
cout<<"Spaces = "<<gang<<endl;
cout<<endl;
cout<<"Hide Vocals = "<<kopi<<endl;
cout<<"Hide !Vocals = "<<kopi2<<endl<<endl;
cout<<"Input Offset = ";
cin>>offset;
kopi==strcpy(kopi, input);
for(kounter=0; kounter<strlen(input); kounter++){
if(kopi[kounter]==' '){
kopi[kounter]=' ';
}
else{
gantine=int(kopi[kounter])+offset;//Merubah ke kode ASCII
kopi[kounter]=char (gantine);//Merubah ASCII ke Karakter
}
}
cout<<"Offset Text = "<<kopi;
cout<<endl;
}
|
e084849b901c4c4baad76b29ac61f891b5c16b0d
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
ok-google/Array-dan-Sting
|
d23d0a5ec01e299f26d5557c9eb2b38470e9dc73
|
e81cafe4a7cb5726a28f9410ce687d877c8fbd72
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-11-20 23:50
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('votacao', '0006_votar_branco'),
]
operations = [
migrations.CreateModel(
name='Vaga',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(max_length=50, verbose_name='Vaga: ')),
],
),
migrations.AlterField(
model_name='votar',
name='candidato',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='Nome_Candidato', to='votacao.Candidato'),
),
migrations.AlterField(
model_name='votar',
name='eleitor',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='Nome_Eleitor', to='votacao.Eleitor'),
),
migrations.AddField(
model_name='candidato',
name='vaga',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='Nome', to='votacao.Vaga'),
),
]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-11-20 23:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('votacao', '0005_votar'),
]
operations = [
migrations.AddField(
model_name='votar',
name='branco',
field=models.BooleanField(default=1),
preserve_default=False,
),
]
<file_sep>from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
# Create your models here.
class Eleitor(models.Model):
nome = models.CharField('Nome ', max_length=200)
cpf = models.CharField('CPF ', max_length=200)
#usuario=models.ForeignKey(User, null=True, blank=False)
def __str__(self):
return str(self.nome)
class Vaga(models.Model):
nome = models.CharField('Vaga: ', max_length=50)
def __str__(self):
return 'Vaga: '+str(self.nome)
class Candidato(models.Model):
nome = models.OneToOneField(Eleitor, related_name='Nome', null=True, blank=False)
partido = models.CharField('Partido: ', max_length=10)
vaga = models.ForeignKey(Vaga, related_name='Nome', null=True, blank=False)
def __str__(self):
return 'Candidato: '+str(self.nome) + ' '+str(self.vaga)
class Token(models.Model):
numero = models.CharField('Numero: ', max_length=10)
def __str__(self):
return 'Token: '+str(self.numero)
class Votar(models.Model):
eleitor = models.OneToOneField(Eleitor, related_name='Nome_Eleitor', null=True, blank=False)
candidato = models.OneToOneField(Candidato, related_name='Nome_Candidato', null=True, blank=True)
token = models.OneToOneField(Token)
branco = models.BooleanField()
voto = models.BooleanField(default=1)
def __str__(self):
return 'Eleitor: '+str(self.eleitor) + ' '+str(self.token)
# Create your models here.
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-11-21 00:35
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('votacao', '0007_auto_20171120_2050'),
]
operations = [
migrations.AlterField(
model_name='candidato',
name='nome',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='Nome', to='votacao.Eleitor'),
),
]
<file_sep>from rest_framework import routers, serializers, viewsets
from django.contrib.auth.models import User
from votacao.models import *
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model=User
fields=('url', 'username', 'email', 'is_staff')
class EleitorSerializer(serializers.HyperlinkedModelSerializer):
usuario=UserSerializer(many=False)
class Meta:
model = Eleitor
fields = ('nome', 'cpf', 'usuario')
def create(self, dados):
dados_user = dados.pop('usuario')
u=User.objects.create(**dados_user)
p=Eleitor.objects.create(usuario=u, **dados)
return p
class CandidatoSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Candidato
fields = ('candidato', 'partido', 'vaga')
class VagaSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Vaga
fields = ('nome')
class TokenSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Token
fields = ('numero')
class VotarSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Votar
fields = ('eleitor', 'token')
<file_sep>from django.shortcuts import render
from votacao.models import *
# import para API
from rest_framework import routers, serializers, viewsets
from django.contrib.auth.models import User
from votacao.serializers import *
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
class EleitorViewSet(viewsets.ModelViewSet):
queryset = Eleitor.objects.all()
serializer_class = EleitorSerializer
class CandidatoViewSet(viewsets.ModelViewSet):
queryset = Candidato.objects.all()
serializer_class = CandidatoSerializer
class TokenViewSet(viewsets.ModelViewSet):
queryset = Token.objects.all()
serializer_class = TokenSerializer
class VotarViewSet(viewsets.ModelViewSet):
queryset = Votar.objects.all()
serializer_class = VotarSerializer
class VagaViewSet(viewsets.ModelViewSet):
queryset = Vaga.objects.all()
serializer_class = VagaSerializer
# Create your views here.
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-11-20 23:00
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('votacao', '0002_auto_20171120_1949'),
]
operations = [
migrations.CreateModel(
name='Candidato',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('partido', models.CharField(max_length=10, verbose_name='Partido: ')),
('nome', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='Nome', to='votacao.Eleitor')),
],
),
]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-11-20 23:19
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('votacao', '0004_token'),
]
operations = [
migrations.CreateModel(
name='Votar',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('candidato', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='Nome_Candidato', to='votacao.Candidato')),
('eleitor', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='Nome_Eleitor', to='votacao.Eleitor')),
('token', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='votacao.Token')),
],
),
]
<file_sep>from django.contrib import admin
from votacao.models import *
admin.site.register(Eleitor)
admin.site.register(Candidato)
admin.site.register(Token)
admin.site.register(Votar)
admin.site.register(Vaga)
# Register your models here.
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-11-20 22:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('votacao', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Eleitor',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(max_length=200, verbose_name='Nome ')),
('cpf', models.CharField(max_length=200, verbose_name='CPF ')),
],
),
migrations.DeleteModel(
name='Pessoa',
),
]
|
f19753ea3019caab931eb693515b82b874f86c4e
|
[
"Python"
] | 10
|
Python
|
1marcushenrique/G2LPC1
|
f3b6fffe7aec04e973efaeffaa0fc97a58092325
|
0c6d96d8fc5c4cc6d6b7aa93d74b9e993dc9f99c
|
refs/heads/master
|
<file_sep>const ContactsModel = require('./model');
const getAllContacts = async (owner, query) => {
const {limit = 5, offset = 0} = query;
const contacts = await ContactsModel.find({owner})
.populate({
path: 'owner',
select: ['_id', 'email'],
})
.skip(Number(offset))
.limit(Number(limit))
;
const total = await ContactsModel.find({owner}).count();
return {
contacts,
limit,
offset,
total
}
}
module.exports = getAllContacts;
<file_sep>const ContactsModel = require('./model');
const removeContact = async (owner, id) => {
return await ContactsModel.findOneAndRemove({_id: id, owner});
}
module.exports = removeContact;
<file_sep>const Contacts = require('../../model/contacts');
const ErrorException = require('../../exceptions/error.exception');
const remove = async (req, res, next) => {
try {
const {contactId} = req.params;
const {id: userId} = req.user;
const contact = await Contacts.removeContact(userId, contactId);
if (contact) {
return res.OK({contact});
}
return next(ErrorException.NotFound());
} catch (e) {
next(e);
}
}
module.exports = remove;
<file_sep>const Contacts = require('../../model/contacts');
const getAll = async (req, res, next) => {
try {
const {id: userId} = req.user;
const contacts = await Contacts.getAllContacts(userId, req.query);
return res.OK({...contacts});
} catch (e) {
next(e);
}
}
module.exports = getAll
<file_sep>const ContactsModel = require('./model');
const addContacts = async (body) => {
return await ContactsModel.create(body);
}
module.exports = addContacts;
<file_sep>const UserModel = require('../../model/users')
const login = async (req, res, next) => {
try {
const {email, password} = req.body;
const userInfo = await UserModel.login(email, password);
return res.OK({...userInfo});
} catch (e) {
next(e);
}
}
module.exports = login;
<file_sep>const UserModel = require('../../model/users')
const registration = async (req, res, next) => {
try {
const {email, password} = req.body;
const user = await UserModel.registration(email, password);
return res.Created({user});
} catch (e) {
next(e);
}
}
module.exports = registration;
<file_sep>const Contacts = require('../../model/contacts');
const create = async (req, res, next) => {
try {
const {id: userId} = req.user;
const contact = await Contacts.addContact({...req.body, owner: userId});
return res.Created({contact});
} catch (e) {
next(e);
}
}
module.exports = create;
<file_sep>const express = require('express');
const router = express.Router();
const ContactsController = require('../../controllers/contacts');
const {validation} = require('../../middlewares');
const {create, update} = require('../../validations/contacts');
router.get('/', ContactsController.getAll);
router.get('/:contactId', ContactsController.getById);
router.post('/', validation(create), ContactsController.create);
router.delete('/:contactId', ContactsController.remove);
router.patch('/:contactId', validation(update), ContactsController.update);
module.exports = router
<file_sep>require('dotenv').config();
const express = require('express');
const logger = require('morgan');
const cors = require('cors');
const ErrorException = require('./exceptions/error.exception');
const routes = require('./routes')
const app = express()
const formatsLogger = app.get('env') === 'development' ? 'dev' : 'short'
app.use(logger(formatsLogger))
app.use(cors())
app.use(express.json())
const {responseMethods} = require('./middlewares');
app.use(responseMethods);
app.use('/', routes);
app.use((_,__, next) => next(ErrorException.NotFound))
app.use((err, req, res, next) => {
const statusCode = err.status || 500;
res.status(statusCode).json({
status: statusCode === 500 ? 'fail' : 'error',
code: statusCode,
message: err.message,
errors: err.errors || []
})
})
module.exports = app
<file_sep>const {Schema, Types, model} = require('mongoose');
const contactsSchema = new Schema(
{
name: String,
email: String,
phone: String,
owner: {
type: Types.ObjectId,
ref: 'users',
required: true
}
},
{
versionKey: false,
timestamps: true
}
);
const Contacts = model('Contacts', contactsSchema);
module.exports = Contacts;
<file_sep>const UserModel = require('../../model/users');
const logout = async (req, res, next) => {
try {
const {id} = req.user;
await UserModel.logout(id);
return res.NoContent();
} catch (e) {
next(e);
}
}
module.exports = logout;
<file_sep>const User = require('./model');
const ErrorException = require('../../exceptions/error.exception');
const userDto = require('../../dtos/user');
const registration = async (email, password) => {
const candidate = await User.findOne({email})
if (candidate) {
throw ErrorException.BadRequest('User registered already');
}
const user = new User({email});
user.setPassword(password);
await user.save();
return userDto(user);
}
module.exports = registration;
<file_sep>MONGODB_URI=mongodb://<USERNAME>:<PASSWORD>@<HOST>:<PORT>/<DATABASE>?<OPTIONS...>
JWT_ACCESS_SECRET=<RANDOM_STRING>
<file_sep>const Joi = require('joi');
const create = Joi.object({
name: Joi.string().min(2).max(32).required(),
phone: Joi.string().pattern(new RegExp(/[0-9+()\s]{5,15}/)),
email: Joi.string().email().required()
});
const update = Joi.object({
name: Joi.string().min(2).max(32),
phone: Joi.string().pattern(new RegExp(/[0-9+()\s]{5,15}/)),
email: Joi.string().email()
}).or('name', 'email', 'phone');
module.exports = {
create,
update
}
<file_sep>const express = require('express');
const router = express.Router();
const AuthController = require('../../controllers/auth');
const {validation, auth} = require('../../middlewares');
const {registrationAndLogin} = require('../../validations/auth');
router.post('/registration', validation(registrationAndLogin), AuthController.registration);
router.post('/login', validation(registrationAndLogin), AuthController.login);
router.get('/logout', auth, AuthController.logout);
module.exports = router
<file_sep>const express = require('express');
const router = express.Router();
const {auth} = require('../../middlewares');
router.use('/auth', require('./auth'))
router.use('/contacts', auth, require('./contacts'))
module.exports = router;
<file_sep>const ContactsModel = require('./model');
const updateContact = async (owner, id, body) => {
return await ContactsModel.findOneAndUpdate({_id: id, owner}, {...body}, {new: true});
}
module.exports = updateContact;
|
00a8b104e3b8c1cf7ea4a34fc880651018fa0f87
|
[
"JavaScript",
"Shell"
] | 18
|
JavaScript
|
AlexLeonNovak/nodejs-homework-template
|
d8f3e4d3fe3b0884771168d589d7eccff5b28acb
|
1df2632bdad9049f11be94347bfc93caf7bc2127
|
refs/heads/main
|
<file_sep>#################################################
# LOAD REQUIRED PACKAGES
library("DESeq2")
library("ggplot2")
library("ggrepel")
#################################################
# PREP INPUT TABLE
# set your working dir
setwd("/Shares/CL_Shared/data/atma/1_QUARANTINE/9_NOV2020/testing_wiki_scripts/deseq_from_K27ac_chipseq/counts")
# read in the tab-delimited count table
countdata <- read.table("bamCountsWithinPeaks.tab", sep="\t", header = FALSE)
# check the table looks correct
head(countdata)
# create a new column which is the chr and coordinates combined
countdata$chr <- paste(countdata$V1,countdata$V2, sep=":")
countdata$coord <- paste(countdata$chr,countdata$V3, sep="-")
#countdata$coord
# set countdata$coord to be the rownames
rownames(countdata) <- countdata$coord
head(countdata)
# remove the first four columns (chr, start, stop, regionlabel)
# and the last two columns (coord, chr) since we don't need them anymore
# retaining only the counts
countdata <- countdata[, c(5, 6, 7, 8)]
head(countdata)
# add bam names as column names
colnames(countdata) <- c("0hr_sw480_run1","0hr_sw480_run2","16hr_sw480_run1","16hr_sw280_run2")
head(countdata)
# convert table to matrix format
countdata <- as.matrix(countdata)
head(countdata)
# assign control vs treated samples
condition <- factor(c(rep("control", 2), rep("treated", 2)))
# create a "coldata" table containing the sample names with their appropriate condition (e.g. control versus cancer sample)
coldata <- data.frame(row.names=colnames(countdata), condition)
coldata
#################################################
# RUN DESEQ2
# construct a DESeqDataSet
dds <- DESeqDataSetFromMatrix(countData = countdata, colData = coldata, design = ~ condition)
dds
# relevel to set the controls as the reference levels
dds$condition <- relevel(dds$condition, ref = "control")
dds
# run deseq2
dds <- DESeq(dds)
resultsNames(dds)
# call results
res_treated_vs_control <- results(dds, contrast=c("condition", "treated", "control"))
head(res_treated_vs_control)
# omit rows with counts of "N/A"
res_treated_vs_control <- na.omit(res_treated_vs_control)
head(res_treated_vs_control)
# sort results by ascending adjusted pvalue
res_treated_vs_control <- res_treated_vs_control[order(res_treated_vs_control$padj), ]
head(res_treated_vs_control)
# report the number of rows with an adjusted pvalue less than 0.05
table(res_treated_vs_control$padj<0.05)
#################################################
# SAVE RESULTS TABLES
# save this output table to fiji
# table will be saved to the current working dir (set at the start of this script)
# if you want to save it elsewhere, include the path before the file name
write.table(res_treated_vs_control, file="res_treated_vs_control.tab", quote = FALSE, row.names = TRUE, col.names=NA, sep = "\t")
# also save a table of the raw counts and normalized counts
raw_counts = counts(dds)
normalized_counts <- counts(dds, normalized=TRUE)
write.table(raw_counts, file="raw_counts.tab", quote = FALSE, row.names = TRUE, col.names=NA, sep = "\t")
write.table(normalized_counts, file="normalized_counts.tab", quote = FALSE, row.names = TRUE, col.names=NA, sep = "\t")
# extract regions that are significantly different in treated samples compared to control
# separate into two files based on whether they are significantly up (treated > control) or down (control > treated)
sigUp = subset(res_treated_vs_control, padj<0.05 & log2FoldChange>1)
head(sigUp)
nrow(sigUp)
write.table(sigUp, file="sigUp.tab", quote = FALSE, row.names = TRUE, col.names=NA, sep = "\t")
sigDown = subset(res_treated_vs_control, padj<0.05 & log2FoldChange<(-1))
head(sigDown)
nrow(sigDown)
write.table(sigDown, file="sigDown.tab", quote = FALSE, row.names = TRUE, col.names=NA, sep = "\t")
#################################################
# PLOT STUFF
# make an MA plot
plotMA(res_treated_vs_control, ylim=c(-10,10))
# save a copy of the MA plot
dev.copy(png,'treated_vs_control_MAplot.png')
dev.off()
# make a volcano plot using ggplot2
# first, make the results table a data frame
res_treated_vs_control <- as.data.frame(res_treated_vs_control)
res_treated_vs_control
ggplot(res_treated_vs_control, aes(log2FoldChange, -log10(padj)), colour="grey") +
scale_color_discrete(name = 'Labels') +
theme_bw() +
labs(y="-log10 adjusted pvalue", x = "log2 fold change") +
# set all dots to be grey
geom_point(data=res_treated_vs_control, colour = "grey") +
# if pvalue<0.05, change dot color to green
geom_point(data=res_treated_vs_control[which(res_treated_vs_control $padj <0.05),], colour = "springgreen2") +
# if log2FC >1, change dot color to orange
geom_point(data=res_treated_vs_control[which(abs(res_treated_vs_control $log2FoldChange)>1),], colour = "darkgoldenrod1") +
# if both, change dot color to blue
geom_point(data=res_treated_vs_control[which(abs(res_treated_vs_control $log2FoldChange)>1 & res_treated_vs_control$padj<0.05),], colour = "royalblue1") +
# add text labels to the most significant regions
geom_text_repel(data =res_treated_vs_control[which(res_treated_vs_control $padj <0.000005),], mapping = aes(log2FoldChange, -log10(padj), label = rownames(res_treated_vs_control[which(res_treated_vs_control $padj <0.000005),])),size = 4,force = 1)
# save a copy of the volcano plot
dev.copy(png, res=200, height = 1000, width = 1000, pointsize=4, 'treated_vs_control_volcano.png')
dev.off()
<file_sep>#!/bin/bash
## Script for computing bam read count table
## Date: 12 Nov 2020
##
## Example usage:
## bamOrder=/Shares/CL_Shared/data/atma/cohen2017_chip/bamOrder.txt \
## bed=/Shares/CL_Shared/data/atma/cohen2017_chip/ALL_peaks.narrowPeak \
## outDir=/Shares/CL_Shared/data/atma/cohen2017_chip/bamCounts \
## sbatch computeBamCountTable.q
##
## Note:
## bamOrder is a text file containing the full path and file names of all the bams, in the order they should appear as columns in the table
## You need to create the bamOrder file before running this script
## And you must include the full path to the bamOrder file, as shown above
##
## Here's what the inside of a bamOrder file could look like:
## /Shares/CL_Shared/data/atma/cohen2017_chip/file1.bam.sorted
## /Shares/CL_Shared/data/atma/cohen2017_chip/file2.bam.sorted
## /Shares/CL_Shared/data/atma/cohen2017_chip/file3.bam.sorted
## /Shares/CL_Shared/data/atma/cohen2017_chip/file4.bam.sorted
##
# General settings
#SBATCH -p short
#SBATCH -N 1
#SBATCH -c 8
#SBATCH --time=1-00:00
#SBATCH --mem=64GB
# Job name and output
#SBATCH -J bamCountTable
#SBATCH -o /Users/%u/slurmOut/slurm-%j.out
#SBATCH -e /Users/%u/slurmErr/slurm-%j.err
# load modules
module load bedtools
# define key variables
bams=$(cat $bamOrder)
# run the thing
pwd; hostname; date
echo "Starting bedtools..."
echo $(date +"[%b %d %H:%M:%S] Computing matrix of bam read counts...")
bedtools multicov -bams ${bams} -bed ${bed} > $outDir/bamCountsWithinPeaks.tab
echo $(date +"[%b %d %H:%M:%S] Done!")
<file_sep>#!/bin/bash
## Script for sorting and indexing bam files
## Date: 12 Nov 2020
##
## Example usage:
## inDir=/Shares/CL_Shared/data/atma/cohen2017_chip/bams sbatch --array 0-42 indexAndSortBam.q
# General settings
#SBATCH -p short
#SBATCH -N 1
#SBATCH -c 16
#SBATCH --time=1-00:00
#SBATCH --mem=64GB
# Job name and output
#SBATCH -J indexAndSortBam
#SBATCH -o /Users/%u/slurmOut/slurm-%A_%a.out
#SBATCH -e /Users/%u/slurmErr/slurm-%A_%a.err
# define query bam files
queries=($(ls $inDir/*.bam | xargs -n 1 basename))
# load modules
module load samtools
# run the thing
pwd; hostname; date
echo "Processing file: "${queries[$SLURM_ARRAY_TASK_ID]}
echo $(date +"[%b %d %H:%M:%S] Sorting bam file...")
samtools sort ${inDir}/${queries[$SLURM_ARRAY_TASK_ID]} -o ${inDir}/${queries[$SLURM_ARRAY_TASK_ID]}.sorted
echo $(date +"[%b %d %H:%M:%S] Indexing bam file...")
samtools index ${inDir}/${queries[$SLURM_ARRAY_TASK_ID]}.sorted
echo $(date +"[%b %d %H:%M:%S] Done!")
|
4ac17fbdf2cd4c226cedee3ecfd84a9f8ec87291
|
[
"R",
"Shell"
] | 3
|
R
|
atmaivancevic/chipseq-analysis
|
6a4c3e19c2ff495409e23cc1cfa1a2ff73c93e3d
|
b69e8f71af0feaf9f9625e809a0c43c5ad74cadc
|
refs/heads/master
|
<file_sep>import reveal from "reveal.js/dist/reveal.js";
import revealPluginNotes from "reveal.js/plugin/notes/notes.js";
import revealPluginZoom from "reveal.js/plugin/zoom/zoom.js";
import revealPluginMathJax from "reveal.js/plugin/math/math.js";
import "reveal.js/dist/reveal.css";
import "prismjs/themes/prism.css";
import "./slides.css";
import slidesContent from "training-material/Slides/slides.json";
const slideContainer = document.querySelector(".slides");
slideContainer.innerHTML = slidesContent.join("\n");
reveal.initialize({
controls: true,
progress: true,
history: true,
center: false,
transition: "fade", // default/cube/page/concave/zoom/linear/fade/none
backgroundTransition: "fade",
slideNumber: false,
mouseWheel: true,
margin: 0,
width: 1420,
height: 800,
plugins: [revealPluginMathJax, revealPluginNotes, revealPluginZoom],
});
<file_sep>const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const DEFAULT_TRAINING_MATERIAL_FOLDER = "training-material";
module.exports = (env = {}, argv) => {
if (!env.material) {
console.warn(
`WARNING: '--env.material' option not set. Falling back on the default: '${DEFAULT_TRAINING_MATERIAL_FOLDER}'`
);
}
const trainingMaterialFolder = path.resolve(
env.material || DEFAULT_TRAINING_MATERIAL_FOLDER
);
console.log(
`Training material folder: '${trainingMaterialFolder}'.`,
`This can be changed using '--env.material=<relative path to training material folder>'.`
);
return {
mode: "development",
entry: { slides: "./src/slides/slides.js", labs: "./src/labs/labs.js" },
module: {
rules: [
{
test: [/slides\.json$/, /parts\.json$/],
type: "javascript/auto",
use: "./src/loaders/slides-json-loader",
},
{
test: /\.md$/,
use: ["html-loader", "./src/loaders/revealjs-loader"],
},
{
test: /\.css$/,
use: [{ loader: MiniCssExtractPlugin.loader }, "css-loader"],
},
{
test: /reveal\.js[\/\\]js[\/\\]reveal\.js$/,
use: { loader: "expose-loader", options: "Reveal" },
},
{
test: /\.(png|jpe?g|gif|svg|webp|mp3|ttf)$/i,
use: {
loader: "file-loader",
options: {
name: "[name]-[contenthash].[ext]",
outputPath: "static-assets",
},
},
},
],
},
resolve: {
alias: {
"training-material": trainingMaterialFolder,
},
},
output: {
path: path.resolve("./dist"),
},
plugins: [
new HtmlWebpackPlugin({
template: "src/slides/slides.html",
chunks: ["slides"],
filename: "slides.html",
}),
new HtmlWebpackPlugin({
template: "src/labs/labs.html",
chunks: ["labs"],
filename: "labs.html",
}),
new MiniCssExtractPlugin(),
],
devServer: {
contentBase: false,
},
};
};
<file_sep>#!/bin/sh
docker container run \
--interactive \
--tty \
--rm \
--volume $(pwd):/training-material:ro \
--publish 8080:8080 \
zenika/sensei
<file_sep>const fs = require("fs");
const puppeteer = require("puppeteer");
async function urlToPdfString(url, options) {
const browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"],
});
const page = await browser.newPage();
await page.goto(url);
const pdfContent = await page.pdf(options);
browser.close();
return pdfContent.toString("base64");
}
async function savePdfFile(filepath, url, options) {
const pdfContent = await urlToPdfString(url, options);
await fs.promises.writeFile(filepath, pdfContent, "base64");
}
if (require.main === module) {
if (process.argv.length !== 4) {
console.error("Usage: node pdf.js <url> <output file path>");
return;
}
savePdfFile(process.argv[3], process.argv[2]).then(() =>
console.log("Done!")
);
}
<file_sep>#!/bin/sh
docker container run \
--interactive \
--tty \
--rm \
--volume $(pwd):/slides \
--net host \
astefanutti/decktape http://localhost:8080/slides.html slides.pdf
<file_sep>const tap = require("tap");
const slidesJsonLoader = require("./slides-json-loader");
tap.equal(slidesJsonLoader(JSON.stringify([])), "export default []");
<file_sep># @zenika/sensei
Sensei is meant to be a replacement of [zenika-formation-framework](https://github.com/Zenika/zenika-formation-framework/),
using a simpler and newer stack. It's not up-to-par in terms of features, but it's ready for test drives.
## Usage
### Using the published Docker image 🐳
- `cd` into a training material folder (must have `Slides/slides.json` and `CahierExercices/parts.json`)
- Run `docker run -it --rm -p 8080:8080 -v $(pwd):/training-material zenika/sensei`.
- Navigate to `http://localhost:8080/slides.html` for slides and `http://localhost:8080/labs.html` for labs
### Using a Docker image built from sources 🐳
- Clone this repo and `cd` into the created folder
- `sh build.sh`
- `cd` into a training material folder (must have `Slides/slides.json` and `CahierExercices/parts.json`)
- `sh ../path/to/sensei/run.sh`
- Navigate to `http://localhost:8080/slides.html` for slides and `http://localhost:8080/labs.html` for labs
### Using Node.js
- Clone this repo and `cd` into the created folder
- `npm install`
- `npm start -- --env.material=/path/to/training-material-folder`
- Navigate to `http://localhost:8080/slides.html` for slides and `http://localhost:8080/labs.html` for labs
### Generating PDFs
- Run the web server like described above and leave it running
- `cd` into `src/pdf`
- `npm install`
- `npm run slides` to generate a PDF for the slides
- `npm run labs` to generate a PDF for the labs
## Reveal plugins
The following plugins are enabled: Markdown, Highlight, Zoom, Notes and Math.
Refer to [Reveal's documentation](https://revealjs.com/plugins/#built-in-plugins) for usage.
## Tip: using a shell alias
You may want to define the following alias to be able to run slides using `slides`:
```
alias slides='docker container run \
--interactive \
--tty \
--rm \
--volume $(pwd):/training-material \
--publish 8080:8080 \
zenika/sensei'
```
<file_sep>FROM node:12-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --production
COPY ./ ./
VOLUME [ "/training-material" ]
EXPOSE 8080
ENTRYPOINT [ "npm", "start", "--silent", "--" ]
CMD ["--host", "0.0.0.0", "--env.material=/training-material"]
<file_sep>#!/bin/sh
docker image build . --tag zenika/sensei
<file_sep>import "./labs.css";
import labs from "training-material/CahierExercices/parts.json";
const labsContainer = document.querySelector(".labs");
labsContainer.innerHTML = labs.join("\n");
|
18545553d59115b760c34432ac6196cb54cdb685
|
[
"JavaScript",
"Dockerfile",
"Markdown",
"Shell"
] | 10
|
JavaScript
|
david-dasilva/sensei
|
5ee5723de8f17f526728728359241b39f60dcc52
|
3ae79c9dbf755c690272be347b7daa535ca3ea2d
|
refs/heads/master
|
<file_sep>/****************************************************************************
Copyright (c) 2015 feihan inspiration.
http://www.flewawayblog.sinnapp.com
*descriptions:
this files contains functions that will be used in game,in other words,this is
a lib of functions
****************************************************************************/
#include "cocos2d.h"
#include <string>
USING_NS_CC;
/*---------------------------------------------------------------------------
*NAME: toStr
*PARA: T any type will be okay
*DESC: change any type of data to string
----------------------------------------------------------------------------*/
template <typename T> std::string tostr(const T& t)
{
std::ostringstream os; os << t; return os.str();
}
/*---------------------------------------------------------------------------
*NAME: getArrayLength
*PARA: T any type of array will be okay
*DESC: get the length of array length (PS: will not work if the array is
created by "new")
----------------------------------------------------------------------------*/
template <typename T> int getArrayLength(const T& t)
{
return sizeof(t) / sizeof(t[0]);
}
/*---------------------------------------------------------------------------
*NAME: seekFromRootByName
*PARA: Node* _root: search root of the csb file
string& name: name of node,when you edit in cocostuio,you gave it a
name
*DESC: select the very widget from csb file by name. In this way,you will no
longer be trouble to find the widget from csb file;
-----------------------------------------------------------------------------*/
Node* seekFromRootByName(Node* _root, std::string& name);<file_sep>#ifndef __FTANK_H__
#define __FTANK_H__
#pragma once
#include "cocos2d.h"
#include "../extensions/cocos-ext.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include "Bullet.h"
using namespace cocos2d::ui;
/*--------------------------------------------------------------
*NAME: BloodBar
*DESC: this is the Blood of tank
---------------------------------------------------------------*/
class BloodBar : public Node
{
public:
static BloodBar* create();
virtual bool init();
//on blood recover
void increase(int blood);
//on be attacked
void decreace(int blood);
void setRange(int maxBlood);
void setBlood(int blood);
int getBlood()const;
cocos2d::Size getBloodBarSize()const; //获取血条的大小
protected:
BloodBar();
~BloodBar();
private:
cocos2d::Sprite* m_currBloodBar; //当前血量同步精灵 作为这个控件的子节点
cocos2d::Sprite* m_bloodBg; //血条背景
int m_range; //血条范围
int m_currBlood; //当前血量
};
/*---------------------------------------------------------------
*NAME: FTank
*DESC: this is the base of Tank.
---------------------------------------------------------------*/
class FTank : public Sprite
{
public:
//tank direction definition;
enum class TankDirect
{
TD_UP,
TD_UP_RIGHT,
TD_RIGHT,
TD_RIGHT_DOWN,
TD_DOWN,
TD_DOWN_LEFT,
TD_LEFT,
TD_LEFT_UP
};
//init tank after created
virtual bool init();
//be attacked
void beAttacked(int damage);
protected:
FTank();
virtual ~FTank();
//turning methods
//turn diretion methods
void turnUp();
void turnDown();
void turnRight();
void turnLeft();
//tank die and run a animation
virtual void goDie();
protected:
BloodBar* m_healthHub; //blood
Vec2 m_currentDir; //current tank direction
int m_HP; //blood level
int m_level; //tank level
int m_damageLevel; //value of attack
cocos2d::Size m_tankSize; //size of tank
float m_angle; //current angle after spin
Vec2 m_headPoint; //head to fire
Vec2 m_healthBarPos; //health bar position
};
/*-------------------------------------------------------------------------
*NAME: EnemyTank
*DESC: this kind of tank have it's own mind, sometimes it will kown how to
* avoid being attack and kown how to attack you
-------------------------------------------------------------------------*/
class EnemyTank :public FTank
{
public:
//create function...
CREATE_WITH_TEXTURE(EnemyTank);
CREATE_WITH_FILE(EnemyTank);
//init Tank after constructed
virtual bool init();
enum class EnemySpeed
{
ES_SPEED=45
};
//tank AI start! it should have it's own mind
void AIStart();
private:
//fire method
void fire(float dt);
//update to change robot's reaction, in some way it looks like it has its own mind
void update(float dt);
private:
Vec2 m_lastPostion; //postion before update
protected:
//let constructor and desconstructor be protected so that this class
//won't be created unconsitiously
EnemyTank();
virtual ~EnemyTank();
};
/*--------------------------------------------------------------------------
*NAME: PlayerTank
*DESC:
---------------------------------------------------------------------------*/
class PlayerTank :public FTank
{
public:
//create function...
CREATE_WITH_TEXTURE(PlayerTank);
CREATE_WITH_FILE(PlayerTank);
//attack type , in this way it will be convinient to extends
enum class PlayerAction
{
PA_FIRE_BULLET, //fire normal bullet
PA_FIRE_BOMB, //send big bombs
PA_SLIDE, //slide a little way
PA_ULTIMATE, //the ultimate skill
PA_CALL_MERCENARY, //call mercenries
PA_TRANSFORM //transform
};
//playerTank type, it has diffent type with diffent abbility
enum class PlayerTankForm
{
PTF_HEAVY, //heavy tank which can launch heavy artillery
PTF_LIGHT, //light tank which is faster
PTF_LANDMINER //miner tank which can install landmines
};
enum class PlayerTankSpeed //the value need to be considered later+++++
{
PTS_LIGHT=35,
PTS_HEAVY=25,
PTS_LANDMINER=20
};
enum class PlayerTankMass //mass of different type
{
PTM_LIGHT = 100,
PTM_HEAVY = 300,
PTM_LANDMINER=200
};
//init Tank after constructed
virtual bool init();
//controll by the player to move
void move(Ref *pSender, Widget::TouchEventType _touchType, FTank::TankDirect _dir);
//try to attack
void act(Ref *pSender, Widget::TouchEventType _touchType, PlayerTank::PlayerAction _playerAction);
public:
//DESC: refresh the CD time of skills
//function type: return void, para: PlayerAction
std::function<void(PlayerTank::PlayerAction _playerAction)> onAct; //cd time refresh
bool getSkillCD(int* &cdArray,int& arrLen);
//DESC:
std::function<void(Vec2 _dir)> onMapMove;
protected:
PlayerTank();
virtual ~PlayerTank();
//override goDie method
virtual void goDie()override;
private:
PlayerTankForm m_currentForm; //current form of player
int m_exp; //exprence of the player
int m_skillCd[3]; //cd time of 3 skills
int m_transformCD; //cd time of transform
};
#endif //__FTANK_H__
<file_sep>#include "Tank.h"
//====================================================================
//=============class name:BloodBar
//====================================================================
//2015-7-12
BloodBar::BloodBar()
:m_currBloodBar(nullptr)
, m_bloodBg(nullptr)
{
}
BloodBar::~BloodBar()
{
}
BloodBar* BloodBar::create()
{
BloodBar* pBloodBar = new (std::nothrow)BloodBar();
if (pBloodBar && pBloodBar->init())
{
pBloodBar->autorelease();
return pBloodBar;
}
else
{
CC_SAFE_DELETE(pBloodBar);
return nullptr;
}
}
bool BloodBar::init()
{
m_bloodBg = Sprite::create(hubBgPath);
m_bloodBg->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
m_currBloodBar = Sprite::create(hubPath);
m_currBloodBar->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT);
m_bloodBg->addChild(m_currBloodBar);
m_currBloodBar->setPosition(Vec2(0,0));
m_bloodBg->setPosition(Vec2(0,0));
this->addChild(m_bloodBg);
return true;
}
void BloodBar::increase(int blood)
{
m_currBlood += blood;
float rate = m_currBlood / m_range;
float currWidth = this->getContentSize().height / m_currBloodBar->getContentSize().height;
m_currBloodBar->setScaleX(rate*currWidth);
}
void BloodBar::decreace(int blood)
{
m_currBlood -= blood;
float rate = m_currBlood / m_range;
float currWidth = this->getContentSize().height / m_currBloodBar->getContentSize().height;
m_currBloodBar->setScaleX(rate*currWidth);
}
void BloodBar::setRange(int maxBlood)
{
m_range = maxBlood;
}
void BloodBar::setBlood(int blood)
{
m_currBlood = blood;
}
int BloodBar::getBlood()const
{
return m_currBlood;
}
Size BloodBar::getBloodBarSize()const
{
return m_bloodBg->getContentSize();
}
//====================================================================
//=============class name:FTank
//====================================================================
//2015-7-12
FTank::FTank()
:m_angle(0.0f)
, m_currentDir(Vec2(0,1))
{
}
FTank::~FTank()
{
}
void FTank::turnUp()
{
this->setRotation(0.0f);
m_angle = 0.0f;
m_currentDir = Vec2(0, 1);
m_headPoint = Vec2(0, m_tankSize.height);//计算发炮点
m_healthBarPos = Vec2(m_tankSize.width / 2, m_tankSize.height + 10);//计算血条位置
}
void FTank::turnDown()
{
this->setRotation(180.0f);
m_angle = 180.0f;
m_currentDir = Vec2(0, -1);
m_headPoint = Vec2(0, -m_tankSize.height);//++
m_healthBarPos = Vec2(m_tankSize.width / 2, -10);//++
}
void FTank::turnRight()
{
this->setRotation(90.0f);
m_angle = 90.0f;
m_currentDir = Vec2(1, 0);
m_headPoint = Vec2(m_tankSize.width, 0);//++
m_healthBarPos = Vec2(-10, m_tankSize.height / 2);//++
}
void FTank::turnLeft()
{
this->setRotation(270.0f);
m_angle = 270.0f;
m_currentDir = Vec2(-1, 0);
m_headPoint = Vec2(-m_tankSize.width / 2, 0);//++
m_healthBarPos = Vec2(10 + m_tankSize.width, m_tankSize.height / 2);//++
}
bool FTank::init()
{
//add your code below...
return true;
}
void FTank::beAttacked(int damage)
{
m_HP -= damage;
m_healthHub->decreace(damage);
if (m_HP <= 0) //当血量降到 0 时 执行死亡
goDie();
}
void FTank::goDie()
{
//然后从界面消失
this->removeFromParentAndCleanup(true);
}
//====================================================================
//=============class name:EnemyTank
//====================================================================
//2015-8-24
EnemyTank::EnemyTank()
:m_lastPostion(Vec2(0,0))
{
}
EnemyTank::~EnemyTank()
{
}
bool EnemyTank::init()
{
//super init first...
if (!FTank::init())
return false;
//add your code below
//get tank size +++++++++++
//////////////////////////
this->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
//add blood bar
m_healthHub = BloodBar::create();
m_healthHub->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
m_tankSize = this->getContentSize();
m_healthHub->setPosition(Vec2(m_tankSize.width / 2, m_tankSize.height + 10));
m_headPoint = Vec2(0, m_tankSize.height);
m_healthHub->setScale(0.05f);
this->addChild(m_healthHub);
//fire a bullet every 2 seconds
schedule(CC_SCHEDULE_SELECTOR(EnemyTank::fire), 2.0f);
return true;
}
void EnemyTank::fire(float dt)
{
auto bullet = Bullet::create("pic/bullet.png");
bullet->getPhysicsBody()->setTag(ENEMY_BULLET_TAG);
bullet->setRotation(m_angle);
this->getParent()->addChild(bullet);
bullet->setPosition(this->getPosition() + m_headPoint);
bullet->getPhysicsBody()->setVelocity(Vec2(m_currentDir.x * 55, m_currentDir.y * 55));
}
void EnemyTank::AIStart()
{
auto speed = EnemyTank::EnemySpeed::ES_SPEED;
this->getPhysicsBody()->setVelocity(Vec2(m_currentDir.x * (int)speed, m_currentDir.y * (int)speed));
this->schedule(schedule_selector(EnemyTank::update), 4.0f); //
}
void EnemyTank::update(float dt)
{
auto currPos = this->getPosition();
if (currPos != m_lastPostion) //在这个时间段内坐标没变,被挡住了,这个时候需要转向
{
srand((unsigned)time(0)); //随机选择一个方向 根据当前时间和坐标 取随机方向
auto dir = (rand() + (int)(currPos.x + currPos.y) % 7) % 4;
switch (dir)
{
case 0:
turnUp();
break;
case 1:
turnRight();
break;
case 2:
turnDown();
break;
case 3:
turnLeft();
break;
default:
break;
}
//set position of blood bar
m_healthHub->setRotation(360.0f - m_angle);
m_healthHub->setPosition(m_healthBarPos);
auto speed = EnemyTank::EnemySpeed::ES_SPEED;
this->getPhysicsBody()->setVelocity(Vec2(m_currentDir.x * (int)speed, m_currentDir.y * (int)speed));
}
}
//====================================================================
//=============class name:PlayerTank
//====================================================================
//2015-7-12
PlayerTank::PlayerTank()
:m_currentForm(PlayerTank::PlayerTankForm::PTF_LIGHT)
, onAct(nullptr)
, onMapMove(nullptr)
{
memset(m_skillCd,0,sizeof(m_skillCd)); //set CDs to be zero
}
PlayerTank::~PlayerTank()
{
}
bool PlayerTank::init()
{
//add your code below...
if (!FTank::init())
return false;
//////////////////////////
this->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
//add blood bar
m_healthHub = BloodBar::create();
m_healthHub->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
m_tankSize = this->getContentSize();
m_healthHub->setPosition(Vec2(m_tankSize.width/2,m_tankSize.height+10));
m_headPoint = Vec2(0, m_tankSize.height);
m_healthHub->setScale(0.05f);
this->addChild(m_healthHub);
return true;
}
void PlayerTank::goDie()
{
//
}
bool PlayerTank::getSkillCD(int* &cdArray, int& arrLen)
{
cdArray = m_skillCd;
arrLen = 3;
return true;
}
void PlayerTank::move(Ref *pSender, Widget::TouchEventType _touchType, FTank::TankDirect _dir)
{
if (_touchType == Widget::TouchEventType::MOVED || _touchType == Widget::TouchEventType::BEGAN)
{
//get speed based on tank form
int speed;
if (m_currentForm == PlayerTank::PlayerTankForm::PTF_HEAVY)
speed = (int)(PlayerTank::PlayerTankSpeed::PTS_HEAVY);
else if (m_currentForm == PlayerTank::PlayerTankForm::PTF_LIGHT)
speed = (int)(PlayerTank::PlayerTankSpeed::PTS_LIGHT);
else
speed = (int)(PlayerTank::PlayerTankSpeed::PTS_LANDMINER);
switch (_dir)
{
case FTank::TankDirect::TD_UP:
{
turnUp();
this->getPhysicsBody()->setVelocity(Vec2(0, 0 + speed));
break;
}
case FTank::TankDirect::TD_UP_RIGHT:
{
this->m_currentDir = Vec2(0.5,0.5);
this->setRotation(45.0f);
m_angle = 45.0f;
m_headPoint = Vec2();
this->getPhysicsBody()->setVelocity(Vec2(0 + cos(speed), 0 + sin(speed)));
break;
}
case FTank::TankDirect::TD_RIGHT:
{
turnRight();
this->getPhysicsBody()->setVelocity(Vec2(0 + speed, 0));
break;
}
case FTank::TankDirect::TD_RIGHT_DOWN:
{
this->m_currentDir = Vec2(0.5,-0.5);
this->setRotation(135.0f);
m_angle = 135.0f;
this->getPhysicsBody()->setVelocity(Vec2(0 + cos(speed), 0 - sin(speed)));
break;
}
case FTank::TankDirect::TD_DOWN:
{
turnDown();
this->getPhysicsBody()->setVelocity(Vec2(0, 0 - speed));
break;
}
case FTank::TankDirect::TD_DOWN_LEFT:
{
this->m_currentDir = Vec2(-0.5,-0.5);
this->setRotation(225.0f);
m_angle = 225.0f;
this->getPhysicsBody()->setVelocity(Vec2(0 - cos(speed), 0 - sin(speed)));
break;
}
case FTank::TankDirect::TD_LEFT:
{
turnLeft();
this->getPhysicsBody()->setVelocity(Vec2(0 - speed, 0));
break;
}
case FTank::TankDirect::TD_LEFT_UP:
{
this->m_currentDir = Vec2(-0.5,0.5);
this->setRotation(315.0f);
m_angle = 315.0f;
m_headPoint = Vec2(m_tankSize.width / 2, m_tankSize.height);
this->getPhysicsBody()->setVelocity(Vec2(0 - cos(speed), 0 + sin(speed)));
break;
}
default:
break;
}
m_healthHub->setRotation(360.0f-m_angle);
m_healthHub->setPosition(m_healthBarPos);
}
//if button released, set velocity equals zero
else if (_touchType == Widget::TouchEventType::ENDED || _touchType == Widget::TouchEventType::CANCELED)
{
this->getPhysicsBody()->setVelocity(Vec2::ZERO);
}
}
void PlayerTank::act(Ref *pSender, Widget::TouchEventType _touchType, PlayerTank::PlayerAction _playerAction)
{
if (_touchType == Widget::TouchEventType::BEGAN)
{
if (m_currentForm == PlayerTank::PlayerTankForm::PTF_LIGHT)
{
switch (_playerAction)
{
case PlayerTank::PlayerAction::PA_FIRE_BULLET:
{
if (m_skillCd[0] <= 0)
{
if (onAct != nullptr)
onAct(PlayerTank::PlayerAction::PA_FIRE_BULLET);
}
auto bullet = Bullet::create("pic/bullet.png");
bullet->getPhysicsBody()->setTag(PLAYER_BULLET_TAG);
this->getParent()->addChild(bullet);
bullet->setPosition(this->getPosition() + m_headPoint);
bullet->setRotation(m_angle);
bullet->getPhysicsBody()->setVelocity(Vec2(m_currentDir.x*55,m_currentDir.y*55));
break;
}
case PlayerTank::PlayerAction::PA_FIRE_BOMB:
{
if (m_skillCd[1] <= 0)
{
if (onAct != nullptr)
onAct(PlayerTank::PlayerAction::PA_FIRE_BOMB);
}
auto bomb = Bomb::create("pic/bomb.png");
bomb->getPhysicsBody()->setTag(PLAYER_BULLET_TAG);
this->getParent()->addChild(bomb);
bomb->setPosition(this->getPosition() + m_headPoint);
bomb->setRotation(m_angle);
bomb->getPhysicsBody()->setVelocity(Vec2(m_currentDir.x * 35, m_currentDir.y * 35));
break;
}
case PlayerTank::PlayerAction::PA_SLIDE:
{
break;
}
case PlayerTank::PlayerAction::PA_CALL_MERCENARY:
{
break;
}
case PlayerTank::PlayerAction::PA_ULTIMATE:
{
break;
}
}
}
}
}<file_sep>#ifndef _BASE_LAYER_H_
#define _BASE_LAYER_H_
#include "audio/include/SimpleAudioEngine.h"
#include "../extensions/cocos-ext.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include "AISystem.h"
using namespace cocos2d::ui;
using namespace CocosDenshion;
//definition of unitive method to run this chapter
#define RUN_THIS_CHAPTER(__TYPE__) \
virtual void runThisChapter() \
{ \
auto scene = Scene::createWithPhysics(); \
scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL); \
scene->addChild(this); \
auto transScene = TransitionTurnOffTiles::create(0.8f, scene); \
Director::getInstance()->replaceScene(transScene); \
}
/*------------------------------------------------------------------------------------
*CLASS NAME: BaseLayer
*DESC: common abilities of each chapter,including music controll and contact test
*USAGE: to inherit this class and implement the "runThisChapter" method.
watch out: only when you have load the map first can you init a player in a map
or no player will show up
-------------------------------------------------------------------------------------*/
class BaseLayer :public cocos2d::Layer
{
public:
BaseLayer();
~BaseLayer();
//init this layer when created
//DESC: including creating a edge to limit tank
virtual bool init();
//every chapter should have this method to create a scene to load this layer
virtual void runThisChapter()=0;
//trun on the background music ,this will called when scene is initialized first
void turnOnBgMusic(Ref *pSender, Widget::TouchEventType _touchType);
//pause the game
void gamePause(Ref *pSender, Widget::TouchEventType _touchType);
//return to main menu
void returnToMainScene(Ref *pSender, Widget::TouchEventType _touchType);
//refresh CD time to controll the button
void refreshButtonCD(float dt);
//controll the map to move
void onMapMove(Vec2 _dir);
protected:
//init playar in scene
//DESC: set player in the scene and set button event bind with tank action methods
// this will call the next function--> setButtonListener.
// in this way to ensure it is safe to add player to the scene and set event
// listener
void initPlayer();
//set button listener
//DESC: as is described above , this method will called when player initialized
void setButtonListener();
//set contact listener
//DESC: called when baseScene initialized
void setContactListener();
//method of contact test
//DESC: controll what to do when a Collision is heard
bool contactListen(const PhysicsContact& contact);
protected:
cocos2d::Node* m_map; //µØÍ¼
bool m_isBgMusicRunning; //background music running status
PlayerTank* m_currentPlayer;
AISystem m_AIManager; //AI system manager
int m_chapterNo; //¹Ø¿¨ºÅ
ui::Button* m_skillButton[4]; //¼¼Äܼü
};
// C++ 11
#endif //__BASE_LAYER_H__
<file_sep>#include "AISystem.h"
AISystem::AISystem(cocos2d::Layer* targetLayer)
:m_battleLand(targetLayer)
{
}
AISystem::~AISystem()
{
}
void AISystem::initTanksInScene(std::vector<Vec2> _positions)
{
for (auto pos : _positions)
{
addRobot(pos);
}
}
void AISystem::addRobot(Vec2 _pos)
{
auto robot = EnemyTank::create(enemyPath);
m_battleLand->addChild(robot);
robot->setPosition(_pos);
robot->getPhysicsBody()->setTag(ENEMY_TAG);
robot->AIStart();
m_robots.push_back(robot);
}
std::vector<EnemyTank*> AISystem::getAllEnemies()
{
return m_robots;
}
bool AISystem::removeAllEnemies()
{
for (auto& robot : m_robots)
{
robot->removeFromParentAndCleanup(true);
}
return true;
}<file_sep>#include "GameHandleLib.h"
//select the very widget from csb file by name
Node* seekFromRootByName(Node* _root, std::string& name)
{
if (!_root)
return nullptr;
if (_root->getName() == name)
return _root;
const auto& childArray = _root->getChildren();
for (auto& child : childArray)
{
Node* pNode = dynamic_cast<Node*>(child); //? or static_cast?
if (pNode)
{
Node* res = seekFromRootByName(pNode, name);
if (res)
return res;
}
}
return nullptr;
}<file_sep>#ifndef __CHAPTER_CONTROLLER_H__
#define __CHAPTER_CONTEOLLER_H__
#include <functional>
#include "chapter1.h"
using namespace std;
/*------------------------------------------------------------------------------
NAME:章节控制器
DESC:将所有章节集合到一个数组中,调用场景通过数组下标完成
USAGE: chapters[idx].callBack()->runThisChapter()
--------------------------------------------------------------------------------*/
typedef struct controller
{
const char* chapterName; //章节名称
const char* chapterLookPath; //章节预览图地址
function<BaseLayer*()> callBack; //章节调用器
}ChapterControoler;
static ChapterControoler chapters[] =
{
{ "protect princess-apartment of CUG", "pic/chapterTest.png", [](){return Chapter1::create(); } }
};
#endif
<file_sep>
#include "Bullet.h"
//====================================================================
//=============class name:Bullet
//====================================================================
//2015-7-23
Bullet::Bullet()
:m_damage(PLAYER_BULLET_DAMAGE)
, m_dagameRange(BULLET_DAMAGE_RANGE)
{
}
Bullet::~Bullet()
{
}
bool Bullet::init()
{
return true;
}
void Bullet::explode()
{
this->removeFromParentAndCleanup(true);
}
int Bullet::getDamageRange()const
{
return m_dagameRange;
}
//====================================================================
//=============class name:Bomb
//====================================================================
//2015-7-23
Bomb::Bomb()
{
m_damage = BOMB_DAMAGE_RANGE;
m_dagameRange = BOMB_DAMAGE_RANGE;
}
Bomb::~Bomb()
{
}
bool Bomb::init()
{
//super init first~
if (!Bullet::init())
return false;
return true;
}
void Bomb::explode()
{
this->getPhysicsBody()->removeFromWorld();
auto CurrentPoint = this->getPosition();
auto body = PhysicsBody::createCircle(m_dagameRange, PHYSICSSHAPE_MATERIAL_DEFAULT, Vec2::ZERO);
this->setPhysicsBody(body);
m_bom = ParticleSystemQuad::create("explode/BOM.plist");
addChild(m_bom);
m_bom->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
m_bom->setPosition(Vec2(0,0));
scheduleOnce(CC_SCHEDULE_SELECTOR(Bomb::removeStunt), 0.5f);
}
void Bomb::removeStunt(float dt)
{
this->removeFromParentAndCleanup(true);
}
//====================================================================
//=============class name:NuclearWeapon
//====================================================================
//2015-7-23
NuclearWeapon::NuclearWeapon()
{
m_damage = NUCLEAR_WEAPON_DAMAGE;
m_dagameRange = NUCLEAR_WEAPON_DAMAGE_RANGE;
}
NuclearWeapon::~NuclearWeapon()
{
}
bool NuclearWeapon::init()
{
//super init first~
if (!Bullet::init())
return false;
return true;
}
void NuclearWeapon::explode()
{
}
<file_sep>#include "PreloadScene.h"
#include "MainMenu.h"
#include "VisibleRect.h"
#include "../GameResource.h"
#include "audio/include/SimpleAudioEngine.h"
#include<thread>
USING_NS_CC;
using namespace CocosDenshion;
Scene* PreloadScene::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = PreloadScene::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool PreloadScene::init()
{
//////////////////////////////
// 1. super init first
if (!Layer::init())
{
return false;
}
//3 seconds to show our logo
scheduleOnce(CC_SCHEDULE_SELECTOR(PreloadScene::jumpOut), 2.0f);
//init our logo here...
auto logo = Sprite::create(logoImgPath);
auto _visibleRect = VisibleRect::getVisibleRect();
logo->setPosition(Vec2(_visibleRect.size.width / 2, _visibleRect.size.height / 2));
this->addChild(logo);
//try to load files the game need
std::thread preloadThread(&PreloadScene::preloadFiles, this);
preloadThread.detach();
return true;
}
/*
*NAME:jumpOut
*PARA:float dt refers to during time
*DESC:by TransitionTurnOffTiles jump, during time is 0.8 seconds;
**/
void PreloadScene::jumpOut(float dt)
{
auto mainMenuScene = MainMenu::createScene();
auto transScene = TransitionTurnOffTiles::create(0.8f, mainMenuScene);
auto director = Director::getInstance();
director->replaceScene(transScene);
}
/*
*NAME:preloadFiles
*PARA:N
*DESC:preload pictures,musics,and so on... so as to show our logo for 2 seconds
**/
void PreloadScene::preloadFiles()
{
//preload the background music
SimpleAudioEngine::getInstance()->preloadBackgroundMusic(LoadingMusicPath);
}<file_sep>////////////////////////////////////////////////////////////////////////////////////////
//
// basic defenition of game
//
////////////////////////////////////////////////////////////////////////////////////////
//物理对象标签
#define PLAYER_TAG 1001 //玩家标签
#define ENEMY_TAG 1002 //敌方标签
#define MAP_BARRIAR_TAG 1003 //地图障碍物标签
#define PLAYER_BULLET_TAG 1004 //玩家子弹标签
#define ENEMY_BULLET_TAG 1005 //敌方
#define EDGE_BOX_TAG 1006 //外围墙标签
#define MAP_POOL_TAG 1007 //地图中湖泊标签
//物理对象掩码
#define UNITIVE_MASK 0xffffffff //通用碰撞掩码
#define POOL_MASK 0x00000000 //河流碰撞掩码
//物理对象种群
#define WEAPON_GROUP 1 //武器种群
#define PLAYER_GROUP 2 //玩家种群
#define ENEMY_GROUP 2
//子弹伤害
#define PLAYER_ENEMY_CONTACT 40 //玩家和敌方碰撞的伤害
#define ENEMY_BULLET_DAMAGE 20 //敌方子弹伤害
#define PLAYER_BULLET_DAMAGE 20 //普通子弹伤害
#define BOMB_DAMAGE 40 //炮弹伤害
#define LASER_DAMAGE 80 //激光伤害
#define NUCLEAR_WEAPON_DAMAGE 80 //核弹伤害
//伤害范围
#define BULLET_DAMAGE_RANGE 0 //子弹伤害范围
#define BOMB_DAMAGE_RANGE 10 //炮弹伤害范围
#define NUCLEAR_WEAPON_DAMAGE_RANGE 40 //核武器伤害范围
//技能CD 时间
#define FIRE_BULLET_CD 2 //发射子弹的CD时间
#define FIRE_BOMB_CD 15 //发射炮弹CD
#define SLIDE_CD 10 //滑步CD时间
#define ULTIMATE_CD 65 //终极武器冷却CD
//z-order 定义
#define TANK_Z_ORDER 4 //坦克z-order
#define BULLET_Z_ORDER 4 //炮弹 z-order
#define TREE_Z_ORDER 5 //树 z-order
#define PLAYER_NAME "player"//玩家名
//文件路径
<file_sep>#ifndef __SELECT_VIEW_H__
#define __SELECT_VIEW_H__
#include "cocos2d.h"
#include "GameScenes\ChapterController.h"
/*----------------------------------------------------------------------------------
*CLASS NAME£ºSelectView
*DESC: table for player to choose which chapter he(she) would to play.
------------------------------------------------------------------------------------*/
class SelectView
: public cocos2d::Layer
, public cocos2d::extension::TableViewDataSource
, public cocos2d::extension::TableViewDelegate
{
public:
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// a selector callback
void menuCloseCallback(cocos2d::Ref* pSender);
//
//pure virtual functions that need to be overrided
virtual void scrollViewDidScroll(cocos2d::extension::ScrollView* view) {};
virtual void scrollViewDidZoom(cocos2d::extension::ScrollView* view) {}
virtual void tableCellTouched(cocos2d::extension::TableView* table, cocos2d::extension::TableViewCell* cell);
virtual cocos2d::Size tableCellSizeForIndex(cocos2d::extension::TableView *table, ssize_t idx);
virtual cocos2d::extension::TableViewCell* tableCellAtIndex(cocos2d::extension::TableView *table, ssize_t idx);
virtual ssize_t numberOfCellsInTableView(cocos2d::extension::TableView *table);
// implement the "static create()" method manually
CREATE_FUNC(SelectView);
//get tableView point
cocos2d::extension::TableView* getTableView(){ return m_chapterTable; }
private:
//do not allowed to be accessed outside
SelectView();
~SelectView();
//member variables
int m_gateNum;
cocos2d::Size m_cellSize;
cocos2d::extension::TableView* m_chapterTable;
};
#endif // __SELECT_VIEW_H__<file_sep>#ifndef __PRELOADSCENE_SCENE_H__
#define __PRELOADSCENE_SCENE_H__
#include "cocos2d.h"
/*-----------------------------------------------------------------------------------
*CLASS NAME: £Ð£ò£å£ì£ï£á£ä£Ó£ã£å£î£å
*DESC: when this app is started,this scene be loaded to show the company logo ,in
the same time,pictures and musics etc. should be loaded into memory.
------------------------------------------------------------------------------------*/
class PreloadScene : public cocos2d::Layer
{
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
//jump to main page of the game
void jumpOut(float dt);
//preload files
void preloadFiles();
// implement the "static create()" method manually
CREATE_FUNC(PreloadScene);
};
#endif // __PRELOADSCENE_SCENE_H__<file_sep>#include "chapter1.h"
#include "../../GameHandleLib.h"
Chapter1::Chapter1()
{
//set chapter_no
m_chapterNo = 1;
}
Chapter1::~Chapter1()
{
}
bool Chapter1::init()
{
if (!BaseLayer::init())
return false;
//add your init code below...
m_map = CSLoader::createNode("tankWorldBg/tankWorldBg.csb");
if (m_map)
{
m_map->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT);
m_map->setPosition(Vec2(0, 0));
this->addChild(m_map);
m_map->setZOrder(0);
//设置层号 z-order
std::string nodeName = "roads";
auto roads = seekFromRootByName(m_map, nodeName);
roads->setZOrder(-1);
nodeName = "trees";
auto trees = seekFromRootByName(m_map, nodeName);
trees->setZOrder(5);
trees->setOpacity(245);
//障碍物添加刚体
nodeName = "houses";
auto housesNode = seekFromRootByName(m_map, nodeName);
auto houses = housesNode->getChildren();
for (auto& house : houses)
{
if (typeid(*house) == typeid(Sprite))
{
auto houseBody = PhysicsBody::createBox(house->getContentSize());
houseBody->setTag(MAP_BARRIAR_TAG);
houseBody->setDynamic(false);
houseBody->setContactTestBitmask(UNITIVE_MASK);
house->setPhysicsBody(houseBody);
}
}
//给湖泊添加刚体
nodeName = "pools";
auto poolNode = seekFromRootByName(m_map,nodeName);
auto pools = poolNode->getChildren();
for (auto& pool : pools)
{
if (typeid(*pool) == typeid(Sprite))
{
auto spriteScaleX = pool->getScaleX();
auto spriteScaleY = pool->getScaleY();
auto bodySize = cocos2d::Size(pool->getContentSize().width*spriteScaleX, pool->getContentSize().height*spriteScaleY);
auto poolBody = PhysicsBody::createBox(bodySize);
poolBody->setTag(MAP_POOL_TAG);
poolBody->setDynamic(false);
poolBody->setContactTestBitmask(POOL_MASK);
pool->setPhysicsBody(poolBody);
}
}
}
//添加玩家进入
this->initPlayer();
//添加机器人
m_AIManager.addRobot(Vec2(100, 100));
m_AIManager.addRobot(Vec2(200, 100));
m_AIManager.addRobot(Vec2(300, 100));
m_AIManager.addRobot(Vec2(400, 100));
return true;
}
<file_sep>#ifndef __AI_SYSTEM_H__
#define __AI_SYSTEM_H__
#include "cocos2d.h"
#include "..\Tank.h"
#include "..\GameResource.h"
/*-------------------------------------------------------------------------------------
*CLASS NAME: £Á£É£Ó£ù£ó£ô£å£í
£ªDESC£º controll all the robots in a scene, to add, to delete, and to set the robot where
it should be.
---------------------------------------------------------------------------------------*/
class AISystem
{
public:
AISystem(cocos2d::Layer* targetLayer);
~AISystem();
//set several tanks in visible horizons
//para: some points to set enemy tanks
void initTanksInScene(std::vector<Vec2> _positions);
//DESC: add robot into scene
//para: postion of the robot when added to the scene
void addRobot(Vec2 _pos);
//DESC::
//return: pointers of all the enemies
std::vector<EnemyTank*> getAllEnemies();
//DESC:
//return: true if remove succeed,or false if not
bool removeAllEnemies();
private:
std::vector<EnemyTank*> m_robots; //all the enemies
cocos2d::Layer* m_battleLand; //battle land
};
#endif //__AI_SYSTEM_H__<file_sep>#include "SelectView.h"
#include "..\GameHandleLib.h"
USING_NS_CC_EXT;
SelectView::SelectView()
:m_gateNum(0)
,m_cellSize(Size(0,0))
{
}
SelectView::~SelectView()
{
}
bool SelectView::init()
{
if (!Layer::init())
{
return false;
}
auto visibleSize = VisibleRect::getVisibleRect().size;
//caculate table cell size
m_cellSize = Size(visibleSize.width/5,visibleSize.height*3/5);
//add table to this view
m_chapterTable = TableView::create(this, Size(m_cellSize.width * 3, m_cellSize.height));
m_chapterTable->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
m_chapterTable->setDirection(extension::ScrollView::Direction::HORIZONTAL);
m_chapterTable->setPosition(VisibleRect::leftBottom());
m_chapterTable->setDelegate(this);
m_chapterTable->setZOrder(2);
this->addChild(m_chapterTable);
m_chapterTable->reloadData();
auto closeItem = MenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
CC_CALLBACK_1(SelectView::menuCloseCallback, this));
closeItem->setPosition(Vec2(visibleSize.width/2,visibleSize.height/10));
// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);
return true;
}
void SelectView::menuCloseCallback(cocos2d::Ref* pSender)
{
this->removeFromParentAndCleanup(true);
}
/*--------------------------------------------------------------------------*/
/*-------------------override methods of tableview--------------------------*/
/*--------------------------------------------------------------------------*/
void SelectView::tableCellTouched(TableView* table, TableViewCell* cell)
{
auto idx = cell->getIdx();
chapters[idx].callBack()->runThisChapter();
}
Size SelectView::tableCellSizeForIndex(TableView *table, ssize_t idx)
{
return m_cellSize;
}
TableViewCell* SelectView::tableCellAtIndex(TableView *table, ssize_t idx)
{
TableViewCell *cell = table->dequeueCell();
if (!cell) {
cell = new (std::nothrow) TableViewCell();
cell->autorelease();
auto sprite = Sprite::create(chapters[idx].chapterLookPath); //load background of each cell
sprite->setScaleX(this->getContentSize().width*m_cellSize.width/this->getContentSize().width);
sprite->setScaleY(this->getContentSize().height*m_cellSize.height/this->getContentSize().height);
sprite->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
sprite->setPosition(Vec2(0, 0));
cell->addChild(sprite);
auto label = Label::createWithSystemFont(chapters[idx].chapterName, "Helvetica", 20.0);
label->setPosition(Vec2::ZERO);
label->setAnchorPoint(Vec2::ZERO);
label->setTag(123);
cell->addChild(label);
}
else
{
auto label = (Label*)cell->getChildByTag(123);
label->setString(chapters[idx].chapterName);
}
return cell;
}
ssize_t SelectView::numberOfCellsInTableView(TableView *table)
{
// here the number need to be changed later
return getArrayLength(chapters);
}<file_sep>#include "BaseScene.h"
#include "extensions/cocos-ext.h"
#include "cocostudio/CocoStudio.h"
#include "../beforeGame/MainMenu.h"
/*---------------------------------------------------------------------------------*/
/*------------------------------class name:BaseLayer--------------------------------*/
/*---------------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------------*/
BaseLayer::BaseLayer()
:m_currentPlayer(nullptr)
,m_AIManager(this)
{
}
BaseLayer::~BaseLayer()
{
}
bool BaseLayer::init()
{
if (!Layer::init())
return false;
//add your init code below...
//set scene edge to limit the tank out of horizon
auto visibleSize = VisibleRect::getVisibleRect().size;
auto edge = Sprite::create();
auto edgeBox = PhysicsBody::createEdgeBox(visibleSize, PHYSICSSHAPE_MATERIAL_DEFAULT, 1);
edgeBox->setContactTestBitmask(UNITIVE_MASK);
edgeBox->setTag(EDGE_BOX_TAG);
edge->setPhysicsBody(edgeBox);
edge->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
edge->setPosition(visibleSize.width / 2, visibleSize.height / 2);
this->addChild(edge);
//set background music
this->m_isBgMusicRunning = true;
SimpleAudioEngine::getInstance()->playBackgroundMusic(LoadingMusicPath, true);
//set schudual to update button CD every seconds to check
schedule(CC_SCHEDULE_SELECTOR(BaseLayer::refreshButtonCD), 1.0f);
////设置CD更新函数
//m_currentPlayer->onAct = [&](PlayerTank::PlayerAction _act)
//{
//};
//-----------------------------------------------------------------
this->setContactListener();
//-----------------------------------------------------------------
return true;
}
void BaseLayer::turnOnBgMusic(Ref *pSender, Widget::TouchEventType _touchType)
{
if (_touchType == Widget::TouchEventType::ENDED)
{
if (this->m_isBgMusicRunning) //if it is running then turn off
{
SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
this->m_isBgMusicRunning = false;
}
else //turn on the music
{
this->m_isBgMusicRunning = true;
SimpleAudioEngine::getInstance()->playBackgroundMusic(LoadingMusicPath,true);
}
}
}
//pause
void BaseLayer::gamePause(Ref *pSender, Widget::TouchEventType _touchType)
{
//
Director::getInstance()->pause();
SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}
//
void BaseLayer::returnToMainScene(Ref *pSender, Widget::TouchEventType _touchType)
{
auto mainScene = MainMenu::createScene();
auto transScene = TransitionTurnOffTiles::create(1.0f, mainScene);
Director::getInstance()->replaceScene(transScene);
}
void BaseLayer::refreshButtonCD(float dt)
{
if (m_currentPlayer)
{
int* pCDArray;
int arrLen=0;
m_currentPlayer->getSkillCD(pCDArray,arrLen);
for (int i = 0; i < arrLen; i++)
{
if (pCDArray[i]>0)
pCDArray[i]--;
if (pCDArray[i] <= 0)
{
}
}
}
}
void BaseLayer::onMapMove(Vec2 _dir)
{
if (m_map)
{
}
}
void BaseLayer::initPlayer()
{
//set player
//warning: ensure you have init map first before call this method
m_currentPlayer = PlayerTank::create(tankImgPath);
if (m_currentPlayer)
{
m_currentPlayer->setPosition(VisibleRect::center());
m_currentPlayer->getPhysicsBody()->setTag(PLAYER_TAG);
m_currentPlayer->setZOrder(TANK_Z_ORDER);
if (m_map != nullptr) //地图初始化完成后,将坦克放到地图上
{
m_map->addChild(m_currentPlayer);
}
//将地图滚动和坦克移动关联起来
m_currentPlayer->onMapMove = CC_CALLBACK_1(BaseLayer::onMapMove, this);
//玩家初始化完成之后,关联按钮事件
this->setButtonListener();
}
}
void BaseLayer::setButtonListener()
{
auto visibleSize = VisibleRect::getVisibleRect().size;
//load controller
auto controllerImg = CSLoader::createNode(PlayerControllerPath);
if (controllerImg!=nullptr)//防御性,保证按钮文件加载成功后,执行后续操作
{
controllerImg->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
controllerImg->setPosition(VisibleRect::center());
this->addChild(controllerImg);
//设置操纵按钮大小
auto conSize = controllerImg->getContentSize();
controllerImg->setScaleX(visibleSize.width / conSize.width);
controllerImg->setScaleY(visibleSize.height / conSize.height);
if (m_currentPlayer != nullptr) //防御性,保证坦克初始化成功后,开始关联按钮响应事件
{
//set move action of button
std::string buttonName = "Btn_up";
auto upBtn = seekFromRootByName(controllerImg, buttonName);
static_cast<Button*>(upBtn)->addTouchEventListener(CC_CALLBACK_2(PlayerTank::move, m_currentPlayer, FTank::TankDirect::TD_UP));
buttonName = "Btn_right";
auto rightBtn = seekFromRootByName(controllerImg, buttonName);
static_cast<Button*>(rightBtn)->addTouchEventListener(CC_CALLBACK_2(PlayerTank::move, m_currentPlayer, FTank::TankDirect::TD_RIGHT));
buttonName = "Btn_down";
auto downBtn = seekFromRootByName(controllerImg, buttonName);
static_cast<Button*>(downBtn)->addTouchEventListener(CC_CALLBACK_2(PlayerTank::move, m_currentPlayer, FTank::TankDirect::TD_DOWN));
buttonName = "Btn_left";
auto leftBtn = seekFromRootByName(controllerImg, buttonName);
static_cast<Button*>(leftBtn)->addTouchEventListener(CC_CALLBACK_2(PlayerTank::move, m_currentPlayer, FTank::TankDirect::TD_LEFT));
//attack action
buttonName = "Btn_bullet";
auto bulletBtn = seekFromRootByName(controllerImg, buttonName);
static_cast<Button*>(bulletBtn)->addTouchEventListener(CC_CALLBACK_2(PlayerTank::act, m_currentPlayer, PlayerTank::PlayerAction::PA_FIRE_BULLET));
buttonName = "Btn_bomb";
auto bombBtn = seekFromRootByName(controllerImg, buttonName);
static_cast<Button*>(bombBtn)->addTouchEventListener(CC_CALLBACK_2(PlayerTank::act, m_currentPlayer, PlayerTank::PlayerAction::PA_FIRE_BOMB));
buttonName = "Btn_slide";
auto slideBtn = seekFromRootByName(controllerImg, buttonName);
static_cast<Button*>(slideBtn)->addTouchEventListener(CC_CALLBACK_2(PlayerTank::act, m_currentPlayer, PlayerTank::PlayerAction::PA_SLIDE));
buttonName = "Btn_ultimate";
auto ultimateBtn = seekFromRootByName(controllerImg, buttonName);
static_cast<Button*>(ultimateBtn)->addTouchEventListener(CC_CALLBACK_2(PlayerTank::act, m_currentPlayer, PlayerTank::PlayerAction::PA_ULTIMATE));
//music and quit
buttonName = "Btn_quit";
auto quitBtn = seekFromRootByName(controllerImg, buttonName);
static_cast<Button*>(quitBtn)->addTouchEventListener(CC_CALLBACK_2(BaseLayer::returnToMainScene, this));
buttonName = "Btn_music";
auto musicBtn = seekFromRootByName(controllerImg, buttonName);
static_cast<Button*>(musicBtn)->addTouchEventListener(CC_CALLBACK_2(BaseLayer::turnOnBgMusic, this));
}
}
}
void BaseLayer::setContactListener()
{
//set contack listener
auto contactListener = EventListenerPhysicsContact::create();
contactListener->onContactBegin = CC_CALLBACK_1(BaseLayer::contactListen, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this);
}
bool BaseLayer::contactListen(const PhysicsContact& contact)
{
auto tagA = contact.getShapeA()->getBody()->getTag();
auto tagB = contact.getShapeB()->getBody()->getTag();
auto spriteA = contact.getShapeA()->getBody()->getNode();
auto spriteB = contact.getShapeB()->getBody()->getNode();
//子弹移除,匿名函数
auto removeBullet = [&](Node* &bulletNode)
{
try
{
if (typeid(*bulletNode) == typeid(NuclearWeapon))
{
static_cast<NuclearWeapon*>(bulletNode)->explode();
}
else if (typeid(*bulletNode) == typeid(Bullet))
{
static_cast<Bullet*>(bulletNode)->explode();
}
else if (typeid(*bulletNode) == typeid(Bomb))
{
static_cast<Bomb*>(bulletNode)->explode();
}
}
catch (...)
{
//发生错误后,鸵鸟一下,我什么都没看见~~~~
}
};
if (tagA == PLAYER_TAG || tagB == PLAYER_TAG) //若碰撞中有玩家
{
if (tagA == PLAYER_TAG && tagB == ENEMY_TAG) //玩家和地方相碰 玩家掉血
{
static_cast<PlayerTank*>(spriteA)->beAttacked(PLAYER_ENEMY_CONTACT);
}
else if (tagA == ENEMY_TAG &&tagB == PLAYER_TAG)//玩家和地方相碰 玩家掉血
{
static_cast<PlayerTank*>(spriteB)->beAttacked(PLAYER_ENEMY_CONTACT);
}
else if (tagA == PLAYER_TAG && tagB == ENEMY_BULLET_TAG)//玩家和敌方子弹相碰
{
static_cast<PlayerTank*>(spriteA)->beAttacked(ENEMY_BULLET_DAMAGE);
removeBullet(spriteB);
}
else if (tagA == ENEMY_BULLET_TAG && tagB == PLAYER_TAG)//玩家和敌方子弹相碰
{
static_cast<PlayerTank*>(spriteB)->beAttacked(ENEMY_BULLET_DAMAGE);
removeBullet(spriteA);
}
}
else if (tagA == ENEMY_TAG || tagB == ENEMY_TAG)//子弹和敌方碰撞
{
if (tagA == PLAYER_BULLET_TAG || tagB == PLAYER_BULLET_TAG)
{
auto enemyNode = spriteA;
auto bulletNode = spriteB;
if (tagA == PLAYER_BULLET_TAG)
{
enemyNode = spriteB;
bulletNode = spriteA;
}
auto enemy = static_cast<EnemyTank*>(enemyNode);
int damage = PLAYER_BULLET_DAMAGE;
if (typeid(*bulletNode) == typeid(Bomb))
damage = BOMB_DAMAGE;
else if (typeid(*bulletNode) == typeid(NuclearWeapon))
damage = NUCLEAR_WEAPON_DAMAGE;
enemy->beAttacked(damage);
removeBullet(bulletNode);
}
}
else if (tagA == MAP_BARRIAR_TAG || tagB == MAP_BARRIAR_TAG)//子弹与不可跨越障碍物
{
if (tagA == ENEMY_BULLET_TAG || tagA == PLAYER_BULLET_TAG
|| tagB == ENEMY_BULLET_TAG || tagB == PLAYER_BULLET_TAG)
{
auto barrialNode = spriteA;
auto bulletNode = spriteB;
if (tagA == ENEMY_BULLET_TAG || tagA == PLAYER_BULLET_TAG)
{
barrialNode = spriteB;
bulletNode = spriteA;
}
if (typeid(*bulletNode) == typeid(Bomb) || typeid(*bulletNode) == typeid(NuclearWeapon))
{
barrialNode->removeFromParentAndCleanup(true);
}
removeBullet(bulletNode);
}
}
else if (tagA == EDGE_BOX_TAG || tagB == EDGE_BOX_TAG) //子弹撞到边界之后将其移出
{
if (tagA == ENEMY_BULLET_TAG || tagA == PLAYER_BULLET_TAG)
{
removeBullet(spriteA);
}
if (tagB == ENEMY_BULLET_TAG || tagB == PLAYER_BULLET_TAG)
{
removeBullet(spriteB);
}
}
else if (tagA == ENEMY_BULLET_TAG || tagB == ENEMY_BULLET_TAG) //两个都是炮弹 都移除
{
if ((tagA == PLAYER_BULLET_TAG || tagB == PLAYER_BULLET_TAG)
|| (tagA == ENEMY_BULLET_TAG && tagB == ENEMY_BULLET_TAG)
|| (tagA == PLAYER_BULLET_TAG && tagB == PLAYER_BULLET_TAG))
{
removeBullet(spriteA);
removeBullet(spriteB);
}
}
return true;
}<file_sep># xiaofei
tankworld introduction:<br/>
this project is a game based on cocos2dx,let me show you how to use it<br/>
first fo all, you should build a enviroment of cocos2dx,you can download here: http://www.cocos2d-x.org/download
secondly,create a new cocos2dx project ,and then copy the folder which named Classes to override the defualt Classes folder.<br/>
thirdly,when you finish what I mentioned above,you can start this project,however, errors will occur when it runs.just take it easy,because you don't have the pictures and musics in the folder which named Resources. then you should look into the code to find the file path I designed.<br/>
中文介绍:<br/>
这个工程是采用的cocos2dx引擎,要安装这个工程且看下面我的介绍:<br/>
首先呢,使用前,你需要配置cocos2dx环境,你可以去这里下载cocos2dx,忘了说了,我现在工程采用的是cocos2dx 3.4版本。<br/>
然后,新建一个新的cocos2dx的项目,你需要复制我这里的Classes文件夹覆盖新项目生成后的默认的那个Classes文件夹。<br/>
接着呢,当你完成上述操作之后其实这个项目就是可以编译通过的呢,只是当你运行的时候就会发生错误,这个时候不要慌张,其实这只是因为你没有我的Resources文件夹导致的,这个时候你需要看代码中找我怎么通过路径调用文件的。<br/>
文件介绍:<br/>
游戏开始之前,有两个场景,<br/>
一:展示程序LOGO的场景,顺便在后台加载声音素材和游戏纹理----------->preloadScene.h<br/>
二:主菜单,用于用户选择开始游戏,游戏关卡,或者选择联系我们------->MainMenu.h<br/>
关卡选择菜单--------------------------------------------------->selectView.h<br/>
游戏中涉及到的:<br/>
坦克的实现--------------------------------------------------------->tank.h<br/>
子弹的实现--------------------------------------------------------->bullet.h<br/>
游戏场景基类,抽出每个关卡都存在的公共部分------------------------->BaseScene.h<br/>
游戏中AI机器坦克的管理--------------------------------------------->AISystem.h<br/>
三:
游戏数据处理会用到的库--------------------------------------------->GameHandleLib.h<br/>
游戏屏幕适配简单处理类--------------------------------------------->VisibleRect.h<br/>
游戏数据基础宏定义------------------------------------------------->baseDefine.h<br/>
关卡:<br/>
前面介绍了有一个BaseScene作为关卡场景的基类,基类中先实现场景通用的方法,在特定关卡中的初始化中添加额外的初始化代码,添加特有的方法,用这种方式实现扩展。<br/>
关卡之间是如何关联起来的: 当前只有一个关卡,关联起来使用的是一个关卡控制器:<br/>
typedef struct controller<br/>
{<br/>
const char* chapterName; //章节名称<br/>
const char* chapterLookPath; //章节预览图地址<br/>
function<BaseLayer*()> callBack; //章节调用器<br/>
}ChapterController;<br/>
static ChapterController chapters[] =<br/>
{<br/>
{ "protect princess-apartment of CUG", "pic/chapterTest.png", [](){return Chapter1::create(); } }<br/>
};<br/>
当你做好一个关卡后,按照这种方式添加到这个数组中即可。<br/>
<hr/>
<hr/>
if you have a better idea,please don't forget to tell me,and if you can continue my job to finish this game I would be very appreciated^_^<br/>
<file_sep>///////////////////////////////////////////////////////////////////////////////////
//
// 关卡一 : 中国地质大学站
// 任务 : 保卫公主楼
//
/////////////////////////////////////////////////////////////////////////////////////
#include "..\BaseScene.h"
class Chapter1 :public BaseLayer
{
public:
virtual bool init();
CREATE_FUNC(Chapter1);
RUN_THIS_CHAPTER(Chapter1);
protected:
Chapter1();
~Chapter1();
};
|
e72d1cf94605208bd0b31a55960980f7d87f9ccd
|
[
"Markdown",
"C",
"C++"
] | 18
|
C++
|
xiaofeige/battle-world
|
8db76e6182ab9639b118bb01361e3ed89111668c
|
5aa00467152231a8349e322e8a837ea14f8e0aa0
|
refs/heads/master
|
<file_sep>var FromSymbol = Symbol("from");
var ArgumentsSymbol = Symbol("arguments");
var UnmappedArgumentsSymbol = Symbol("unmappedArguments");
var BaseSymbol = Symbol("base");
var Apply = (Function.prototype.call).bind(Function.prototype.apply);
var Call = Function.prototype.call.bind(Function.prototype.call);
var ArrayConcat = Array.prototype.concat;
var ArraySlice = Array.prototype.slice;
function curry(aFunction, newArguments)
{
var syntacticChildren = Call(ArraySlice, arguments, 2);
var previousArguments = aFunction[UnmappedArgumentsSymbol] || { };
var syntacticChildren = Call(ArraySlice, arguments, 2);
var children = syntacticChildren.length ? syntacticChildren : newArguments && newArguments.children || previousArguments.children || [];
var currentArguments = Object.assign({ }, previousArguments, newArguments, { children: children });
var baseFunction = base(aFunction);
return Object.defineProperty(
Object.assign(function _(attributes)
{
var args = map(Object.assign({ }, currentArguments, attributes, arguments));
if (this instanceof _)
return new (baseFunction(args));
return baseFunction(args);
},
{
[BaseSymbol]: base(aFunction),
[ArgumentsSymbol]: map(currentArguments),
[UnmappedArgumentsSymbol]: currentArguments
}), "name", { value: baseFunction.name });
function map(args)
{
if (!Object.keys(args).some(key => args[key] && args[key][FromSymbol] !== undefined))
return args;
var adjusted = { };
for (var key of Object.keys(args))
adjusted[key] = exhaust(key, args);
return adjusted;
}
function exhaust(key, args)
{
var value = args[key];
if (value && value[FromSymbol] !== undefined)
return exhaust(value[FromSymbol], args);
return args[key];
}
}
function from(aKey)
{
return { [FromSymbol]: aKey };
}
module.exports.from = from;
module.exports.curry = curry;
module.exports.base = base;
module.exports.getArguments = getArguments;
function getArguments(aFunction)
{
return aFunction[ArgumentsSymbol] || { children:[] };
}
function base(aFunction)
{
return aFunction[BaseSymbol] || aFunction
};
<file_sep>var curry = "(require(\"generic-jsx\").curry)";
var insertion = require("babylon").parse(curry).program.body[0].expression;
var plugin = function plugin(options)
{
var types = options.types;
var visitor = require("babel-helper-builder-react-jsx")(
{
pre: function(state)
{
state.args.push(state.tagExpr);
state.callee = insertion;
}
});
return {
inherits: require("babel-plugin-syntax-jsx"),
visitor: visitor
};
}
module.exports = plugin;
<file_sep>
module.exports = displayTransform;
function displayTransform(aString)
{
var result = require("jsx-transform").fromString(aString, { factory: "React.createElement" });
var escapedResult = require("js-string-escape")(result);
return "<div id = \"code\">\
<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.12.0/codemirror.css\">\
<script src=\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.12.0/codemirror.js\"></script>\
<script src=\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.12.0/mode/javascript/javascript.js\"></script>\
<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.12.0/theme/neo.css\">\
<style type=\"text/css\">body{margin:0} .CodeMirror {font-size:15px; width: 100%,; height: 100%; margin:0}</style>\
<script type=\"text/javascript\">\
window.onload = function() {\
var myCodeMirror = CodeMirror(document.getElementById(\"code\"), {\
value: \"" + escapedResult + "\",\
mode: \"javascript\",\
theme: \"neo\",\
lineWrapping: true,\
lineNumbers: true\
});\
};\
</script>\
</div>"
}
|
52deff2a302a19fe9fd10d353eeaa3a61b420099
|
[
"JavaScript"
] | 3
|
JavaScript
|
Me1000/generic-jsx
|
de7b59b7fcc9acb4211862618e392fba25867778
|
f544ac9c115fc9931161529bec7ee344fbab2e2e
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
import unittest
from reverse_int import reverse_int
class UnitTests(unittest.TestCase):
def test_bad_data(self):
result = reverse_int("a")
self.assertEqual(result, '0')
def test_negative(self):
result = reverse_int(-123)
self.assertEqual(result, '-321')
def test_regular_number(self):
result = reverse_int(123)
self.assertEqual(result, '321')
def test_leading_zeros(self):
result = reverse_int(120)
self.assertEqual(result, '21')
def test_for_zero(self):
result = reverse_int(0)
self.assertEqual(result, '0')
if __name__ == "__main__":
unittest.main()
<file_sep>#!/usr/bin/env python
def reverse_int(num):
'''
Purpose: Reverse an integer passed as argument zero.
Arguments: Argument 0 contains an integer to reverse
Return values: Returns the reversed number or 0
'''
# Check to make sure argument zero contains an integer
if not num or type(num) != int:
return("0")
# Handle zero or a NULL value
elif num == 0:
return("0")
# Handles negative numbers
elif num < 0:
reverse = "-" + str(abs(num))[::-1]
return(reverse)
# Handles positive integers and numbers with leading zeros
elif num > 0:
return(str(num)[::-1].lstrip("0"))
def main():
pass
if __name__ == "__main__":
main()
<file_sep># Overview
Sample python code to reverse an integer.
# Program execution
The tests.py program will unit test the following inputs:
* Passing in bad data "a" will return 0
* Passing in 0 will return 0
* Passing in -123 will return -321
* Passing in 123 will return 321
* Passing in 120 will return 21
# Running the tests
You can use the following command to run the unit tests:
$ ./test.py
|
88a39136c1e43bda036ccb70904e661a976c9754
|
[
"Markdown",
"Python"
] | 3
|
Python
|
Matty9191/python_reverse_int
|
2ec19a6d8b0c74b8d3f4ced05b37bfdd138e70fe
|
d757f6b6371b40a81c27f08c1d5bc9d46872fb31
|
refs/heads/main
|
<repo_name>cristisava/playerGame<file_sep>/same but with classes/player.js
class Player {
constructor(box) {
this.box = box;
this.posY = 4;
this.posX = 4;
this.speed = 3;
this.inputX = 0;
this.inputY = 0;
}
getInputFromUser() {
document.onkeydown = detectKey;
const player = this;
function detectKey(e) {
e = e || window.event;
if (e.keyCode == "38" && player.checkBorders()) {
// up arrow
player.inputY = -1;
} else if (e.keyCode == "40" && player.checkBorders()) {
// down arrow
player.inputY = 1;
} else if (e.keyCode == "37" && player.checkBorders()) {
// left arrow
player.inputX = -1;
} else if (e.keyCode == "39" && player.checkBorders()) {
// right arrow
player.inputX = 1;
}
player.playerMovement();
player.inputX = 0;
player.inputY = 0;
}
}
playerMovement(){
this.posY = this.posY + this.speed * this.inputY;
this.posX = this.posX + this.speed * this.inputX;
this.box.style.marginTop = this.posY + "px";
this.box.style.marginLeft = this.posX + "px";
}
checkBorders() {
if(this.posY-this.speed < 0){
this.posY += 1;
return false;
}
if(this.posY+ this.speed > 380){
this.posY -= 1;
return false;
}
if(this.posX+ this.speed > 380){
this.posX -= 1;
return false;
}
if(this.posX - this.speed < 0){
this.posX += 1;
return false;
}
return true;
}
}
let playerContainer = document.getElementById('player');
let newPlayer = new Player(playerContainer);
newPlayer.getInputFromUser();
|
e6eca703aaf4f6b6ac8a10bf9a63b09cb4f2bb19
|
[
"JavaScript"
] | 1
|
JavaScript
|
cristisava/playerGame
|
ac28689357aadd6ca10fccf6b6daae5a6df9bcb1
|
abaeb69b984e3b537df88dda63127531417b3fc2
|
refs/heads/master
|
<repo_name>natzelo/Weatherize<file_sep>/index.js
const iconUrl =
"https://gist.githubusercontent.com/tbranyen/62d974681dea8ee0caa1/raw/3405bfb2a76b7cbd90fde33d8536f0cd13706955/icons.json";
$.getJSON(iconUrl, (weatherIcons) => {
//Geolocation
navigator.geolocation.getCurrentPosition((pos) => {
const loc_url = `https://api.openweathermap.org/data/2.5/weather?lat=${pos.coords.latitude}&lon=${pos.coords.longitude}&appid=cb9a585ba3b63c09473b324d336c5701&units=metric`;
$.getJSON(loc_url, (response) => {
update(response,weatherIcons);
});
});
// Click listenser
$(".search-btn").click(() => {
handler(weatherIcons);
});
//Enter key listener
$(document).keypress((e) => {
if(e.key === "Enter") {
handler(weatherIcons);
}
})
});
const handler = (weatherIcons) => {
const query = $(".search-box").val();
const url =
"https://api.openweathermap.org/data/2.5/weather?q=" +
query +
"&appid=cb9a585ba3b63c09473b324d336c5701&units=metric";
$.getJSON(url, (response) => {
update(response, weatherIcons);
});
}
const update = (response,weatherIcons) => {
$("#curr-temp").text(response.main.temp);
$("#low-temp").text(response.main.temp_min);
$("#high-temp").text(response.main.temp_max);
$(".summary").text(response.weather[0].description);
$("#wind-speed").text(response.wind.speed);
$("#wind-direc").text(response.wind.deg);
$("#humid").text(response.main.humidity);
$("#feel").text(response.main.feels_like);
$("#pressure").text(response.main.pressure);
$("#cloud").text(response.clouds.all);
$('#name').text(response.name);
$('#country').text(response.sys.country);
var prefix = "wi wi-";
var code = response.weather[0].id;
var icon = weatherIcons[code].icon;
// If we are not in the ranges mentioned above, add a day/night prefix.
// if (!(code > 699 && code < 800) && !(code > 899 && code < 1000)) {
// icon = 'day-' + icon;
// }
var today = new Date();
var hour = today.getHours();
if (hour > 6 && hour < 19) {
//Day time
if (code === 800) {
icon = "day-sunny";
} else {
icon = "day-" + icon;
}
} else {
//Night time
if (code === 800) {
icon = "night-clear";
} else {
icon = "night-" + icon;
}
}
// Finally tack on the prefix.
icon = prefix + icon;
$(".graphic i").removeClass();
$(".graphic i").addClass(icon);
};
<file_sep>/README.md
# Weatherize
Minimalistic weather app based on Open Weather API
|
701a82971e97c8c6efb11d6ffdca5b451495c5e2
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
natzelo/Weatherize
|
631d362140fd7c0dbbc1c34ca870c492f062bc04
|
cf30c51aa8d67280e2ff831f3e324b33ec9885c6
|
refs/heads/master
|
<repo_name>Lux652/EJ-web_2.0<file_sep>/dist/js/script.js
AOS.init({});
const navSlide = () =>{
const burger = document.querySelector('.burger');
const nav = document.querySelector('.mobile-menu');
burger.addEventListener('click',()=>{
nav.classList.toggle('active');
burger.classList.toggle('toggle');
document.body.classList.toggle('noscroll');
})
}
const klik = () => {
const contactPage = document.getElementById('contact_section')
contactPage.scrollIntoView({ behavior: 'smooth'});
};
navSlide();<file_sep>/README.md
# EJ-web_2.0
Enio Jergović website
|
a9ee04ec40a7e990d185a90f9984ec4bccd748b9
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
Lux652/EJ-web_2.0
|
fb8326d0c07def06f1276f4c2be41b78692ae147
|
2e60a63ef49093701fd405bddf8ecb5e03ccc92e
|
refs/heads/master
|
<repo_name>romaricp/bs<file_sep>/src/scripts/menu.js
$('.burger').click(function() {
$(this).toggleClass('open');
$('.mobmenu').toggleClass('open');
$('body').toggleClass('stop-scrolling');
/*
if ($('body').hasClass()) {}
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
*/
//$('body').bind('touchmove', function(e){e.preventDefault()});
//$('body').unbind('touchmove');
});
<file_sep>/src/header.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bonjour Solene</title>
<link rel="stylesheet" href="<?php echo get_site_url(); ?>/wp-content/themes/bs/styles/main.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css?family=Indie+Flower|Lora:400i" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Nunito+Sans:300,900" rel="stylesheet">
<?php wp_head(); ?>
</head>
<body>
<file_sep>/src/gallery.php
<?php
/*
Template Name: Gallery
*/
get_header(); ?>
<header class="header">
<div class="navbar row">
<h2 class="col-md-4 col-lg-3"><a href="<?php echo get_site_url(); ?>"> <span class="bold">Solène </span><span> Louvrier </span> </a></h2>
<div class=" col-lg-6 col-md-7">
<div class="breadcrumb">
<h1> <?php echo get_the_title(); ?> </h1>
<ul>
<?php $projects = array('post_type' => 'project', 'category_name'=>get_query_var('pagename'));
foreach (query_posts($projects) as $project) { ?>
<li> <a href="#<?php echo get_field('ancre', $project->ID); ?>"> <?php echo $project->post_title; ?> </a> </li>
<?php } ?>
</ul>
</div>
</div>
<div class="burger pull-right">
<span> </span>
</div>
</div>
<?php include_once( 'menu.php' ); ?>
</header>
<div class="content">
<?php
foreach (query_posts($projects) as $project) { ?>
<div class="project" id="<?php echo get_field('ancre', $project->ID); ?>">
<div class="container">
<h2 class="h1"><?php echo $project->post_title; ?></h2>
<h3 class="desc"><?php echo get_field('base_line', $project->ID); ?></h3>
<p class="info"><?php echo get_field('agence', $project->ID); ?> - <?php echo get_field('mise_en_ligne', $project->ID); ?></p>
<?php if (get_field('url', $project->ID) != null) { ?>
<a href="http://<?php echo get_field('url', $project->ID); ?>" class="link" target="_blank"> <?php echo get_field('url_libelle', $project->ID); ?></a>
<?php } ?>
</div>
<div class="container-fluid">
<div class="row gallery">
<div class="container-gallery col-xl-6 col-md-9 col-sm-12" style="background-color: <?php echo get_field('color1', $project->ID); ?>">
<div>
<div class="col-md-4 col-sm-4">
<!--logo-->
<img src="<?php echo get_field('logo', $project->ID)['url'] ?>" alt="" class="img-responsive">
</div>
<div class="col-md-8 col-sm-8">
<!--img large 1-->
<img src="<?php echo get_field('image_1', $project->ID)['url'] ?>" alt="" class="img-responsive">
</div>
</div>
</div>
<div class="col-xl-2 col-md-3 col-sm-6 hidden-sm hidden-xs">
<div class="col-lg-12" style="background-color: <?php echo get_field('color2', $project->ID); ?>">
<!-- img 2 hidden-sm hidden-xs -->
<img src="<?php echo get_field('image_2', $project->ID)['url'] ?>" alt="" class="img-responsive">
</div>
</div>
<div class="col-xl-2 col-md-3 col-sm-6 col-xs-12">
<div class="col-lg-12">
<!-- img 3 -->
<img src="<?php echo get_field('image_3', $project->ID)['url'] ?>" alt="" class="img-responsive">
</div>
</div>
<div class="col-xl-2 visible-xl">
<div class="col-lg-12">
<!-- illustration visible-xl-->
<img src="<?php echo get_field('illustration_1', $project->ID)['url'] ?>" alt="" class="img-responsive">
</div>
</div>
<div class="col-sm-6 visible-sm visible-xs col-xs-12">
<div class="col-lg-12">
<!-- img 4 visible-sm visible-xs -->
<img src="<?php echo get_field('image_4', $project->ID)['url'] ?>" alt="" class="img-responsive">
</div>
</div>
<div class="container-gallery col-xl-4 col-md-6 col-sm-12">
<div style="background-color: <?php echo get_field('color2', $project->ID); ?>" class="bg-pink">
<div class="col-sm-push-6 col-sm-6 col-xs-12">
<div class="tips ">
<?php echo get_field('liste', $project->ID); ?>
</div>
</div>
<div class="col-sm-pull-6 col-sm-6 col-xs-12">
<!-- img 5 texte-->
<img src="<?php echo get_field('image_5', $project->ID)['url'] ?>" alt="" class="img-responsive">
</div>
</div>
</div>
<div class="col-xl-2 col-md-3 col-sm-6 hidden-xs hidden-sm">
<div class="col-lg-12">
<!-- img 4 hidden-sm hidden-xs -->
<img src="<?php echo get_field('image_4bis', $project->ID)['url'] ?>" alt="" class="img-responsive">
</div>
</div>
<div class="col-xl-2 visible-xl">
<div class="col-lg-12">
<!-- illustration 2 visible-xl-->
<img src="<?php echo get_field('illustration_2', $project->ID)['url'] ?>" alt="" class="img-responsive">
</div>
</div>
</div>
</div>
</div>
<?php } ?>
<div class="container">
<div class="nav-project">
<div class="prev col-xs-6">
<?php
//echo get_the_ID(); exit;
//$pages_includes = array_diff([9, 11, 12], [get_the_ID()]);
//echo implode($pages_includes, ','); exit;
//var_dump($pages_includes); exit;
$pages = get_pages(array(
'sort_order' => 'desc',
'echo' => 0,
'exclude' => '4,17,7,15,'.get_the_ID()
));
?>
<h3><a href="<?php echo get_page_link($pages[0]->ID); ?>"><?php echo $pages[0]->post_title; ?></a></h3>
</div>
<div class="next col-xs-6">
<h3><a href="<?php echo get_page_link($pages[1]->ID); ?>"><?php echo $pages[1]->post_title; ?></a></h3>
</div>
</div>
</div>
</div>
<?php include_once( 'copyright.php' ); ?>
<?php get_footer(); ?><file_sep>/src/copyright.php
<footer class="footer">
<p>© 2017 <NAME> // <a href="mailto:<EMAIL>"> Contact : <EMAIL> </a> // <a href="<?php echo get_site_url(); ?>/cv-solene-2017-web.pdf" target="_blank"> Télécharger CV </a> </p>
</footer><file_sep>/gulpfile.js
var gulp = require('gulp');
var sass = require('gulp-sass');
var inject = require('gulp-inject');
var wiredep = require('wiredep').stream;
var del = require('del');
var mainBowerFiles = require('main-bower-files');
var filter = require('gulp-filter');
var concat = require('gulp-concat');
var csso = require('gulp-csso');
var uglify = require('gulp-uglify');
var bower = './bower_components';
gulp.task('clean', function(cb){
del(['dist'], cb);
});
gulp.task('php', function(){
return gulp.src('src/*.php')
.pipe(gulp.dest('dist/wp-content/themes/bs'));
});
gulp.task('css', function(){
return gulp.src('src/*.css')
.pipe(gulp.dest('dist/wp-content/themes/bs'));
});
gulp.task('styles', function(){
var injectAppFiles = gulp.src('src/styles/*.scss', {read: false});
var injectGlobalFiles = gulp.src('src/global/*.scss', {read: false});
function transformFilepath(filepath) {
return '@import "' + filepath + '";';
}
var injectAppOptions = {
transform: transformFilepath,
starttag: '// inject:app',
endtag: '// endinject',
addRootSlash: false
};
var injectGlobalOptions = {
transform: transformFilepath,
starttag: '// inject:global',
endtag: '// endinject',
addRootSlash: false
};
return gulp.src('src/main.scss')
.pipe(wiredep())
.pipe(inject(injectGlobalFiles, injectGlobalOptions))
.pipe(inject(injectAppFiles, injectAppOptions))
.pipe(sass())
.pipe(csso())
.pipe(gulp.dest('dist/wp-content/themes/bs/styles'));
});
gulp.task('scripts', function() {
return gulp.src([bower + '/jquery/dist/jquery.js', bower + '/bootstrap-sass/assets/javascripts/bootstrap.js','./src/scripts/*.js'])
.pipe(concat('main.js'))
.pipe(uglify())
.pipe(gulp.dest('dist/wp-content/themes/bs/scripts'));
});
gulp.task('default', ['styles', 'scripts', 'php', 'css'], function(){
var injectFilesCss = gulp.src(['dist/wp-content/themes/bs/styles/main.css']);
var injectFilesJs = gulp.src(['dist/wp-content/themes/bs/scripts/main.js']);
var injectOptions = {
addRootSlash: false,
ignorePath: ['src', 'dist']
};
return gulp.src('src/*.php')
//.pipe(inject(injectFilesCss, injectOptions))
//.pipe(inject(injectFilesJs, injectOptions))
.pipe(gulp.dest('dist/wp-content/themes/bs'));
});
gulp.task('watch', function(){
gulp.watch('src/*', ['default']);
gulp.watch('src/styles/*', ['default']);
gulp.watch('src/scripts/*', ['default']);
gulp.watch('src/global/*', ['default']);
})<file_sep>/src/index.php
<?php
/*
Template Name: Accueil
*/
get_header(); ?>
<div class="home">
<header class="header">
<div class="navbar row">
<h2 class="col-md-4 col-lg-3"><a href="<?php echo get_site_url(); ?>"> <span class="bold">Solène </span><span> Louvrier </span> </a></h2>
<div class="burger pull-right">
<span> </span>
</div>
</div>
<?php include_once( 'menu.php' ); ?>
</header>
<div class="content container">
<h1><a href="<?php echo get_page_link(9); ?>">Webdesign,</a> <a href="<?php echo get_page_link(11); ?>">Design mobile,</a> <br> <a href="<?php echo get_page_link(13); ?>">Intégration</a> </h1>
</div>
</div>
<?php get_footer(); ?>
|
e4433ff1dac2a0354b014852904b6266e1027495
|
[
"JavaScript",
"PHP"
] | 6
|
JavaScript
|
romaricp/bs
|
c9bd8cbcab0ebfb8260db39bb4f8d0c7b7b19d71
|
0fc0f4f473854ce14a7e698182dbab2da0098cc2
|
refs/heads/master
|
<repo_name>carloalberty/form<file_sep>/registro-usuario.php
<?php
error_reporting( ~E_NOTICE );
require_once 'config.php';
if(isset($_POST['btnsave']))
{
$username = $_POST['user_name'];
$userjob = $_POST['user_job'];
$userciudad = $_POST['user_ciudad'];
$userphone = $_POST['user_phone'];
$useremail = $_POST['user_email'];
$formpass = $_POST['user_pass'];
$hash=password_hash($formpass, PASSWORD_BCRYPT);
$fecha=date("Y-m-d H:i:s");
//$salt = '<PASSWORD>';
//$password_hash = hash('sha256', $salt . hash('sha256', $userPass . $salt));
//$hashed_password = password_hash($_POST["userPass"],PASSWORD_DEFAULT);
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if(empty($username)){
$errMSG = "Debe Ingresar un nombre.";
}
else if(empty($userjob)){
$errMSG = "Por Favor Ingrese su Ocupacion.";
}
else if(empty($imgFile)){
$errMSG = "Debe Seleccionar una Imagen de Perfil.";
}
else
{
$upload_dir = 'user_images/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
// rename uploading image
$userpic = rand(1000000,10000000).".".$imgExt;
// allow valid image file formats
if(in_array($imgExt, $valid_extensions)){
// Check file size '5MB'
if($imgSize < 5000000) {
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else{
$errMSG = "Su Imagen Seleccionada es Muy Pesada.";
}
}
else{
$errMSG = "Disculpe.. JPG, JPEG, PNG & GIF son los Formatos Permitidos.";
}
}
// if no error occured, continue ....
if(!isset($errMSG)){
$stmt = $pdo->prepare('INSERT INTO tbl_users(userName,userProfession,userCiudad,userPhone,userEmail,userPass, created, userPic) VALUES(:uname, :ujob, :uciudad, :uphone, :uemail, :upass, :ucreated, :upic)');
$stmt->bindParam(':uname',$username);
$stmt->bindParam(':ujob',$userjob);
$stmt->bindParam(':uciudad',$userciudad);
$stmt->bindParam(':uphone',$userphone);
$stmt->bindParam(':uemail',$useremail);
$stmt->bindParam(':ucreated',$fecha);
$stmt->bindParam(':upass',$hash);
$stmt->bindParam(':upic',$userpic);
if($stmt->execute())
{
$successMSG = "Datos Ingresados Correctamente ...";
header("refresh:3; publicar.php"); // redirects image view page after 5 seconds.
}
else
{
$errMSG = "Ocurrio un error, Intente luego ....";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Jua" rel="stylesheet">
<link rel="shortcut icon" href="https://mdbootstrap.com/wp-content/themes/mdbootstrap4/favicon.ico" />
<link rel="stylesheet" href="../css/ezeiza.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" >
<!-- Minified JS library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Compiled and minified Bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
</head>
<body>
<div class="container">
<ul class="navigation">
<li class="inicio"><a href="../public/index.php">ezeizaweb</a></li>
<li><a href="publicar.php">publicar</a></li>
</ul>
<style>
.inicio a{
background-color: #304ffe;
color: #fff;
}
.ezeiza{
font-family: 'Jua', sans-serif;
font-size: 44px;
color: #ff3d00;
}
.control-label{
font-size: 1.6em;
font-family: "Zilla Slab","Open Sans",X-LocaleSpecific,sans-serif;
}
</style>
<div class="separa"></div>
<!-- menu-opciones-publicar -->
<div class="container-fluid">
<div class="row text-center">
<div class="container">
<div class="page-header">
<h1 class="h2">Crea perfil de usuario.</h1>
</div>
<?php
if(isset($errMSG)){
?>
<div class="alert alert-danger">
<span class="glyphicon glyphicon-info-sign"></span> <strong><?php echo $errMSG; ?></strong>
</div>
<?php
}
else if(isset($successMSG)){
?>
<div class="alert alert-success">
<strong><span class="glyphicon glyphicon-info-sign"></span> <?php echo $successMSG; ?></strong>
</div>
<?php
}
?>
<div style=" border: solid 1px #006D9C; align:left;">
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<table class="table table-bordered table-responsive">
<tr>
<td><label class="control-label">Nombre.</label></td>
<td><input class="form-control" type="text" name="user_name" placeholder="Ingrese Su Nombre" value="<?php echo $username; ?>" /></td>
</tr>
<tr>
<td><label class="control-label">Ocupacion.</label></td>
<td><input class="form-control" type="text" name="user_job" maxlength="15" placeholder="Ingrese Su Ocupacion" value="<?php echo $userjob; ?>" /></td>
</tr>
<tr>
<td><label class="control-label">Ciudad.</label></td>
<td><input class="form-control" type="text" name="user_ciudad" placeholder="Ingrese Su Ciudad" value="<?php echo $userciudad; ?>" /></td>
</tr>
<tr>
<td><label class="control-label">Telefono.</label></td>
<td><input class="form-control" type="text" name="user_phone" placeholder="Ingrese Su Telefono" value="<?php echo $userphone; ?>" /></td>
</tr>
<tr>
<td><label class="control-label">Email.</label></td>
<td><input class="form-control" type="text" name="user_email" placeholder="Ingrese Su Email" value="<?php echo $useremail; ?>" /></td>
</tr>
<tr>
<td><label class="control-label">Contraseña.</label></td>
<td><input class="form-control" type="password" name="user_pass" placeholder="In<PASSWORD> Su Contraseña" value="<?php echo $userpass; ?>" /></td>
</tr>
<input type="hidden" name="created" value="fecha">
<tr>
<td><label class="control-label">Imagen de Perfil.</label></td>
<td><input class="input-group" type="file" name="user_image" accept="image/*" /></td>
</tr>
<tr>
<td colspan="2"><button type="submit" name="btnsave" class="btn btn-default">
<span class="glyphicon glyphicon-save"></span> registrarse
</button>
</td>
</tr>
</table>
</form>
</div>
<div class="alert alert-info">
<strong>Al registrarse entendemos que acepta las </strong> <a href="../legales/terminos-condiciones-de-uso.php">condiciones de uso</a>!
</div>
</div>
<div class="aviso">
<hr>
<center> <h4>Recuerde que con su <strong><span style="color:red">Email y password</span></strong> tendra que ingresar nuevamente para completar su registro <br> por lo tanto mantenga sus datos de ingreso seguros.</h4></center>
</div>
<br><hr><br>
<?php
include "../public/includes/footer.php";
?>
</body>
</html><file_sep>/panel_user2.php
<?php
session_start();
if (isset($_SESSION['userEmail'])) {
$userEmail = $_SESSION['userEmail'];
}
else {
header('location: publicar.php');
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
<link type="text/css" rel="stylesheet" href="../css/materialize.css" media="screen,projection"/>
<link href="estilo-panel.css" type="text/css" rel="stylesheet" media="screen,projection"/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" >
<title>Panel de agente</title>
<style>
body {
width: 90%;
margin: 0 auto;
font-family: verdana;
font-size: 12px;
padding: 20px 30px 0 30px;
text-align: center;
}
h3 {
font-size: 2.92rem;
line-height: 110%;
margin: 1.9466666667rem 0 1.168rem 0;
}
table {
width: 100%;
display: table;
border-collapse: collapse;
border-spacing: 0;
border: none;
}
.container {
margin: 0 auto;
max-width: 1280px;
width: 96%;
}
.row {
margin-left: auto;
margin-right: auto;
margin-bottom: 20px;
}
.status-ok{
color: green;
}
.status{
color: red;
}
tr { border-bottom: 1px solid rgba(0, 0, 0, 0.12);}
tr {
display: table-row;
vertical-align: inherit;
border-color: inherit;
}
td, th {
padding: 15px 5px;
display: table-cell;
text-align: left;
vertical-align: middle;
border-radius: 2px;
font-size: 1.4em;
margin-left: 20px;
}
.page-footer{
width: 100%;
min-height: 130px;
margin-top:30%;
}
</style>
</head>
<body>
<div class="container">
<h3>panel de control</h3>
<div class="row">
<?php
$link = mysqli_connect("localhost", "root", "", "testdb");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM tbl_users WHERE userEmail='$userEmail'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
//new
//new
echo "<table>";
echo "<tr>";
echo "<th>NOMBRE</th>";
echo "<th>EMAIL</th>";
echo "<th>TELEFONO</th>";
echo "<th>CIUDAD</th>";
echo "<th>STATUS</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['userName'] . "</td>";
echo "<td>" . $row['userEmail'] . "</td>";
echo "<td>" . $row['userPhone'] . "</td>";
echo "<td>" . $row['userCiudad'] . "</td>";
echo "<td class='status-ok'>" . $row['userStatus'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
}
//new
//new
else{
echo "No se encontraron registros.";
}
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
</div>
</div>
<div class="row text-center">
<div class="col-md-4">
<a class="btn btn-info" href="modificar-datos.php?edit_id=<?php echo $_SESSION['userEmail']; ?>" title="click for edit">
<span class="glyphicon glyphicon-edit"></span> Publicar Aviso</a>
</div>
<div class="col-md-4">
<a class="btn btn-info" href="modificar-datos.php?edit_id=<?php echo $_SESSION['userEmail']; ?>" title="click for edit">
<span class="glyphicon glyphicon-edit"></span> Ver Publicados</a>
</div>
<div class="col-md-4">
<a class="btn btn-info" href="modificar-datos.php?edit_id=<?php echo $_SESSION['userEmail']; ?>" title="click for edit">
<span class="glyphicon glyphicon-edit"></span> Editar Perfil</a>
</div>
</div>
</div>
<footer class="page-footer">
<hr>
<div class="container">
<div class="row text-center">
<div class="col-md-12">
<a href="logout.php" class="btn btn-success btn-lg" role="button">SALIR</a>
</div>
</div>
</div>
<hr>
<div class="footer-copyright">
<div class="container">
<p>@copyright     Ezeizaweb</p>
</div>
</div>
</footer>
</body>
</html><file_sep>/checklogin.php
<?php
session_start();
?>
<?php
$host_db = "localhost";
$user_db = "root";
$pass_db = "";
$db_name = "testdb";
$tbl_name = "tbl_users";
$conexion = new mysqli($host_db, $user_db, $pass_db, $db_name);
if ($conexion->connect_error) {
die("La conexion falló: " . $conexion->connect_error);
}
$userEmail = $_POST['userEmail'];
$userPass = $_POST['userPass'];
$sql = "SELECT * FROM $tbl_name WHERE userEmail = '$userEmail'";
$result = $conexion->query($sql);
if ($result->num_rows > 0) {
}
$row = $result->fetch_array(MYSQLI_ASSOC);
if (password_verify($userPass, $row['userPass'])) {
$_SESSION['loggedin'] = true;
$_SESSION['userEmail'] = $userEmail;
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (5 * 60);
echo "Bienvenido! " . $_SESSION['userEmail'];
header("Location: panel_user2.php");
//echo "<br><br><a href='panel_user2.php'>Panel de Control</a>";
} else {
echo "Nombre o Contraseña estan incorrectos.";
echo "<br><a href='publicar.php'>Volver a Intentarlo</a>";
}
mysqli_close($conexion);
?><file_sep>/publicar.php
<?php
session_start();
require 'config.php';
//$hashed_password="<PASSWORD>";
if(isset($_POST['login'])) {
$errMsg = '';
// Get data from FORM
$userEmail = $_POST['userEmail'];
$userPass = $_POST['userPass'];
if($userEmail == '')
$errMsg = 'Ingrese un email';
//if($userPass == '')
if($userPass == '')
$errMsg = 'Ingrese contraseña';
if($errMsg == '') {
try {
$stmt = $pdo->prepare('SELECT userID, userName, userProfession, userCiudad, userPhone, userEmail, userPass, userPic FROM tbl_users WHERE userEmail = :userEmail');
$stmt->execute(array(
':userEmail' => $userEmail, ':userPass' =>$<PASSWORD>,));
$data = $stmt->fetch(PDO::FETCH_ASSOC);
if($data == false){
$errMsg = "Email o Contraseña incorrectos";
}
else {
if(password_verify($userPass, $data['userPass']))
{
$_SESSION['name'] = $data['userEmail'];
$_SESSION['userProfession'] = $data['userProfession'];
$_SESSION['userPass'] = $<PASSWORD>['<PASSWORD>'];
header('Location: panel_user2.php');
exit;
}
else
$errMsg = 'Password not match.';
}
}
catch(PDOException $e) {
$errMsg = $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Jua" rel="stylesheet">
<link rel="shortcut icon" href="https://mdbootstrap.com/wp-content/themes/mdbootstrap4/favicon.ico" />
<link rel="stylesheet" href="../css/ezeiza.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" >
<!-- Minified JS library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Compiled and minified Bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
</head>
<body>
<div class="container">
<ul class="navigation">
<li class="publicar"><a href="../public/index.php">ezeizaweb</a></li>
<li><a href="../contacto/contacto.php">Contacto</a></li>
</ul>
<style>
.publicar a{
background-color: #304ffe;
color: #fff;
}
.ezeiza{
font-family: 'Jua', sans-serif;
font-size: 44px;
color: #ff3d00;
}
.btn {
background-color: #4285f4;
}
.btn:hover {
background-color: #296CDB;
}
.btn:focus {
background-color: #0F52C1;
/* The outline parameter surpresses the border
color / outline when focused */
outline: 0;
}
.btn:active {
background-color: #0039A8;
}
</style>
<div class="separa"></div>
<!-- menu-opciones-publicar -->
<div class="container-fluid">
<div class="row text-center">
<hr>
<!-- formulario-login -->
<div class="col-md-6">
<h2>ingreso</h2>
<?php
if(isset($errMsg)){
echo '<div style="color:#FF0000;text-align:center;font-size:17px;">'.$errMsg.'</div>';
}
?>
<form action="checklogin.php" method="post" name="FormEntrar">
<div class="input-group input-group-lg">
<span class="input-group-addon" id="sizing-addon1"><i class="glyphicon glyphicon-envelope"></i></span>
<input type="email" class="form-control" name="userEmail" placeholder="email" id="email" aria-describedby="sizing-addon1" required>
</div>
<br>
<div class="input-group input-group-lg">
<span class="input-group-addon" id="sizing-addon1"><i class="glyphicon glyphicon-lock"></i></span>
<input type="<PASSWORD>" name="userPass" class="form-control" placeholder="<PASSWORD>" aria-describedby="sizing-addon1" required>
</div>
<br>
<button class="btn btn-lg btn-primary btn-block btn-signin" id="IngresoLog" type="submit">Ingrese a su Panel</button>
<br>
<div class="opcioncontra"><a href="">Olvidaste tu contraseña?</a></div>
</form>
</div>
<!--fin-formulario-login-->
<div class="col-md-6">
<br>
<h2>Nuevo Usuario</h2>
<h2><a href="../extras/registro-usuario.php" class="btn btn-info btn-lg btn-block active" role="button" aria-pressed="true"><span style="text-transform: uppercase">registrate aqui</span></a></h2>
<h3><span class="gratis">publica gratis</span>
<br><br>alquileres, empleos, servicios</h3>
</div>
<style>
.gratis{
font-family: 'Jua', sans-serif;
font-size: 1.3em;
font-weight: bolder;
color: red;
}
.control-label-new{
font-size: 1.3em;
font-family: verdana;
}
</style>
</div>
<hr>
</div>
<!-- fin-menu-opciones -->
<div class="row">
<?php
include "../public/includes/footer.php"
?>
</div>
</div>
</body>
</html><file_sep>/dashboard.php
<?php
session_start();
if (isset($_SESSION['userEmail'])) {
header('location: login1.php');
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Jua" rel="stylesheet">
<link rel="shortcut icon" href="https://mdbootstrap.com/wp-content/themes/mdbootstrap4/favicon.ico" />
<link rel="stylesheet" href="../css/ezeiza.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" >
<!-- Minified JS library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Compiled and minified Bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
</head>
<body>
<div class="container">
<ul class="navigation">
<li class="publicar"><a href="../public/index.php">ezeizaweb</a></li>
<li><a href="../contacto/contacto.php">Contacto</a></li>
</ul>
<style>
.publicar a{
}
.ezeiza{
font-family: 'Jua', sans-serif;
font-size: 44px;
color: #ff3d00;
}
</style>
<div class="separa"></div>
<!-- menu-opciones-publicar -->
<div class="container-fluid">
<div class="row text-center">
<body>
<h1>dashboard</h1>
<div align="center">
<div style=" border: solid 1px #006D9C; align:left;">
<?php
if(isset($errMsg)){
echo '<div style="color:#FF0000;text-align:center;font-size:17px;">'.$errMsg.'</div>';
}
?>
<div style="background-color:#006D9C; color:#FFFFFF; padding:10px;">Bienvenido <b><?php echo $_SESSION['name']; ?></b></div>
<div style="margin: 15px">
Zona privada de edicion <br>
</div>
</div>
</div>
<br>
<div class="col-sm-6 col-md-3">
<a href="perfil.php" class="btn btn-warning btn-lg btn-block active" role="button" aria-pressed="true">Tu Perfil</a>
</div>
<div class="col-sm-6 col-md-3">
<a href="publicar-aviso.php" class="btn btn-warning btn-lg btn-block active" role="button" aria-pressed="true">Publicar..!!</a>
</div>
<div class="col-sm-6 col-md-3">
<a href="modificar.php" class="btn btn-warning btn-lg btn-block active" role="button" aria-pressed="true">Modificar</a>
</div>
<div class="col-sm-6 col-md-3">
<a href="logout.php" class="btn btn-danger btn-lg btn-block active" role="button" aria-pressed="true">Cerrar Sesion</a>
</div>
</div>
</div>
<br>
<!--FOOTER-->
<br><br>
<div style="width: 100%; min-height: 120px;background-color: #181719;margin: 0;">
<div class="container-fluid">
<div class="footer">
<div class="row text-center">
<div class="col-md-4">
<h4><a href="">Sobre Nosotros</a></h4>
<h4><a href=""> Politica de Acuerdo</a></h4>
<h4><a href="../legales/terminos-condiciones-de-uso.php">Condiciones de uso</a></h4>
</div>
<div class="col-md-4">
</div>
<div class="col-md-4">
</div>
</div>
</div>
</div>
</div>
<!--FIN-FOOTER-->
</div>
</body>
</html><file_sep>/modificar-datos.php
<?php
session_start();
if (isset($_SESSION['userEmail'])) {
$userEmail = $_SESSION['userEmail'];
}
else {
header('location: publicar.php');
}
error_reporting( ~E_NOTICE );
require_once 'config.php';
if(isset($_GET['edit_id']) && !empty($_GET['edit_id']))
{
//$id = $_GET['edit_id'];
$id = $_SESSION['userEmail'];
$stmt_edit = $pdo->prepare('SELECT userName, userProfession, userPhone, userEmail, userPic FROM tbl_users WHERE userEmail =:uid');
$stmt_edit->execute(array(':uid'=>$id));
$edit_row = $stmt_edit->fetch(PDO::FETCH_ASSOC);
extract($edit_row);
}
else
{
header("Location: publicar.php");
}
if(isset($_POST['btn_save_updates']))
{
$username = $_POST['user_name'];
$userjob = $_POST['user_job'];
$userphone = $_POST['user_phone'];
$useremail = $_POST['user_email'];
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if($imgFile)
{
$upload_dir = 'user_images/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$userpic = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions))
{
if($imgSize < 5000000)
{
unlink($upload_dir.$edit_row['userPic']);
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else
{
$errMSG = "Sorry, your file is too large it should be less then 5MB";
}
}
else
{
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
else
{
// if no image selected the old image remain as it is.
$userpic = $edit_row['userPic']; // old image from database
}
// if no error occured, continue ....
if(!isset($errMSG))
{
$stmt = $pdo->prepare('UPDATE tbl_users
SET userName=:uname,
userProfession=:ujob,
userPhone=:uphone,
userEmail=:uid,
userPic=:upic
WHERE userEmail=:uid');
$stmt->bindParam(':uname',$username);
$stmt->bindParam(':ujob',$userjob);
$stmt->bindParam(':uphone',$userphone);
$stmt->bindParam(':uemail',$useremail);
$stmt->bindParam(':upic',$userpic);
$stmt->bindParam(':uid',$id);
if($stmt->execute()){
?>
<script>
alert('Successfully Updated ...');
window.location.href='panel_user2.php';
</script>
<?php
}
else{
$errMSG = "Sorry Data Could Not Updated !";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload, Insert, Update, Delete an Image using PHP MySQL - Coding Cage</title>
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="../crud/bootstrap/css/bootstrap-theme.min.css">
<!-- custom stylesheet -->
<link rel="stylesheet" href="style.css">
<!-- Latest compiled and minified JavaScript -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="jquery-1.11.3-jquery.min.js"></script>
</head>
<body>
<div class="contenedor">
<div class="navbar navbar-default navbar-static-top" role="navigation">
<div class="container">
<div class="navbar-header">
<h2>ezeizaweb</h2>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row text-center">
<div class="col-md-6">
<h2>ingreso usuario</h2>
<br><br>
<form method="post" enctype="multipart/form-data" class="form-horizontal">
<?php
if(isset($errMSG)){
?>
<div class="alert alert-danger">
<span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
</div>
<?php
}
?>
<table class="table table-bordered table-responsive">
<tr>
<td><label class="control-label">Nombre</label></td>
<td><input class="form-control" type="text" name="user_name" value="<?php echo $userName; ?>" required /></td>
</tr>
<tr>
<td><label class="control-label">Ocupacion</label></td>
<td><input class="form-control" type="text" name="user_job" value="<?php echo $userProfession; ?>" required /></td>
</tr>
<tr>
<td><label class="control-label">Telefono</label></td>
<td><input class="form-control" type="text" name="user_phone" value="<?php echo $userPhone; ?>" required /></td>
</tr>
<tr>
<td><label class="control-label">Email</label></td>
<td><input class="form-control" type="text" name="user_email" value="<?php echo $userEmail; ?>" required /></td>
</tr>
<tr>
<td><label class="control-label">Imagen de perfil</label></td>
<td>
<p><img src="user_images/<?php echo $userPic; ?>" height="150" width="150" /></p>
<input class="input-group" type="file" name="user_image" accept="image/*" />
</td>
</tr>
<tr>
<td colspan="2"><button type="submit" name="btn_save_updates" class="btn btn-default">
<span class="glyphicon glyphicon-save"></span> Modificar
</button>
</td>
<br>
<td>
<a class="btn btn-default" href="panel_user2.php"> <span class="glyphicon glyphicon-backward"></span> Cancelar </a>
</td>
</tr>
</table>
</form>
<br><br>
<div class="alert alert-info">
<strong>Al publicar entendemos que acepta las </strong> <a href="http://www.codingcage.com/2016/02/upload-insert-update-delete-image-using.html">Condiciones de uso</a>!
</div>
</div>
</div>
</div>
</div>
<style>
.contenedor{
width: 90%;
margin: o auto;
padding: 10px 10px 0 10px;
}
tr,td{
margin-top: 20px;
}
body{
font-family: verdana;
}
</style>
</body>
</html><file_sep>/publicar2.php
<?php
session_start();
// check whether the loginbtn was clicked
if (isset($_POST['login'])) {
include_once 'config.php';
// initialize variable
$userName = $_POST['userName'];
$userPass = $_POST['userPass'];
// error handlers
// check if inputs are empty
if (empty($userName) || empty($userPass)) {
$pdo = null;
header("Location: ../index.php?login=error_field");
exit();
} else {
// check if username is in database
$stmt = $pdo->prepare("SELECT userName FROM tbl_agentes WHERE = ?");
$stmt->execute([$userName]);
if ($stmt->rowCount() < 1) {
$pdo = null;
header("Location: ../index.php?login=error_username");
exit();
} else {
// check if password is correct
$stmt = $pdo->prepare("SELECT userPass FROM tbl_users WHERE userName = ?");
$stmt->execute([$userName]);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// dehashing the password
$hashedPwdCheck = password_verify($pwd, $result[0]['userPass']);
if ($hashedPwdCheck == false) {
$pdo = null;
header("Location: ../index.php?login=error_password");
exit();
} else {
// login the user in
$stmt = $pdo->prepare("SELECT userID, userName, userPhone, userEmail, userCiudad FROM tbl_users WHERE userName = ?");
$stmt->execute([$userName]);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$_SESSION['userID'] = $result[0]['userID'];
$_SESSION['userName'] = $result[0]['userName'];
$_SESSION['userPhone'] = $result[0]['userPhone'];
$_SESSION['userEmail'] = $result[0]['userEmail'];
$_SESSION['userCiudad'] = $result[0]['userCiudad'];
$pdo = null;
header("Location: ../updates.php?login=success");
exit();
}
}
}
} else {
header("Location: ../index.php?login=error");
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Jua" rel="stylesheet">
<link rel="shortcut icon" href="https://mdbootstrap.com/wp-content/themes/mdbootstrap4/favicon.ico" />
<link rel="stylesheet" href="../css/ezeiza.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" >
<!-- Minified JS library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Compiled and minified Bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
</head>
<body>
<div class="container">
<ul class="navigation">
<li class="publicar"><a href="../public/index.php">ezeizaweb</a></li>
<li><a href="../contacto/contacto.php">Contacto</a></li>
</ul>
<style>
.publicar a{
background-color: #304ffe;
color: #fff;
}
.ezeiza{
font-family: 'Jua', sans-serif;
font-size: 44px;
color: #ff3d00;
}
</style>
<div class="separa"></div>
<!-- menu-opciones-publicar -->
<div class="container-fluid">
<div class="row text-center">
<hr>
<!-- formulario-login -->
<div class="col-md-6">
<h2>ingreso</h2>
<?php
if(isset($errMsg)){
echo '<div style="color:#FF0000;text-align:center;font-size:17px;">'.$errMsg.'</div>';
}
?>
<form action"" method="post" enctype="multipart/form-data" class="form-horizontal">
<div style=" border: solid 2px #006D9C; " align="left">
<table class="table table-bordered table-responsive">
<tr>
<td><label class="control-label-new">email.</label></td>
<td><input class="form-control" type="text" name="userName" value="<?php if(isset($_POST['userName'])) echo $_POST['userName'] ?>" autocomplete="off" class="box"/></td>
</tr>
<tr>
<td><label class="control-label-new">contraseña</label></td>
<td><input class="form-control" type="password" name="userPass" value="<?php if(isset($_POST['userPass'])) echo $_POST['userPass'] ?>" autocomplete="off" class="box" /></td>
</tr>
<tr>
<td colspan="2"><input class="form-control" type="submit" name='login' value="Login" class='submit'/></td>
</tr></table>
</div>
</form>
</div>
<!--fin-formulario-login-->
<div class="col-md-6">
<br>
<h2>Nuevo Usuario</h2>
<h2><a href="../extras/registro-usuario.php" class="btn btn-info btn-lg btn-block active" role="button" aria-pressed="true"><span style="text-transform: uppercase">registrate aqui</span></a></h2>
<h3><span class="gratis">publica gratis</span>
<br><br>alquileres, empleos, servicios</h3>
</div>
<style>
.gratis{
font-family: 'Jua', sans-serif;
font-size: 1.3em;
font-weight: bolder;
color: red;
}
.control-label-new{
font-size: 1.3em;
font-family: verdana;
}
</style>
</div>
<hr>
</div>
<!-- fin-menu-opciones -->
<div class="row">
<?php
include "../public/includes/footer.php"
?>
</div>
</div>
</body>
</html><file_sep>/login.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Jua" rel="stylesheet">
<link rel="shortcut icon" href="https://mdbootstrap.com/wp-content/themes/mdbootstrap4/favicon.ico" />
<link rel="stylesheet" href="../css/ezeiza.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" >
<!-- Minified JS library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Compiled and minified Bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
</head>
<body>
<div class="container">
<ul class="navigation">
<li><a href="../public/index.php">Inicio</a></li>
<li><a href="../contacto/contacto.php">Contacto</a></li>
<li class="publicar"><a href="#">publicar</a></li>
</ul>
<style>
.publicar a{
background-color: #304ffe;
color: #fff;
}
.ezeiza{
font-family: 'Jua', sans-serif;
font-size: 44px;
color: #ff3d00;
}
</style>
<div class="separa"></div>
<!-- menu-opciones-publicar -->
<div class="container-fluid">
<div class="row text-center">
<!-- formulario-login -->
<div class="col-md-6">
<h2>ingreso usuario</h2>
<div class="ContentForm">
<form action="check-publicar.php" method="post" name="FormEntrar">
<div class="input-group input-group-lg">
<span class="input-group-addon" id="sizing-addon1"><i class="glyphicon glyphicon-envelope"></i></span>
<input type="email" class="form-control" name="email" placeholder="email" id="email" aria-describedby="sizing-addon1" required>
</div>
<br>
<div class="input-group input-group-lg">
<span class="input-group-addon" id="sizing-addon1"><i class="glyphicon glyphicon-lock"></i></span>
<input type="password" name="pass" class="form-control" placeholder="<PASSWORD>" aria-describedby="sizing-addon1" required>
</div>
<br>
<button class="btn btn-lg btn-primary btn-block btn-signin" id="IngresoLog" type="submit">Entrar</button>
<br>
<div class="opcioncontra"><a href="">Olvidaste tu contraseña?</a></div>
</form>
</div>
<!-- fin-formulario-login -->
</div>
<div class="col-md-6">
<br>
<hr>
<h3>Date de alta en <br><span class="ezeiza">ezeizaweb</span><br> y publica alquileres, empleos, etc.</h3>
<hr>
<a href="registro-usuario.php" class="btn btn-warning btn-lg btn-block active" role="button" aria-pressed="true">registrate</a>
</div>
</div>
<hr>
</div>
<!-- fin-menu-opciones -->
<div class="row">
<?php
include "../public/includes/footer.php"
?>
</div>
</div>
</body>
</html><file_sep>/login2.php
<?php
session_start();
require 'config.php';
if(isset($_POST['login'])) {
$errMsg = '';
// Get data from FORM
$userEmail = $_POST['userEmail'];
$userPass = $_POST['userPass'];
if($userEmail == '')
$errMsg = 'Ingrese un email';
if($userPass == '')
$errMsg = 'Ingrese contraseña';
if($errMsg == '') {
try {
$stmt = $pdo->prepare('SELECT userID, userName, userProfession, userCiudad, userPhone, userEmail, userPic FROM tbl_users WHERE userEmail = :userEmail AND userPass = :userPass');
$stmt->execute(array(
':userEmail' => $userEmail, ':userPass' =>$<PASSWORD>,));
$data = $stmt->fetch(PDO::FETCH_ASSOC);
if($data == false){
$errMsg = "Email o Contraseña incorrectos";
}
else {
if($userPas == $data['userPass']) {
$_SESSION['name'] = $data['userEmail'];
$_SESSION['userProfession'] = $data['userProfession'];
$_SESSION['userPass'] = $data['<PASSWORD>'];
header('Location: dashboard.php');
exit;
}
else
$errMsg = 'Password not match.';
}
}
catch(PDOException $e) {
$errMsg = $e->getMessage();
}
}
}
?>
<html>
<head><title>Login</title></head>
<style>
html, body {
margin: 1px;
border: 0;
}
</style>
<body>
<div align="center">
<div style=" border: solid 1px #006D9C; " align="left">
<?php
if(isset($errMsg)){
echo '<div style="color:#FF0000;text-align:center;font-size:17px;">'.$errMsg.'</div>';
}
?>
<div style="background-color:#006D9C; color:#FFFFFF; padding:10px;"><b>Login</b></div>
<div style="margin: 15px">
<form action="" method="post">
<label>email</label>
<input type="text" name="userEmail" value="<?php if(isset($_POST['userEmail'])) echo $_POST['userEmail'] ?>" autocomplete="off" class="box"/><br /><br />
<label>contraseña</label>
<input type="password" name="userPass" value="<?php if(isset($_POST['userPass'])) echo $_POST['userPass'] ?>" autocomplete="off" class="box" /><br/><br />
<input type="submit" name='login' value="Login" class='submit'/><br />
</form>
</div>
</div>
</div>
</body>
</html>
|
f1fd1eca94979511a73a10df0c1edf0bf1356e46
|
[
"PHP"
] | 9
|
PHP
|
carloalberty/form
|
535e632678b673ec08541f5071e30f7b65c42478
|
718f8cd5e91a0bd3d4f3d46e9298ba052e1e65ac
|
refs/heads/master
|
<repo_name>the-former-faith/ff-backend<file_sep>/schemas/mapDocument.js
import { FaMapMarkedAlt } from 'react-icons/fa'
import docMetadata from './docMetadata'
export default {
name: 'mapDocument',
title: 'Map',
type: 'document',
icon: FaMapMarkedAlt,
fields: [
...docMetadata,
{
name: 'center',
title: 'Map Center',
type: 'geopoint',
validation: Rule => Rule.required()
},
{
name: 'zoom',
title: 'Zoom Level',
type: 'number',
validation: Rule => Rule.required()
},
{
title: 'Marker Points',
name: 'points',
type: 'array',
of: [
{
type: 'reference',
to: [
{type: 'location'},
{type: 'event'},
]
}
]
},
],
fieldsets: [
{
name: 'metadata',
title: 'Metadata',
options: {
collapsible: true,
collapsed: true
}
}
],
initialValue: {
zoom: 12
},
preview: {
select: {
title: 'title.en',
media: 'mainImage.image'
}
}
}<file_sep>/schemas/newspaperArticleObject.js
export default {
name: 'newspaperArticleObject',
title: 'Newspaper Article',
type: 'object',
fields: [
{ name: 'embed',
type: 'reference',
to: [{type: 'newspaperArticle'}]
},
{ name: 'caption',
type: 'simpleBlockContent',
title: 'Caption'
}
],
preview: {
select: {
title: 'caption',
media: 'embed.file'
}
}
}<file_sep>/schemas/website.js
import { FaBookOpen } from 'react-icons/fa'
export default {
name: 'website',
title: 'Website',
icon: FaBookOpen,
type: 'document',
fields: [
{
name: 'title',
title: 'Title',
type: 'string',
},
],
preview: {
select: {
title: 'title',
},
}
}<file_sep>/schemas/event.js
import { FaRegCalendarAlt } from 'react-icons/fa'
import docMetadata from './docMetadata'
export default {
name: 'event',
title: 'Event',
icon: FaRegCalendarAlt,
type: 'document',
fields: [
...docMetadata,
{
name: 'date',
title: 'Date Began',
type: 'dateObject',
validation: Rule => Rule.required()
},
{
name: 'dateEnd',
title: 'Date Ended',
type: 'dateObject'
},
{
name: 'location',
title: 'Location',
type: 'reference',
to: {type: 'location'}
},
],
fieldsets: [
{
name: 'metadata',
title: 'Metadata',
options: {
collapsible: true,
collapsed: true
}
}
],
preview: {
select: {
title: 'title.en',
media: 'mainImage.file'
}
}
}<file_sep>/schemas/mapObject.js
export default {
name: 'mapObject',
title: 'Map',
type: 'object',
fields: [
{ name: 'embed',
type: 'reference',
to: [{type: 'mapDocument'}]
},
{ name: 'caption',
type: 'simpleBlockContent',
title: 'Caption'
}
],
preview: {
select: {
title: 'caption',
media: 'embed.mainImage.file'
}
}
}<file_sep>/schemas/localeStringArray.js
import {SUPPORTED_LANGUAGES} from './languages'
export default {
type: 'object',
name: 'localeStringArray',
fields: SUPPORTED_LANGUAGES.map(lang => ({
name: lang.id,
title: lang.title,
type: 'string',
type: 'array',
of: [{ type: 'string' }],
options: {
layout: 'tags'
}
}))
}<file_sep>/schemas/time.js
export default {
name: 'timeObject',
type: 'object',
title: 'Time',
options: {
columns: 3
},
fields: [
{
type: 'number',
name: 'hour',
title: 'Hour',
validation: Rule => Rule.positive().integer()
},
{
type: 'number',
name: 'minute',
title: 'Minute',
validation: Rule => Rule.positive().max(59).integer()
},
{
type: 'number',
name: 'second',
title: 'Second',
validation: Rule => Rule.positive().max(59).integer()
}
]
}<file_sep>/schemas/blockQuoteObject.js
import { FaQuoteLeft } from 'react-icons/fa'
export default {
name: 'blockQuoteObject',
title: 'Block Quote',
type: 'object',
icon: FaQuoteLeft,
fields: [
{
name: 'text',
type: 'simpleBlockContent',
title: 'Text',
},
{
name: 'source',
type: 'object',
fields: [
{
name: 'author',
title: 'Author',
type: 'reference',
to: [{type: 'person'}]
},
{
name: 'title',
type: 'string',
title: 'Quote Source Title'
},
{
name: 'url',
type: 'url',
title: 'Quote Source URL'
}
]
},
],
preview: {
select: {
title: 'text',
givenNames: 'source.author.givenNames.en',
familyName: 'source.author.familyName.en'
},
prepare(selection) {
const { title } = selection
const quoteText = (t = []) =>
t.map((x) =>
x.children
? x.children.map((y) => y.text)
: x);
const joinWithSpace = (t = []) => t.join(" ")
const joinedText = joinWithSpace(quoteText(title))
const parseGivenName = (x = { givenNames: [] }) =>
x.givenNames ? x.givenNames.join(" ") : "";
const parseFamilyName = (x) => x.familyName || "";
const combineNames = (x) => {
const givenName = parseGivenName(x);
const familyName = parseFamilyName(x);
return givenName && familyName ? `${givenName} ${familyName}` : familyName || givenName
};
const displayName = x => combineNames(x) || "Unattributed"
return {
title: joinedText,
subtitle: displayName(selection)
}
}
}
}<file_sep>/components/WikidataLookup/index.js
import React from 'react'
import AutoFill from '../AutoFill'
import {useToast} from '@sanity/ui'
import {withDocument} from 'part:@sanity/form-builder'
import WBK from 'wikibase-sdk'
import fetchWikiCommonsImage from './fetchWikiCommonsImage'
import slugify from './../../utils/slugify'
const wbk = WBK({
instance: 'https://www.wikidata.org',
sparqlEndpoint: 'https://query.wikidata.org/sparql'
})
const WikidataLookup = React.forwardRef((props, ref) => {
const toast = useToast()
//TODO double the options layers:
//There are some options unique to this WikiData field (possibly only instanceOf)
//and there are ones that all autofill components need (fields)
//TODO use this in the actual filter.
//I probably need to move the filter function here from Autocomplete field,
//and pass it as a prop
const instanceOf = 'Q5'
const fetchEnities = async(ids, props)=> {
const url = wbk.getEntities({
ids: ids,
languages: [ 'en' ],
props: props ? props : ''
})
const headers = { method: 'GET' }
const entities = await fetch( url, headers ).then( body => body.json() )
const simplifiedEntities = await wbk.simplify.entities(entities)
return await simplifiedEntities
}
const getLabels = async(ids) => {
if (!ids) return ['']
const entities = await fetchEnities(ids, ['labels'])
const entitiesArray = Object.values(entities)
const enitiesLabels = entitiesArray.map(x => {
return x.labels.en
})
return enitiesLabels
}
const fieldsToFill = async(entity) => {
const claims = entity.payload.claims
return {
'title.en': entity.payload.name,
'slug.en.current': slugify(entity.payload.name),
'mainImage._ref': entity.payload.imageId ? await fetchWikiCommonsImage(entity.payload.imageId) : undefined,
'shortDescription.en': entity.payload.description,
'familyName.en': (await getLabels(claims.P734)).join(' '),
'givenNames.en': await getLabels(claims.P735),
'date.time': claims.P569 ? claims.P569[0] : undefined,
'date.precision': claims.P569 ? 11 : undefined,
'date.isCirca': claims.P569 ? false : undefined,
'dateEnd.time': claims.P570 ? claims.P570[0] : undefined,
'dateEnd.precision': claims.P570 ? 9 : undefined,
'dateEnd.isCirca': claims.P570 ? false : undefined,
'wikipediaId': entity.payload.wikipediaId
}
}
const searchEnities = async(searchTerm, props)=> {
const url = wbk.searchEntities({
search: searchTerm,
language: [ 'en' ],
props: props ? props : ''
})
const headers = { method: 'GET' }
const entities = await fetch( url, headers ).then( body => body.json() )
if (entities.success === 1 ) {
return entities.search
}
//TODO add error catch if no results
}
const mapEntitiesWithClaims = async(x) => {
const ids = await x.map(i => i.id)
const entitiesWithClaims = await fetchEnities(ids, ['claims', 'sitelinks'])
const mappedEntities = (x, y) => x.map(i => {
return {
value: i.id,
payload: {
description: i.description,
name: i.label,
names: i.aliases ? [i.label, ...i.aliases] : [i.label],
imageUrl: y[i.id].claims.P18 ? `https://commons.wikimedia.org/w/thumb.php?width=100&f=${y[i.id].claims.P18[0].split(' ').join('_')}` : null,
imageId: y[i.id].claims.P18 ? y[i.id].claims.P18[0] : null,
wikipediaId: y[i.id].sitelinks.enwiki ? y[i.id].sitelinks.enwiki : undefined,
instanceOf: y[i.id].claims.P31 ? y[i.id].claims.P31[0] : null,
claims: y[i.id].claims
}
}
})
return await mappedEntities(x, entitiesWithClaims)
}
//I Can make this async instead of chaining.
const fetchEntriesFromSearchTerm = async(x) => {
const entriesFromSearchTerm = await searchEnities(x)
const mappedEntities = await mapEntitiesWithClaims(entriesFromSearchTerm)
return mappedEntities
}
return (
<AutoFill
fetchOptionsCallback={fetchEntriesFromSearchTerm}
fieldsToFill={fieldsToFill}
currentRef={ref}
{...props}
/>
)
})
export default withDocument(WikidataLookup)<file_sep>/schemas/organization.js
import { FaUserFriends } from 'react-icons/fa'
export default {
name: 'organization',
icon: FaUserFriends,
type: 'document',
fields: [
{
name: 'title',
title: 'Title',
type: 'localeString',
},
],
preview: {
select: {
title: 'title.en',
},
}
}<file_sep>/schemas/videoObject.js
export default {
name: 'videoObject',
type: 'object',
title: 'Video',
fields: [
{
name: 'embed',
title: 'Image File',
type: 'reference',
to: [
{ type: 'videoDoc' }
]
},
{
name: 'url',
title: 'External URL',
type: 'url',
},
{
name: 'caption',
type: 'simpleBlockContent',
title: 'Caption'
},
{
name: 'startTime',
type: 'timeObject',
title: 'Start Time',
},
{
name: 'endTime',
type: 'timeObject',
title: 'End Time',
},
],
preview: {
select: {
title: 'imageFile.title',
media: 'imageFile.image'
}
}
}<file_sep>/schemas/audioObject.js
export default {
name: 'audioObject',
type: 'object',
title: 'Audio',
fields: [
{
name: 'embed',
title: 'Audio File',
type: 'reference',
to: [
{ type: 'audioDoc' }
]
},
{
name: 'url',
title: 'External URL',
type: 'url',
},
{
name: 'caption',
type: 'simpleBlockContent',
title: 'Caption'
},
{
name: 'startTime',
type: 'timeObject',
title: 'Start Time',
},
{
name: 'endTime',
type: 'timeObject',
title: 'End Time',
},
],
preview: {
select: {
title: 'embed.title.en'
}
}
}<file_sep>/schemas/simpleBlockContent.js
import {
FaBible,
FaPaperclip,
FaUserAlt,
FaLanguage,
FaFileAlt,
FaEllipsisH,
FaQuoteLeft,
FaMapMarkerAlt,
FaRegCalendarAlt,
FaItunesNote } from 'react-icons/fa'
export default {
title: 'Block Content',
name: 'simpleBlockContent',
type: 'array',
of: [
{
title: 'Block',
type: 'block',
// Styles let you set what your user can mark up blocks with. These
// corrensponds with HTML tags, but you can set any title or value
// you want and decide how you want to deal with it where you want to
// use your content.
styles: [
{title: 'Normal', value: 'normal'}
],
lists: [{title: 'Bullet', value: 'bullet'}],
// Marks let you mark up inline text in the block editor.
marks: {
// Decorators usually describe a single property – e.g. a typographic
// preference or highlighting by editors.
decorators: [{title: 'Strong', value: 'strong'}, {title: 'Emphasis', value: 'em'}],
// Annotations can be any object structure – e.g. a link or a footnote.
annotations: [
{
name: 'link',
type: 'object',
title: 'link',
fields: [
{
name: 'href',
title: 'URL',
type: 'url'
}
]
},
{
name: 'internalLink',
type: 'object',
title: 'Internal link',
blockEditor: {
icon: FaPaperclip
},
fields: [
{
name: 'reference',
type: 'reference',
to: [
{ type: 'post' },
{ type: 'organization' },
{ type: 'newspaperArticle' },
{ type: 'book' }
// other types you may want to link to
]
}
]
},
{
name: 'personLink',
type: 'object',
title: 'Person link',
blockEditor: {
icon: FaUserAlt
},
fields: [
{
name: 'reference',
type: 'reference',
to: [
{ type: 'person' }
]
}
]
},
{
name: 'bibleTag',
type: 'object',
title: 'Bible Verse',
blockEditor: {
icon: FaBible
},
fields: [
{
name: 'book',
type: 'string',
options: {
list: [
"Genesis",
"Exodus",
"Leviticus",
"Numbers",
"Deuteronomy",
"Joshua",
"Judges",
"Ruth",
"1 Samuel",
"2 Samuel",
"1 Kings",
"2 Kings",
"1 Chronicles",
"2 Chronicles",
"Ezra",
"Nehemiah",
"Esther",
"Job",
"Psalms",
"Proverbs",
"Ecclesiastes",
"Song of Solomon",
"Isaiah",
"Jeremiah",
"Lamentations",
"Ezekiel",
"Daniel",
"Hosea",
"Joel",
"Amos",
"Obadiah",
"Jonah",
"Micah",
"Nahum",
"Habakkuk",
"Zephaniah",
"Haggai",
"Zechariah",
"Malachi",
"Matthew",
"Mark",
"Luke",
"John",
"Acts",
"Romans",
"1 Corinthians",
"2 Corinthians",
"Galatians",
"Ephesians",
"Philippians",
"Colossians",
"1 Thessalonians",
"2 Thessalonians",
"1 Timothy",
"2 Timothy",
"Titus",
"Philemon",
"Hebrews",
"James",
"1 Peter",
"2 Peter",
"1 John",
"2 John",
"3 John",
"Jude",
"Revelation"
]
}
},
{
name: 'chapter',
type: 'number',
},
{
name: 'verse',
type: 'number',
},
{
name: 'verseEnd',
type: 'number',
}
]
},
{
name: 'eventLink',
type: 'object',
title: 'Event link',
blockEditor: {
icon: FaRegCalendarAlt
},
fields: [
{
name: 'reference',
type: 'reference',
to: [
{ type: 'event' }
]
}
]
},
]
}
},
// You can add additional types here. Note that you can't use
// primitive types such as 'string' and 'number' in the same array
// as a block type.
//{
//type: 'image',
//options: {hotspot: true}
//}
]
}
<file_sep>/schemas/book.js
import { FaBook } from 'react-icons/fa'
import docMetadata from './docMetadata'
export default {
name: 'book',
title: 'Book',
icon: FaBook,
type: 'document',
fields: [
...docMetadata,
{
name: 'date',
title: 'Date Published',
type: 'dateObject',
},
{
name: 'links',
title: 'Links',
type: 'array',
of: [{
type: 'object',
fields: [
{
name: 'title',
type: 'string',
title: 'Site Title',
options: {
list: [
{title: 'Archive.org', value: 'archive.org'},
{title: 'Publisher Official', value: 'publisher'},
]
}
},
{
name: 'url',
type: 'url',
title: 'URL',
},
]
}]
},
],
fieldsets: [
{
name: 'metadata',
title: 'Metadata',
options: {
collapsible: true,
collapsed: true
}
}
],
preview: {
select: {
title: 'title.en',
media: 'mainImage.file'
},
}
}<file_sep>/components/AutoFill/Option.js
import React from 'react'
import { Card, Flex, Stack, Text, Avatar } from '@sanity/ui'
const Option = (props) => {
return (
<Card as="button" padding={2}>
<Flex align="center">
<Avatar
size={[0, 0, 1]}
src={props.option.payload.imageUrl}
/>
<Stack space={[1, 1, 2]} padding={2}>
<Text size={[2, 2, 3]}>
{props.option.payload.name}
</Text>
<Text size={[1, 1, 2]}>
{props.option.payload.description}
</Text>
</Stack>
</Flex>
</Card>
)
}
export default Option<file_sep>/schemas/sermon.js
import { object } from 'prop-types'
import { GiPublicSpeaker } from 'react-icons/gi/'
import docMetadata from './docMetadata'
export default {
name: 'sermon',
icon: GiPublicSpeaker,
type: 'document',
fields: [
...docMetadata,
{
name: 'narrations',
type: 'array',
of: [{
type: 'object',
fields: [
{
type: 'file',
name: 'File',
title: 'Audio or Video File'
},
{
type: 'string',
name: 'lang',
title: 'Language',
options: {
list: ['en','sw']
}
},
{
name: 'narrator',
type: 'reference',
to: [
{ type: 'person' }
]
}
]
}]
},
{
name: 'date',
type: 'dateObject',
title: 'Date Created',
},
{
name: 'dateEnd',
type: 'dateObject',
title: 'Latest Possible Date Created',
},
{
name: 'categories',
title: 'Categories',
type: 'array',
validation: Rule => Rule.unique().error('You already have that category listed.'),
of: [{type: 'reference', to: {type: 'category'}}],
fieldset: 'metadata'
},
],
fieldsets: [
{
name: 'metadata',
title: 'Metadata',
options: {
collapsible: true,
collapsed: true
}
}
],
preview: {
select: {
title: 'title.en',
author: 'author.name',
media: 'mainImage.file'
},
prepare(selection) {
const {author} = selection
return Object.assign({}, selection, {
subtitle: author && `by ${author}`
})
}
}
}
<file_sep>/schemas/videoDoc.js
import { FaFilm } from 'react-icons/fa'
export default {
name: 'videoDoc',
title: 'Video',
icon: FaFilm,
type: 'document',
fields: [
{
name: 'title',
title: 'Title',
type: 'localeString',
validation: Rule => Rule.required()
},
{
name: 'slug',
title: 'Slug',
type: 'localeSlug',
options: {
source: 'title',
maxLength: 96,
isUnique: input => input
},
validation: Rule => Rule.required()
},
{
name: 'files',
title: 'Video Files',
type: 'array',
of: [{
type: 'file',
title: 'Video File'
}]
},
{
name: 'transcriptions',
type: 'array',
of: [{
type: 'object',
fields: [
{
name: 'transcription',
type: 'file',
title: 'Transcription File'
},
{
name: 'lang',
type: 'string',
title: 'Language'
},
]
}]
},
{
name: 'cover',
type: 'image',
title: 'Cover Photo'
},
{
name: 'authors',
title: 'Authors',
type: 'array',
validation: Rule => Rule.unique().error('You can only have one of a person'),
of: [{type: 'reference', to: [{type: 'person'}, {type: 'organization'}]}]
},
{
name: 'date',
type: 'dateObject',
title: 'Date Created',
},
{
name: 'source',
type: 'url',
title: 'Source URL',
},
{
name: 'license',
type: 'string',
title: 'License Type',
options: {
list: [
{title: 'Unknown', value: 'NA'},
{title: 'Copyright', value: 'C'},
{title: 'Public Domain', value: 'PD'},
{title: 'Creative Commons Attribution (CC BY)', value: 'CC_BY'},
{title: 'Creative Commons Attribution ShareAlike (CC BY-SA)', value: 'CC_BY-SA'},
{title: 'Creative Commons Attribution-NoDerivs (CC BY-ND)', value: 'CC_BY-ND'},
{title: 'Creative Commons Attribution-NonCommercial (CC BY-NC)', value: 'CC_BY-NC'},
{title: 'Creative Commons Attribution-NonCommercial-ShareAlike (CC BY-NC-SA)', value: 'CC_BY-NC-SA'},
{title: 'Attribution-NonCommercial-NoDerivs (CC BY-NC-ND)', value: 'CC_BY-NC-ND'},
]
}
},
{
name: 'permissionGranted',
type: 'boolean',
title: 'Used with permission',
},
{
name: 'notes',
type: 'simpleBlockContent',
title: 'Internal Notes',
description: 'You might want to put details here about how the permission was attained, in case it was ever needed.'
}
],
initialValue: {
permissionGranted: false,
},
preview: {
select: {
title: 'title.en',
media: 'file'
}
}
}<file_sep>/components/AutoFill/index.js
import React, { useState, useEffect } from 'react'
import { Grid, Stack, Label, TextInput } from '@sanity/ui'
import PatchEvent, {set, unset} from '@sanity/form-builder/PatchEvent'
import { FormField } from '@sanity/base/components'
import client from 'part:@sanity/base/client'
import AutocompleteField from './AutocompleteField'
const AutoFill = (props) => {
//TODO Create 3 props to make re-usable
//1. Options (object) - contain the fields to be matched with Autocomplete results
//2. Handle Search Change (function)
//3. Handle Text Input Change (function)
//So all external API calls will be handled by individual instances,
//and this will handle layout, basic function between the 2 inputs, and Sanity patches
const [selectedOption, setSelectedOption] = useState(null)
const {
type,
value,
readOnly,
placeholder,
markers,
presence,
compareValue,
onChange,
onFocus,
onBlur,
fieldsToFill,
currentRef
} = props
const handleSelectCallback = async(e) => {
onChange( PatchEvent.from(e.value ? set(e.value) : unset()) )
const fields = await fieldsToFill(e)
setSelectedOption(fields)
}
useEffect(() => {
if(value && selectedOption){
client.patch(props.document._id).setIfMissing(selectedOption).commit()
}
}, [selectedOption, value])
//TODO set up autofill on blur
const handleBlur = React.useCallback(
// useCallback will help with performance
(event) => {
const inputValue = event.currentTarget.value
//onBlur(fetchFillValues(inputValue))
},
[onBlur]
)
const handleChange = React.useCallback(
(event) => {
const inputValue = event.currentTarget.value
onChange(PatchEvent.from(inputValue ? set(inputValue) : unset()))
},
[onChange]
)
return (
<FormField
description={type.description} // Creates description from schema
title={type.title} // Creates label from schema title
__unstable_markers={markers} // Handles all markers including validation
__unstable_presence={presence} // Handles presence avatars
compareValue={compareValue} // Handles "edited" status
>
<Grid columns={[1, 1, 2, 2]} gap={2} >
<Stack space={2}>
<Label>Search</Label>
<AutocompleteField {...props} handleSelectCallback={handleSelectCallback} />
</Stack>
<Stack space={2}>
<Label>Text</Label>
<TextInput
id="fgfgf666gjjgjhguu8"
value={value}
readOnly={readOnly}
placeholder={placeholder}
onFocus={onFocus}
onChange={handleChange}
onBlur={handleBlur}
ref={currentRef}
/>
</Stack>
</Grid>
</FormField>
)
}
export default AutoFill<file_sep>/schemas/section.js
import { FaParagraph } from 'react-icons/fa'
export default {
name: 'section',
title: 'Section',
icon: FaParagraph,
type: 'object',
fields: [
{
name: 'headingText',
title: 'Heading Text',
type: 'localeString',
fieldset: 'heading'
},
{
name: 'headingLevel',
title: 'Heading Level',
type: 'string',
fieldset: 'heading',
options: {
list: ['h2','h3','h4','h5','h6']
}
},
{
name: 'content',
title: 'Section Content',
type: 'localeAdvancedBlockContent'
},
{
name: 'author',
title: 'Author',
type: 'reference',
to: {type: 'person'}
},
{
name: 'sectionImage',
title: 'Section Image',
type: 'imageObject',
fieldset: 'appearance'
},
{
name: 'sectionColor',
title: 'Section Color',
type: 'color',
fieldset: 'appearance'
},
{
name: 'sectionAttachment',
title: 'Section Attachment',
type: 'file',
fieldset: 'appearance'
}
],
fieldsets: [
{
name: 'heading',
title: 'Section Heading',
options: {
columns: 2
}
},
{
name: 'appearance',
title: 'Appearance',
description: 'These are fields that themes will use in different ways.',
options: {
collapsible: true,
collapsed: true
},
}
],
preview: {
select: {
title: 'headingText.en',
author: 'author.name',
media: 'sectionImage.imageFile.image'
}
}
}
<file_sep>/schemas/chartBlock.js
export default {
name: 'chartBlock',
title: 'Chart',
type: 'object',
fields: [
{
name: 'title',
type: 'string',
title: 'Title',
validation: Rule => Rule.required()
},
{
name: 'type',
type: 'string',
title: 'Type',
validation: Rule => Rule.required(),
options: {
list: ['bar', 'line', 'scatter', 'pie', 'percentage']
}
},
{
title: 'Labels',
name: 'labels',
description: 'These are the labels for the data in the chart. They might be years, months, etc.',
type: 'array',
of: [{type: 'string'}],
options: {
layout: 'tags'
},
validation: Rule => Rule.required()
},
{
title: 'Datasets',
name: 'datasets',
type: 'array',
of: [{
type: 'object',
name: 'dataset',
fields: [
{
title: 'Name',
name: 'name',
type: 'string'
},
{
title: 'Values',
name: 'values',
type: 'array',
of: [{type: 'number'}],
validation: rule => rule.custom((value, schema) => {
const sectionKey = schema.path[1]._key
const parentKey = schema.path[4]._key
const match = (s, c, l = 'en') =>
schema.document.sections.filter(y =>
y._key === s)
.map(z =>
z.content[l].filter(a => a._key === c))
const parentValue = match(sectionKey,parentKey)
if (parentValue[0][0].labels.length === value.length) {
return true
} else {
return 'You need to add the same number of items as there are labels in the chart.'
}
})
},
]
}]
},
{
name: 'caption',
type: 'simpleBlockContent',
title: 'Caption',
}
]
}<file_sep>/schemas/citationBook.js
export default {
type: 'object',
name: 'citationBook',
fields: [
{
name: 'source',
title: 'Source Book',
type: 'reference',
to: {type: 'book'}
},
{
name: 'pageStart',
title: 'Start Page',
type: 'string'
},
{
name: 'pageEnd',
title: 'End Page',
type: 'string'
}
],
preview: {
select: {
title: 'source.title.en',
media: 'source.mainImage.imageFile.image'
}
}
}<file_sep>/schemas/newspaperArticle.js
import { FaRegFileAlt } from 'react-icons/fa'
export default {
name: 'newspaperArticle',
title: 'Newspaper Article',
icon: FaRegFileAlt,
type: 'document',
fields: [
{
name: 'title',
title: 'Title',
type: 'localeString',
validation: Rule => Rule.required()
},
{
name: 'slug',
title: 'Slug',
type: 'localeSlug',
options: {
source: 'title',
maxLength: 96,
isUnique: input => input
},
validation: Rule => Rule.required()
},
{
name: 'subtitle',
title: 'Sub Title',
type: 'localeString'
},
{
name: 'file',
type: 'image',
title: 'Image File',
options: {
hotspot: true
},
fields: [
{
name: 'alt',
type: 'localeString',
title: 'Alt Text',
description: 'Use Newspaper Article, if you do not need to describe an image in the clipping',
validation: Rule => Rule.required(),
options: {
isHighlighted: true
}
},
]
},
{
name: 'authors',
title: 'Authors',
type: 'array',
validation: Rule => Rule.unique().error('You can only have one of a person'),
of: [{type: 'reference', to: [{type: 'person'}, {type: 'organization'}]}]
},
{
name: 'parent',
title: 'Newspaper',
type: 'reference',
to: {type: 'newspaper'},
validation: Rule => Rule.required()
},
{
name: 'pageStart',
title: 'Start Page',
type: 'number',
validation: Rule => Rule.required()
},
{
name: 'pageEnd',
title: 'End Page',
type: 'number'
},
{
name: 'date',
title: 'Date Published',
type: 'dateObject',
validation: Rule => Rule.required()
},
{
name: 'source',
title: 'Source URL',
type: 'url',
fieldset: 'source'
},
{
title: 'Is the source behind a paywall?',
name: 'paywall',
type: 'boolean',
fieldset: 'source'
},
{
name: 'content',
title: 'Content',
type: 'localeAdvancedBlockContent'
},
],
fieldsets: [
{
name: 'source',
title: 'Source',
options: {
collapsible: true,
collapsed: true
}
},
{
name: 'metadata',
title: 'Metadata',
options: {
collapsible: true,
collapsed: true
}
}
],
initialValue: {
paywall: false,
},
preview: {
select: {
title: 'title.en',
media: 'file',
subtitle: 'parent.title.en'
},
}
}<file_sep>/components/FaceTagger/index.js
import './index.css'
import React from 'react'
import {withDocument} from 'part:@sanity/form-builder'
import client from 'part:@sanity/base/client'
import urlBuilder from '@sanity/image-url'
import Container from './Container'
import Form from './Form'
const FaceTagger = React.forwardRef((props, ref) => {
// this is called by the form builder whenever this input should receive focus
//props.onFocus(() => ref)
const {type} = props
let imageUlr
if (props.document[type.options.imageField]) {
const imageReference = props.document[type.options.imageField]
imageUlr = urlBuilder(client).image(imageReference)
}
return (
<div>
<h2>{type.title}</h2>
<div tabIndex="0" ref={ref}>
<Container src={imageUlr} {...props} />
</div>
<Form {...props} />
</div>
)
})
export default withDocument(FaceTagger)<file_sep>/schemas/citationPublicationArticle.js
export default {
type: 'object',
name: 'citationPublicationArticle',
fields: [
{
name: 'source',
title: 'Source Article',
type: 'reference',
to: {type: 'publicationArticle'}
},
{
name: 'pageStart',
title: 'Start Page',
type: 'string'
},
{
name: 'pageEnd',
title: 'End Page',
type: 'string'
}
],
preview: {
select: {
title: 'source.title.en',
media: 'source.mainImage'
}
}
}<file_sep>/schemas/dateObject.js
export default {
type: 'object',
name: 'dateObject',
fields: [
{
name: 'time',
title: 'Time',
type: 'datetime',
},
{
name: 'precision',
title: 'Precision',
type: 'number',
options: {
list: [
{title: 'Millennium', value: 6},
{title: 'Century', value: 7},
{title: 'Decade', value: 8},
{title: 'Year', value: 9},
{title: 'Month', value: 10},
{title: 'Day', value: 11},
{title: 'Hour', value: 12},
{title: 'Minute', value: 13}
]
},
validation: Rule => Rule.min(6).max(13)
},
{
name: 'isCirca',
title: 'Is Circa',
type: 'boolean',
},
{
name: 'calendar',
title: 'Calendar',
type: 'string',
}
],
}<file_sep>/components/Logo/index.js
import React from 'react'
import './global.css?raw'
const Logo = () => {
return (
<svg id="svg65" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 96.46" fill="currentColor">
<path d="M99.91,85.69,64.1,86,64,76.64H90.67l.12-67.14-36.35,0V.3L100,.27l-.09,85.42Z" transform="translate(0 -0.27)"/>
<path d="M14.64.41H51.7V9.58l-26.58.05.05,13.92,22.22.06,0,8.51-22.21-.06c.49,10.16.22,30.62.22,30.62l-10.92,0Z" transform="translate(0 -0.27)"/>
<path d="M50.56,84.77,50.4,23.21l37.06-.13,0,9.17-26.58.15L61,46.31l22.21,0,.08,8.51-22.21,0,.11,30.83-.05.55-10.48,0Z" transform="translate(0 -0.27)"/>
<path d="M47.89,86l-32.09.11L25,96.73H14.65L0,81,14.71,65.45H25.46l-9.77,11H47.84l0,9.61Z" transform="translate(0 -0.27)"/>
</svg>
)
}
export default Logo<file_sep>/components/WikidataLookup/fetchWikiCommonsImage.js
import client from 'part:@sanity/base/client'
import md5 from 'md5'
import parseDate from './parseDate'
import slugify from '../../utils/slugify'
const fetchImageMetaData = async (name) => {
const url = `https://commons.wikimedia.org/w/api.php?action=query&titles=Image:${encodeURIComponent(name)}&prop=imageinfo&iiprop=extmetadata&format=json&origin=*`
const headers = { method: 'GET' }
const body = await fetch(url, headers)
return await body.json()
}
const fetchSanityImageRef = async (name) => {
const formattedName = name.split(' ').join('_')
const hash = md5(formattedName)
const url = `https://upload.wikimedia.org/wikipedia/commons/${hash.substring(0, 1)}/${hash.substring(0, 2)}/${formattedName}`
const imageFile = await fetch(url).then(x => x.blob())
const imageRef = await client.assets.upload('image', imageFile).then(a => a._id)
return imageRef
}
const postImageDocToSanity = async(mutation) => {
const postedDoc = await client.create(mutation)
const docRef = postedDoc._id
return docRef
}
const createMutation = async(options) => {
const {imageRef, imageMetaData} = options
const meta = Object.values(imageMetaData.query.pages)[0].imageinfo[0].extmetadata
const date = async(x) => {
if (x.DateTimeOriginal) {
return parseDate(x.DateTimeOriginal.value)
} else {
return {
date: {
time: x.DateTime.value,
precision: 7,
isCirca: false
}
}
}
}
return {
'_type': 'imageDoc',
'title': {'en': meta.ObjectName.value},
'slug': {'en': {'current': slugify(meta.ObjectName.value)} },
'file': {
asset: {
_ref: imageRef,
},
alt: {'en': meta.ImageDescription ? meta.ImageDescription.value : meta.ObjectName.value},
},
'authors': meta.Artist ? [{"_key": "a84c87d2ee6d", "title": {"en": meta.Artist.value.replace(/<[^>]*>?/gm, '') }}] : undefined,
'source': `https://commons.wikimedia.org/wiki/File:${meta.ObjectName.value.split(' ').join('_')}`,
'license': meta.License ? meta.License.value : undefined,
...await date(meta)
}
}
const fetchWikiCommonsImage = async(fileName) => {
const sanityImageRef = await fetchSanityImageRef(fileName)
const wikimediaImageMetaData = await fetchImageMetaData(fileName)
const mutation = await createMutation({imageRef: sanityImageRef, imageMetaData: wikimediaImageMetaData})
const imageDocRef = await postImageDocToSanity(mutation)
//The API call to upload the image to sanity and the one to get metadata from WMC
//can happen at the same time.
//Maybe I can use Promise.all?
return imageDocRef
}
export default fetchWikiCommonsImage<file_sep>/components/FaceTagger/Container.js
import React, {useState, useEffect, useRef } from 'react'
import Box from './Box'
import styles from './index.css'
import PatchEvent, {set, unset} from 'part:@sanity/form-builder/patch-event'
const createPatchFrom = (value, path) => PatchEvent.from(value === '' ? unset() : set(value, path))
function Container(props) {
const [mouseStatus, setMouseStatus] = useState(undefined)
const faces = props.value ? props.value.faces : []
const [containerSize, setContainerSize] = useState({x: 0, y:0})
const containerRef = useRef(null)
const ro = new ResizeObserver(entries => {
for (let entry of entries) {
setContainerSize({
x: entry.contentRect.width,
y: entry.contentRect.height
})
}
})
useEffect(() => {
if(containerRef !== null) {
ro.observe(containerRef.current)
}
}, [])
const handleReposition = (path,value) => {
props.onChange(createPatchFrom(value, path))
}
const faceBoxes = faces.map((face) =>
<Box
key={face._key}
mouseStatus={mouseStatus}
containerSize={containerSize}
handleReposition={handleReposition}
{...face}
/>
)
return (
<div
className={styles.container}
onMouseMove={(event) => {
event.persist()
setMouseStatus(event)
}}
onMouseUp={(event) => {
event.persist()
setMouseStatus(event)
}}
onMouseLeave={(event) => {
event.persist()
setMouseStatus(event)
}}
>
<img className={styles.image} ref={containerRef} src={props.src} />
{faceBoxes}
</div>
)
}
export default Container
<file_sep>/schemas/websiteArticle.js
import { FaGlobe } from 'react-icons/fa'
import docMetadata from './docMetadata'
export default {
name: 'websiteArticle',
title: 'Website Article',
icon: FaGlobe,
type: 'document',
fields: [
...docMetadata,
{
name: 'parent',
title: 'Website',
type: 'reference',
to: {type: 'website'},
validation: Rule => Rule.required()
},
{
name: 'date',
title: 'Date Published',
type: 'dateObject'
},
{
name: 'url',
title: 'Source URL',
type: 'url',
},
{
name: 'urlArchive',
title: 'Archive URL',
type: 'url',
}
],
fieldsets: [
{
name: 'metadata',
title: 'Metadata',
options: {
collapsible: true,
collapsed: true
}
}
],
preview: {
select: {
title: 'title.en',
media: 'mainImage.file'
},
}
}<file_sep>/schemas/schema.js
// First, we must import the schema creator
import createSchema from 'part:@sanity/base/schema-creator'
// Then import schema types from any plugins that might expose them
import schemaTypes from 'all:part:@sanity/base/schema-type'
// We import object and document schemas
import simpleBlockContent from './simpleBlockContent'
import audioDoc from './audioDoc'
import book from './book'
import category from './category'
import chartBlock from './chartBlock'
import citationBook from './citationBook'
import citationNewspaperArticle from './citationNewspaperArticle'
import citationPublicationArticle from './citationPublicationArticle'
import citationUrl from './citationWebsiteArticle'
import post from './post'
import postLink from './postLink'
import person from './person'
import section from './section'
import sermon from './sermon'
import localeString from './localeString'
import localeSlug from './localeSlug'
import dateObject from './dateObject'
import imageObject from './imageObject'
import audioObject from './audioObject'
import videoObject from './videoObject'
import localeSimpleBlockContent from './localeSimpleBlockContent'
import localeAdvancedBlockContent from './localeAdvancedBlockContent'
import localeStringArray from './localeStringArray'
import localeBlurb from './localeBlurb'
import localeImage from './localeImage'
import localeUrl from './localeUrl'
import mapDocument from './mapDocument'
import mapObject from './mapObject'
import newspaper from './newspaper'
import newspaperArticle from './newspaperArticle'
import newspaperArticleObject from './newspaperArticleObject'
import organization from './organization'
import publication from './publication'
import publicationArticle from './publicationArticle'
import song from './song'
import advancedBlockContent from './advancedBlockContent'
import blockQuoteObject from './blockQuoteObject'
import imageDoc from './imageDoc'
import videoDoc from './videoDoc'
import location from './location'
import event from './event'
import time from './time'
import website from './website'
import websiteArticle from './websiteArticle'
// Then we give our schema to the builder and provide the result to Sanity
export default createSchema({
// We name our schema
name: 'default',
// Then proceed to concatenate our our document type
// to the ones provided by any plugins that are installed
types: schemaTypes.concat([
// The following are document types which will appear
// in the studio.
post,
postLink,
book,
category,
imageDoc,
videoDoc,
person,
event,
location,
newspaper,
newspaperArticle,
organization,
publication,
publicationArticle,
audioDoc,
sermon,
song,
website,
websiteArticle,
mapDocument,
// When added to this list, object types can be used as
// { type: 'typename' } in other document schemas
section,
imageObject,
audioObject,
videoObject,
simpleBlockContent,
localeString,
localeSlug,
chartBlock,
citationBook,
citationNewspaperArticle,
citationPublicationArticle,
citationUrl,
dateObject,
localeSimpleBlockContent,
localeAdvancedBlockContent,
localeStringArray,
localeBlurb,
localeImage,
localeUrl,
advancedBlockContent,
blockQuoteObject,
mapObject,
newspaperArticleObject,
time
])
})
<file_sep>/parts/assetSource.js
import AssetSource from "part:sanity-plugin-media-library/asset-source"
export default [AssetSource]<file_sep>/components/WikidataLookup/parseDate.js
import * as chrono from 'chrono-node'
const removeSpecialCharacters = (s) => s.replaceAll(/\[|\]/g, '')
const re = new RegExp(/circa|ca\.|c(?=[0-9]{4})|c\.(?=[0-9]{4})|c\./, 'g')
const checkIfCirca = (o) => {
const value = o.date.time
const newValue = value.replaceAll(re, '')
o.date.isCirca = value !== newValue
o.date.time = removeSpecialCharacters(newValue)
return o
}
const handleDecadeRangeSplit = (s) => {
//1817-18 but not 1880 - 1890
const decades = s.match(/([1-9]{2})([0-9]{2})\s*(-|—|–)\s*([0-9]{2}(?=[^0-9]|$))/)
return decades ? [`${decades[1]}${decades[2]}`, `${decades[1]}${decades[4]}`] : null
}
const handleRegularSplit = (s) => {
const splitter = s.match(/(-|—|–|and)/)
return splitter ? s.split(splitter[0]) : null
}
const checkForSplit = (o) => {
const value = o.date.time
const decadeRange = handleDecadeRangeSplit(value)
const splitValue = decadeRange ? decadeRange : handleRegularSplit(value)
if (splitValue) {
o.date.time = splitValue[0]
o.date.isCirca = true
o.dateEnd = { time: splitValue[1], isCirca: true, precision: 0 }
}
return o
}
const getChronoPrecision = (x) => {
if ( x.isCertain('day') ) {
return 11
} else if ( x.isCertain('month') ) {
return 10
} else {
return 9
}
}
const runChrono = (o) => {
const results = chrono.parse(o.time)
if (results.length > 0) {
const result = results[0].start
o.precision = getChronoPrecision(result)
o.time = result.date().toISOString()
} else {
//Here check for just year
const year = o.time.match(/([0-9]{4})/)
if (year) {
o.precision = 9
o.time = new Date(year[0]).toISOString()
}
}
return o
}
const objectMap = (object, mapFn) => {
return Object.keys(object).reduce(function(result, key) {
result[key] = mapFn(object[key])
return result
}, {})
}
const parseDate = async(dateString) => {
const date = { date: { time: dateString, isCirca: false, precision: 9 } }
//Check that it is not an actual date format
if ( dateString.match(/([0-9]{4}-[0-9]{2}-[0-9]{2})/) ) return date
const cleanedDate = checkIfCirca(date)
const splitDate = checkForSplit(cleanedDate)
const runChronoOnBothDates = objectMap(splitDate, (x) => {
return runChrono(x)
})
return runChronoOnBothDates
}
export default parseDate
// TODO: check for 1800s / late 1850s / early 1700 s<file_sep>/schemas/publicationArticle.js
import { FaRegFileAlt } from 'react-icons/fa'
import docMetadata from './docMetadata'
export default {
name: 'publicationArticle',
title: 'Publication Article',
icon: FaRegFileAlt,
type: 'document',
fields: [
...docMetadata,
{
name: 'parent',
title: 'Publication',
type: 'reference',
to: {type: 'publication'},
validation: Rule => Rule.required()
},
{
name: 'pageStart',
title: 'Start Page',
type: 'number',
validation: Rule => Rule.required()
},
{
name: 'pageEnd',
title: 'End Page',
type: 'number'
},
{
name: 'date',
title: 'Date Published',
type: 'dateObject',
validation: Rule => Rule.required()
},
{
name: 'volume',
title: 'Volume',
type: 'number'
},
{
name: 'issueNumber',
title: 'Issue Number',
type: 'number'
},
{
name: 'url',
title: 'Source URL',
type: 'url',
fieldset: 'source'
},
{
title: 'Is the source behind a paywall?',
name: 'paywall',
type: 'boolean',
fieldset: 'source'
}
],
fieldsets: [
{
name: 'source',
title: 'Source',
options: {
collapsible: true,
collapsed: true
}
},
{
name: 'metadata',
title: 'Metadata',
options: {
collapsible: true,
collapsed: true
}
}
],
initialValue: {
paywall: false
},
preview: {
select: {
title: 'title.en',
media: 'mainImage.file'
},
}
}<file_sep>/parts/resolveProductionUrl.js
export default function resolveProductionUrl(document) {
if (document.slug) {
return `http://localhost:3000/en/post/${document.slug.en.current}`
}
}
<file_sep>/schemas/postLink.js
import { FaLink } from 'react-icons/fa/'
import docMetadata from './docMetadata'
export default {
name: 'postLink',
title: 'Link Post',
icon: FaLink,
type: 'document',
fields: [
{
name: 'source',
title: 'Source URL',
type: 'url',
validation: Rule => Rule.required()
},
...docMetadata,
{
name: 'categories',
title: 'Categories',
type: 'array',
validation: Rule => Rule.unique().error('You already have that category listed.'),
of: [{type: 'reference', to: {type: 'category'}}],
fieldset: 'metadata'
},
],
fieldsets: [
{
name: 'metadata',
title: 'Metadata',
options: {
collapsible: true,
collapsed: true
}
}
],
preview: {
select: {
title: 'title.en',
author: 'author.name',
media: 'mainImage.file'
},
prepare(selection) {
const {author} = selection
return Object.assign({}, selection, {
subtitle: author && `by ${author}`
})
}
}
}
<file_sep>/schemas/post.js
import { FaFileAlt } from 'react-icons/fa/'
import docMetadata from './docMetadata'
export default {
name: 'post',
title: 'Post',
icon: FaFileAlt,
type: 'document',
fields: [
...docMetadata,
{
name: 'sections',
title: 'Post Content Sections',
description: 'Click on a section title to edit the content',
type: 'array',
of: [{type: 'section'}],
options: {editModal:'fullscreen'}
},
{
name: 'categories',
title: 'Categories',
type: 'array',
validation: Rule => Rule.unique().error('You already have that category listed.'),
of: [{type: 'reference', to: {type: 'category'}}],
fieldset: 'metadata'
},
{
title: 'Theme',
name: 'theme',
type: 'string',
options: {
list: [
{title: 'Default', value: 'defaultTheme'},
{title: 'Victorian', value: 'victorian'}
]
}
},
],
fieldsets: [
{
name: 'metadata',
title: 'Metadata',
options: {
collapsible: true,
collapsed: true
}
}
],
initialValue: {
theme: 'defaultTheme'
},
preview: {
select: {
title: 'title.en',
author: 'author.name',
media: 'mainImage.file'
},
prepare(selection) {
const {author} = selection
return Object.assign({}, selection, {
subtitle: author && `by ${author}`
})
}
}
}
<file_sep>/schemas/song.js
import { FaItunesNote } from 'react-icons/fa'
import docMetadata from './docMetadata'
export default {
name: 'song',
title: 'Song',
icon: FaItunesNote,
type: 'document',
fields: [
...docMetadata,
{
name: 'links',
title: 'Links',
type: 'array',
of: [{
type: 'object',
fields: [
{
name: 'title',
type: 'string',
title: 'Site Title',
options: {
list: [
{title: 'Hymnary.org', value: 'hymnary.org'},
]
}
},
{
name: 'url',
type: 'url',
title: 'URL',
},
]
}]
},
{
name: 'tunes',
title: 'Tunes',
type: 'array',
validation: Rule => Rule.unique().error('You can only link to the same song once'),
of: [{type: 'reference', to: {type: 'song'}}],
},
{
name: 'date',
title: 'Date Published',
type: 'dateObject',
},
],
fieldsets: [
{
name: 'metadata',
title: 'Metadata',
options: {
collapsible: true,
collapsed: true
}
}
],
preview: {
select: {
title: 'title.en',
media: 'mainImage'
},
}
}<file_sep>/schemas/docMetadata.js
export default [
{
name: 'title',
title: 'Title',
type: 'localeString',
validation: Rule => Rule.required()
},
{
name: 'slug',
title: 'Slug',
type: 'localeSlug',
options: {
source: 'title',
maxLength: 96,
isUnique: input => input
},
validation: Rule => Rule.required()
},
{
name: 'subtitle',
title: 'Sub Title',
type: 'localeString'
},
{
name: 'authors',
title: 'Authors',
type: 'array',
validation: Rule => Rule.unique().error('You can only have one of a person'),
of: [{type: 'reference', to: {type: 'person'}}],
fieldset: 'metadata'
},
{
name: 'mainImage',
title: 'Main image',
type: 'reference', to: [{type: 'imageDoc'},{type: 'newspaperArticle'}],
},
{
name: 'longDescription',
title: 'Long Description',
type: 'localeSimpleBlockContent',
fieldset: 'metadata'
},
{
name: 'shortDescription',
title: 'Short Description',
type: 'localeBlurb',
description: 'This will be shown in list views and shared on social media. 140 characters max length.',
fieldset: 'metadata'
},
{
name: 'content',
title: 'Content',
type: 'localeAdvancedBlockContent'
},
{
name: 'tags',
title: 'Tags',
type: 'tags'
},
{
name: 'featured',
type: 'boolean',
title: 'Featured'
},
]
|
629d3a21ec430f20377c1f4b12c29f4fcfe08101
|
[
"JavaScript"
] | 38
|
JavaScript
|
the-former-faith/ff-backend
|
476278be9334a887ed3bb04d46bd11c9c1f283ba
|
2a904c44d363e1d21c1cef5873379357e2339dcf
|
refs/heads/master
|
<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>最新</title>
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/new.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/component.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/lable.css">
</head>
<body>
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>" >首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>" >发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle active">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/center/caiji');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/center/love');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<div id="flip" style="margin-top: 7rem">全部分类</div>
<div id="panel">
<?php if(is_array($category)): foreach($category as $key=>$vo): ?><div class="fenlei-name" ><?php echo ($vo["xqfl"]["name"]); ?></div><?php endforeach; endif; ?>
<div style="clear: both"></div>
</div>
<div class="guide">
<div class="unit">
<?php if(is_array($one)): foreach($one as $key=>$vo): ?><a href="<?php echo U('portal/interestDetail/index',array('id'=>$vo['xqfl_id']));?>" class="unit_a"><?php echo ($vo["xqfl_name"]); ?></a><?php endforeach; endif; ?>
</div>
<div class="unit">
<?php if(is_array($two)): foreach($two as $key=>$vo): ?><a href="<?php echo U('portal/interestDetail/index',array('id'=>$vo['xqfl_id']));?>" class="unit_a"><?php echo ($vo["xqfl_name"]); ?></a><?php endforeach; endif; ?>
</div>
<div class="unit" style="border-right:none ">
<?php if(is_array($three)): foreach($three as $key=>$vo): ?><a href="<?php echo U('portal/interestDetail/huaban',array('id'=>$vo['xqfl_id']));?>" class="unit_a"><?php echo ($vo["xqfl_name"]); ?></a><?php endforeach; endif; ?>
</div>
</div>
<div class="pictype">
<?php if(is_array($xingqu)): foreach($xingqu as $key=>$vo): ?><a href="<?php echo U('portal/InterestDetail/interest',array('xid'=>$vo['xq_id']));?>"><div class="pictype_1" ><img src="<?php echo U('portal/newest/imgXingqu',array('id'=>$vo['xq_id']));?>" ><div class="pictype_2 " style=" margin: -1.5rem 0 0 -2rem;"><?php echo ($vo["xq_name"]); ?></div></div></a><?php endforeach; endif; ?>
<div style="clear: both"></div>
</div>
<div class="middle">
<div id="collect-box"></div>
<div style="clear: both"></div>
</div>
<div class="nomore">
<div class="nomore_1" style="font-family: 微软雅黑;font-size:1rem" id="load">╮(・o・)╭ 查看更多.....</div>
<a href="#"><i class="iconfont icon-daosanjiao" style="color: black"></i></a>
</div>
<div class="footer" >
<div class="footer_1">
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div style="clear: both"></div>
</div>
<div class="footer_2">
<div class="footer_2_1"><a href="#">关注我们</a></div>
<div class="footer_2_2"><a href="#">信息博客</a><br><a href="#">新浪博客</a><br><a href="#">官方微信</a></div>
<div class="footer_2_2"><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a></div>
</div>
<div style="clear: both"></div>
<div class="footer_3">Copyright2016-2017 Heifeiku Leijan Technology Co.Ltd All Rights Reserved<br>
皖ICP备17010401号-2皖公网安备3301080233301号
</div>
</div>
<script type="text/javascript">
//全局变量
var GV = {
ROOT: "/",
WEB_ROOT: "/",
JS_ROOT: "public/js/"
};
</script>
<!-- Placed at the end of the document so the pages load faster -->
<script src="/public/js/jquery.js"></script>
<script src="/public/js/wind.js"></script>
<script src="/themes/simplebootx/Public/assets/simpleboot/bootstrap/js/bootstrap.min.js"></script>
<script src="/public/js/frontend.js"></script>
<script>
$(function(){
$('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });
$("#main-menu li.dropdown").hover(function(){
$(this).addClass("open");
},function(){
$(this).removeClass("open");
});
$.post("<?php echo U('user/index/is_login');?>",{},function(data){
if(data.status==1){
if(data.user.avatar){
$("#main-menu-user .headicon").attr("src",data.user.avatar.indexOf("http")==0?data.user.avatar:"<?php echo sp_get_image_url('[AVATAR]','!avatar');?>".replace('[AVATAR]',data.user.avatar));
}
$("#main-menu-user .user-nicename").text(data.user.user_nicename!=""?data.user.user_nicename:data.user.user_login);
$("#main-menu-user li.login").show();
}
if(data.status==0){
$("#main-menu-user li.offline").show();
}
/* $.post("<?php echo U('user/notification/getLastNotifications');?>",{},function(data){
$(".nav .notifactions .count").text(data.list.length);
}); */
});
;(function($){
$.fn.totop=function(opt){
var scrolling=false;
return this.each(function(){
var $this=$(this);
$(window).scroll(function(){
if(!scrolling){
var sd=$(window).scrollTop();
if(sd>100){
$this.fadeIn();
}else{
$this.fadeOut();
}
}
});
$this.click(function(){
scrolling=true;
$('html, body').animate({
scrollTop : 0
}, 500,function(){
scrolling=false;
$this.fadeOut();
});
});
});
};
})(jQuery);
$("#backtotop").totop();
});
</script>
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/swiper.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/assets/js/slippry.min.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/assets/js/classie.js"></script>
<script src="/themes/simplebootx/Public/assets/js/modalEffects.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("fast");
});
});
</script>
<!-- Initialize Swiper -->
<script>
$(".nav-box .right-menu .close-menu").click(function(){
$(".login-ul").slideUp();
$(".nav-box-ul").slideUp();
$(this).parent().removeClass("active");
});
$(".nav-box .right-menu .open-menu").click(function(){
$(".login-ul").slideDown();
$(".nav-box-ul").slideDown();
$(this).parent().addClass("active");
});
var pageIndex=1;
function getPostList(page) {
$.ajax({
type: "GET",
url: "/index.php?g=&m=Newest&a=collect&p="+page,
dataType: "json",
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
var pid = data[i].pid;
var uid = data[i].uid;
$("#collect-box").append(
'<div class="lable-box">' +
'<div class="img-detail-box">' +
'<a href="index.php?g=&m=Article&a=posts&pid='+pid+'"><img src="index.php?g=&m=Index&a=imgCollect&id=' + pid + '"></a>' +
'</div>' +
'<div class="user-box">' +
'<a href="index.php?g=Portal&m=user&a=index&id='+uid+'">'+
'<div class="user-touxiang">' +
'<img src="index.php?g=user&m=public&a=avatar&id=' + uid + '">' +
'</div></a>' +
'<div class="title-box-right">' +
'<div class="title-left">' +
data[i].post_title +
'</div>' +
'<div class="title-right">' +
'<a href="#">' +
'<i class="iconfont icon-guanzhu" style="color: red"></i>' +
'<font id="num-like" style="color: #989998">'+data[i].post_love+'</font>' +
'</a>' +
/* '<a href="#">' +
'<font style="float: right">' +
'<i class="iconfont icon-fenxiang"></i>' +
'</font>' +*/
'</a>' +
'</div>' +
'</div>' +
'<div class="user-name">'+data[i].user_nicename+'</div>' +
'</div>' +
'</div>'
)
}
if(data.length<16)
{
$("#load").text("╮(・o・)╭没有更多了.....");
}
pageIndex++;
}
});
}
getPostList(pageIndex);
$("#load").click(function()
{
getPostList(pageIndex);
});
</script>
</body>
</html><file_sep><?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
class ActivityController extends AdminbaseController{
protected $activity_model;
public function _initialize()
{
parent::_initialize();
$this->activity_model=D("Common/Activity");
}
//活动首页
public function index()
{
$User = M('Activity'); // 实例化User对象
$count=$User->count();
$page = $this->page($count, 10);
$activity = $User->limit($page->firstRow.','.$page->listRows)->select();
$this->assign('activity',$activity);
$this->assign("page", $page->show('Admin'));// 赋值分页输出
$this->display();
}
///添加
public function add()
{
$this->display();
}
public function add_post()
{
if (IS_POST) {
$_POST['post']['hd_img_url'] = $_POST['hd_img_url'];
$_POST['post']['hd_time'] = date("Y-m-d H:i:s", time());
$_POST['post']['hd_recommend'] = $_POST['hd_recommend'];
$_POST['post']['hd_name'] = $_POST['hd_name'];
$_POST['post']['hd_url'] = $_POST['hd_url'];
$page = I("post.post");
$result = $this->activity_model->add($page);
if ($result) {
$this->success("添加成功!");
} else {
$this->error("添加失败!");
}
}
}
//编辑
public function edit()
{
$id = I("get.id",0,'intval');
$activity=$this->activity_model->where(array('hd_id'=>$id))->find();
$this->assign("activity",$activity);
$this->display();
}
//编辑提交
public function edit_post()
{
if(IS_POST){
if ($this->activity_model->create()!==false) {
if ($this->activity_model->save()!==false) {
$this->success("保存成功!", U("xingqu/index"));
} else {
$this->error("保存失败!");
}
} else {
$this->error($this->activity_model->getError());
}
}
}
// 兴趣删除
public function delete(){
if(isset($_POST['ids'])){
$ids = implode(",", $_POST['ids']);
$data['slide_status']=0;
if ($this->activity_model->where("xq_id in ($ids)")->delete()!==false) {
$this->success("删除成功!");
} else {
$this->error("删除失败!");
}
}else{
$id = I("get.id",0,'intval');
if ($this->activity_model->delete($id)!==false) {
$this->success("删除成功!");
} else {
$this->error("删除失败!");
}
}
}
}<file_sep><?php if (!defined('THINK_PATH')) exit();?><html><!DOCTYPE HTML>
<head>
<title>发现</title>
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/swiper.min.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/found.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
</head>
<body>
<!--[if lte IE 8]>
<div class="text-center padding-top-50 padding-bottom-50 bg-blue-grey-100">
<p class="browserupgrade font-size-18">你正在使用一个<strong>过时</strong>的浏览器。请<a href="http://browsehappy.com/" target="_blank">升级您的浏览器</a>,以提高您的体验。</p>
</div>
<![endif]-->
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>" >首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>" class="active">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/center/caiji');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/center/love');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<!-- 幻灯片-->
<?php $home_slides=sp_getslide("portal_find"); $home_slides=empty($home_slides)?$default_home_slides:$home_slides; ?>
<div class="slide-box">
<div class="row" >
<div class="col-md-12" style="padding: 0px">
<!-- Swiper -->
<div class="swiper-container">
<div class="swiper-wrapper">
<?php if(is_array($home_slides)): foreach($home_slides as $key=>$vo): ?><div class="swiper-slide"><a href="<?php echo ($vo["slide_url"]); ?>"><img src="<?php echo sp_get_asset_upload_path($vo['slide_pic']);?>" alt=""></a></div><?php endforeach; endif; ?>
</div>
<!-- Add Pagination -->
<div class="swiper-pagination"></div>
<!-- Add Arrows -->
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
</div>
</div>
</div>
<div class="contain">
<!-- 大家关注的活动 -->
<div class="middle">
<div class="about">
<li class="text">大家关注</li>
</div>
<div class="edge">
<div class="edge-1"><div class="edge-1-1"style="margin-left:-1rem "></div></div>
<div class="edge-2"><li class="text-1">MORE ATTENTION</li></div>
<div class="edge-1"><div class="edge-1-1"style="margin-right:-1rem "></div></div>
</div>
</div>
<div class="room">
<div class="room-1-1" >
<?php if(is_array($activity)): foreach($activity as $key=>$vo): ?><div class="room-1" ><a href="<?php echo ($vo["hd_url"]); ?>" target="_blank"><img src="<?php echo sp_get_asset_upload_path($vo['hd_img_url']);?>"></a>
<div style="position: relative; text-align: center;color: white;font-size: 25px; top: -55%;text-shadow: 5px 3px 5px rgba(0,0,0,0.6)"><?php echo ($vo["hd_name"]); ?></div>
</div><?php endforeach; endif; ?>
</div>
</div>
<div class="middle">
<div class="about">
<li class="text">画板采集</li>
</div>
<div class="edge">
<div class="edge-1"><div class="edge-1-1"></div></div>
<div class="edge-2"><li class="text-1"> RECOMMENDED </li></div>
<div class="edge-1"><div class="edge-1-1" style="margin-left:1rem"></div></div>
</div>
</div>
<div id="hb-box">
</div>
<div class="colick">
<button type="submit" id="load" style="width: 100%; height: 40px; background-color: #FF455F;color: white;
border-bottom-left-radius: 20px;
border-bottom-right-radius: 20px;
border-top-left-radius: 20px;
border-top-right-radius: 20px;border: none;outline:medium">点击查看更多>>></button></div>
<div class="middle">
<div class="about">
<li class="text">兴趣采集</li>
</div>
<div class="edge">
<div class="edge-1"><div class="edge-1-1"></div></div>
<div class="edge-2"><li class="text-1"> RECOMMENDED </li></div>
<div class="edge-1"><div class="edge-1-1"></div></div>
</div>
</div>
<div id="hb">
</div>
<div class="colick">
<button type="submit" id="load2" style="width: 100%; height: 40px; background-color: #FF455F;color: white;
border-bottom-left-radius: 20px;
border-bottom-right-radius: 20px;
border-top-left-radius: 20px;
border-top-right-radius: 20px;border: none;outline:medium">点击查看更多>>></button></div>
</div>
<div class="footer" >
<div class="footer_1">
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div style="clear: both"></div>
</div>
<div class="footer_2">
<div class="footer_2_1"><a href="#">关注我们</a></div>
<div class="footer_2_2"><a href="#">信息博客</a><br><a href="#">新浪博客</a><br><a href="#">官方微信</a></div>
<div class="footer_2_2"><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a></div>
</div>
<div style="clear: both"></div>
<div class="footer_3">Copyright2016-2017 Heifeiku Leijan Technology Co.Ltd All Rights Reserved<br>
皖ICP备17010401号-2皖公网安备3301080233301号
</div>
</div>
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/swiper.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/assets/js/slippry.min.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/assets/js/classie.js"></script>
<script src="/themes/simplebootx/Public/assets/js/modalEffects.js"></script>
<script>
var isLogin='<?php echo ($isLogin); ?>';
// console.log(isLogin);
var pageIndex = 1;
function getHuabanList(page) {
$.ajax({
type: "GET",
url: "/index.php?g=&m=Find&a=gethuabanList&p="+page,
dataType: "json",
success: function (data) {
console.log(data);
var html = '';
for (var i = 0; i < data.length; i++) {
// var xid = data[i].xq_id;
if (data[i].pidlist != null) {
var pidlist = data[i].pidlist.split(",");
if(data[i].hbgz_hbid ==null || isLogin == 0)
{
html = html + '<div class="sheji">' +
'<div class="ping"> ' +
'<div class="high">'+pidlist.length+'</div> ' +
'<div class="text-2">' + data[i].hb_name + '</div> ' +
'<div class="text-3">' + data[i].hb_descp + '</div> ' +
'<div class="annv"> ' +
'<button data-hb_id="'+data[i].hb_id+'" class="guanzhu" style="border: none;width: 150px; height: 40px; background-color:#EEEEEE;color:#757575;border-bottom-left-radius: 20px;border-bottom-right-radius: 20px;border-top-left-radius: 20px;border-top-right-radius: 20px;outline:medium">' + '点击关注</button>' +
'</div>' +
'</div>'
}else{
html = html + '<div class="sheji">' +
'<div class="ping"> ' +
'<div class="high">'+pidlist.length+'</div> ' +
'<div class="text-2">' + data[i].hb_name + '</div> ' +
'<div class="text-3">' + data[i].hb_descp + '</div> ' +
'<div class="annv"> ' +
'<button data-hb_id="'+data[i].hb_id+'" class="guanzhu" style="border: none;width: 150px; height: 40px; background-color:#C0C0C0;color: white;border-bottom-left-radius: 20px;border-bottom-right-radius: 20px;border-top-left-radius: 20px;border-top-right-radius: 20px;outline:medium">' + '已关注</button>' +
'</div>' +
'</div>'
}
for (var j = 0; j < 4; j++) {
var pid = pidlist[j];
//console.log(pid);
html = html + '<div class="mian">' + '<a href="index.php?g=&m=Article&a=posts&pid=' + pid + '">' + '<img src="index.php?g=&m=Index&a=imgCollect&id=' + pid + '">' + '</a>' + '</div>';
}
html = html + '<div class="more">' +
'<a href="index.php?g=Portal&m=User&a=huaban&id=' + data[i].hb_id + '"><img src="/themes/simplebootx/Public/new/image/more.png"></a>' +
'<div class="text-4"><a href="index.php?g=Portal&m=User&a=huaban&id=' + data[i].hb_id + '">加载更多</a></div>' +
'</div>' +
'</div>'
}
}
$("#hb-box").append(html);
if (data.length < 6) {
$("#load").text("没有更多数据了");
}
pageIndex++;
}
});
}
getHuabanList(pageIndex);
$("#load").click(function()
{
getHuabanList(pageIndex);
});
$("body").on("click",".guanzhu",function()
{
var hb_id= $(this).attr("data-hb_id");
if($(this).text()=="点击关注")
{
$.ajax({
type: "GET",
url: "/index.php?g=User&m=follow&a=clickDrawFollow",
dataType: "json",
data:{
id:hb_id
},
success:function(data){
}
})
$(this).text("已关注")
$(this).css({"background":'#C0C0C0',"color":'white'})
}
else{
$.ajax({
type: "GET",
url: "/index.php?g=User&m=follow&a=clickCancelDraw",
dataType: "json",
data:{
id:hb_id
},
success:function(data){
}
})
$(this).text("点击关注")
$(this).css({"background":'#EEEEEE',"color":'#757575'})
}
});
var pageIndex2 = 1;
function getInterestList(page) {
$.ajax({
type: "GET",
url: "/index.php?g=&m=Find&a=getInterestList&p="+page,
dataType: "json",
success: function (data) {
var html = '';
for (var i = 0; i < data.length; i++) {
if (data[i].pidlist != null) {
var pidlist = data[i].pidlist.split(",");
var xid = data[i].xq_id;
if(data[i].xqdgz_xqid == null||isLogin==0)
{
html = html + '<div class="sheji-1">' +
'<div class="ping-1"> ' +
'<div class="high-1" style="color:white">'+pidlist.length+'</div> ' +
'<div class="text-2-1">' + data[i].xq_name + '</div> ' +
'<div class="text-3-1">' + data[i].xq_intro + '</div> ' +
'<div class="annv"> ' +
'<button data-xq-id ="'+xid+'" class="xqgz" style="border: none;width: 150px; height: 40px; background-color:#C1A062;color: white;border-bottom-left-radius: 20px;border-bottom-right-radius: 20px;border-top-left-radius: 20px;border-top-right-radius: 20px;outline:medium">' + '点击关注</button>' +
'</div>' +
'</div>'
}
else{
html = html + '<div class="sheji-1">' +
'<div class="ping-1"> ' +
'<div class="high-1" style="color:white">'+pidlist.length+'</div> ' +
'<div class="text-2-1">' + data[i].xq_name + '</div> ' +
'<div class="text-3-1">' + data[i].xq_intro + '</div> ' +
'<div class="annv"> ' +
'<button data-xq-id ="'+xid+'" class="xqgz" style="border: none;width: 150px; height: 40px; background-color:#C0C0C0;color: white;border-bottom-left-radius: 20px;border-bottom-right-radius: 20px;border-top-left-radius: 20px;border-top-right-radius: 20px;outline:medium">' + '已关注</button>' +
'</div>' +
'</div>'
}
for (var j = 0; j < 4; j++) {
var pid = pidlist[j];
html = html + '<div class="mian">' + '<a href="index.php?g=&m=Article&a=posts&pid=' + pid + '">' + '<img src="index.php?g=&m=Index&a=imgCollect&id=' + pid + '">' + '</a>' + '</div>';
}
html = html + '<div class="more">' +
'<a href="index.php?g=portal&m=InterestDetail&a=interest&xid=' + xid + '"><img src="/themes/simplebootx/Public/new/image/more.png"></a>' +
'<div class="text-4"><a href="index.php?g=portal&m=InterestDetail&a=interest&xid=' + xid + '">加载更多</a></div>' +
'</div>' +
'</div>'
}
}
$("#hb").append(html);
if(data.length < 6)
$("#load2").text("没有更多数据了");
pageIndex2++;
}
});
}
getInterestList(pageIndex2);
$("#load2").click(function()
{
getInterestList(pageIndex2);
});
$("body").on("click",".xqgz",function()
{
var xid= $(this).attr("data-xq-id");
console.log(xid);
if($(this).text()=="点击关注")
{
$.ajax({
type: "GET",
url: "/index.php?g=User&m=follow&a=clickInterestFollow",
dataType: "json",
data:{
id:xid
},
success:function(data){
}
})
$(this).text("已关注")
$(this).css({"background":'#C0C0C0',"color":'white'})
}
else{
$.ajax({
type: "GET",
url: "/index.php?g=User&m=follow&a=clickCancelInterest",
dataType: "json",
data:{
id:xid
},
success:function(data){
}
})
$(this).text("点击关注")
$(this).css({"background":'#C1A062'})
}
});
var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
paginationClickable: true,
spaceBetween: 30,
centeredSlides: true,
autoplay: 20000,
autoplayDisableOnInteraction: false
});
$(".nav-box .right-menu .close-menu").click(function(){
$(".login-ul").slideUp();
$(".nav-box-ul").slideUp();
$(this).parent().removeClass("active");
});
$(".nav-box .right-menu .open-menu").click(function(){
$(".login-ul").slideDown();
$(".nav-box-ul").slideDown();
$(this).parent().addClass("active");
});
</script>
</body>
</html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<div lang="en">
<head>
<meta charset="utf-8">
<title>搜索</title>
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/new.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
<style>
.search{
width: 90%;
height: 3.5rem;
border-radius: 5px;
border: 1px solid gainsboro;
margin: 0 auto;
margin-top: -4rem;
}
.search input{
width: 90%;
height: 3.5rem;
background-color:transparent;
border-radius: 5px;
border: 0px solid gainsboro;
margin-left: 5%;
outline: medium
}
.search-icon button{
z-index: 99;
float: right;
margin-top: -10rem;
margin-right: 0.5rem;
width: 3rem;
height: 3rem;
background: rgba(255, 255, 255, 0);
border: 0px;
outline: medium;
}
.search-icon button i{
font-size: 2.5rem;
color: #959595;
}
.search-icon button i:hover{
color: black;
}
</style>
</head>
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/collect/index');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/love/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<div id="flip" style="margin-top: 7rem">全部分类</div>
<div id="panel">
<?php if(is_array($category)): foreach($category as $key=>$vo): ?><div class="fenlei-name" ><?php echo ($vo["xqfl"]["name"]); ?></div><?php endforeach; endif; ?>
</div>
<div class="guide" style="padding-top: 5rem;height: 12rem">
<div class="unit">
<?php if(is_array($one)): foreach($one as $key=>$vo): ?><a href="<?php echo U('portal/interestDetail/index',array('id'=>$vo['xqfl_id']));?>" class="unit_a"><?php echo ($vo["xqfl_name"]); ?></a><?php endforeach; endif; ?>
</div>
<div class="unit">
<?php if(is_array($two)): foreach($two as $key=>$vo): ?><a href="<?php echo U('portal/interestDetail/index',array('id'=>$vo['xqfl_id']));?>" class="unit_a"><?php echo ($vo["xqfl_name"]); ?></a><?php endforeach; endif; ?>
</div>
<div class="unit" style="border-right:none ">
<?php if(is_array($three)): foreach($three as $key=>$vo): ?><a href="<?php echo U('portal/interestDetail/huaban',array('id'=>$vo['xqfl_id']));?>" class="unit_a"><?php echo ($vo["xqfl_name"]); ?></a><?php endforeach; endif; ?>
</div>
<div class="search">
<form method="post" action="<?php echo U('Portal/search/index');?>">
<input name="postname" placeholder="点击搜索一下您就知道">
<div class="search-icon" ><button type="submit"><i class="iconfont icon-sousuo" ></i></button></div>
</form>
</div>
</div>
<div class="middle">
<?php if(is_array($list)): foreach($list as $key=>$vo): ?><div class="middle_2">
<div class="picture">
<img src="<?php echo U('Portal/index/imgCollect',array('id'=>$vo['pid']));?>">
</div>
<div class="touxiang">
<a href="<?php echo U('Portal/user/index',array('id'=>$vo['uid']));?>">
<div class="touxiang_1">
<div class="touxiang_1_img"><img src="<?php echo U('User/public/avatar',array('id'=>$vo['uid']));?>" ></div>
<div class="touxiang_1_p"><p><?php echo ($vo["user_nicename"]); ?></p></div>
</div>
</a>
<div class="touxiang_2_p"><p><?php echo ($vo["post_title"]); ?></p></div>
<div class="touxiang_3">
<div class="touxiang_3_img"><a href="#"><i class="iconfont icon-guanzhu" style="color: #959595"></i></a></div>
<div class="touxiang_3_p"><p><?php echo ($vo["post_love"]); ?></p></div>
</div>
<div class="touxiang_4">
<div class="touxiang_4_img"><a href="#"><i class="iconfont icon-fenxiang" style="color: #959595"></i></a></div>
</div>
</div>
</div><?php endforeach; endif; ?>
<div style="clear: both"></div>
</div>
<div class="nomore">
<div class="nomore_1" style="font-family: 微软雅黑;font-size:1rem">╮(・o・)╭ 没有更多了.....</div>
<a href="#"><i class="iconfont icon-daosanjiao" style="color: black"></i></a>
</div>
<div class="footer">
<div class="footer_1">
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div style="clear: both"></div>
</div>
<div class="footer_2">
<div class="footer_2_1"><a href="#">关注我们</a></div>
<div class="footer_2_2"><a href="#">信息博客</a><br><a href="#">新浪博客</a><br><a href="#">官方微信</a></div>
<div class="footer_2_2"><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a></div>
</div>
<div style="clear: both"></div>
<div class="footer_3">Copyright©2016-2017 Heifeiku Leijan Technology Co.Ltd All Rights Reserved<br>
皖ICP备17010401号-2皖公网安备3301080233301号
</div>
</div>
</div>
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideToggle("fast");
});
});
</script>
<!-- Initialize Swiper -->
<script>
$(".nav-box .right-menu .close-menu").click(function(){
$(".login-ul").slideUp();
$(".nav-box-ul").slideUp();
$(this).parent().removeClass("active");
});
$(".nav-box .right-menu .open-menu").click(function(){
$(".login-ul").slideDown();
$(".nav-box-ul").slideDown();
$(this).parent().addClass("active");
});
</script>
</body>
</html><file_sep><?php
/**
* Created by PhpStorm.
* User: Admin
* Date: 2018/1/10
* Time: 16:36
*/
namespace Portal\Model;
use Common\Model\CommonModel;
class XingquModel extends CommonModel {
public function items()
{
return $this->hasMany('Huaban', 'hb_xqd_id', 'xq_id');
}
public static function getHuaban(){
$huaban = self::with("item")->select();
return $huaban;
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: 周前
* Date: 2018/1/7
* Time: 12:15
*/
namespace User\Controller;
use Common\Controller\MemberbaseController;
/*
* 用户画板行为
*/
class DrawController extends MemberbaseController
{
//用户中心关注的画板展示
public function interest_draw()
{
$this->check_login();
$uid = sp_get_current_userid();
$hbgz_model = M("Hbgz");
$where = array("hbgz_uid" => $uid);
$hbgz = $hbgz_model->where($where)
->order("hbgz_create_time")
->alias("a")
->join("tb_huaban b on a.hbgz_hbid = b.hb_id")
->join("tb_hbcj c on b.hb_id = c.hbcj_hb_id")
->join("tb_posts d on c.hbcj_posts_id = d.id")
->select();
echo json_encode($hbgz);
}
//用户中心编辑画板
public function edit_draw()
{
// $this->check_login();
$uid = sp_get_current_userid();
$hid = I("get.id", 0, 'intval');
$huaban_model = M("Huaban");
$fl_model = M("Xingqu_fenlei");
$hb_fl = $fl_model->where("xqfl_area = 3")->select();
$result = $huaban_model->where(array("hb_id" => $hid, "hb_uid" => $uid))->find();
$this->assign($result);
//var_dump($result);
$this->assign("category",$hb_fl);
$this->display(":editdraw");
}
//用户中心编辑画板提交
public function edit_post()
{
if(IS_POST){
$this->check_login();
$uid = sp_get_current_userid();
$huaban_model = M("Huaban");
$id = $_POST["hb_id"];
$draw["hb_name"] = $_POST["hb_name"];
$draw["hb_descp"] = $_POST["hb_descp"];
$draw["hb_update_time"] = date("Y-m-d H:i:s", time());
$draw["hb_xqd_id"] = $_POST["hb_term_id"];
$result = $huaban_model->where(array("hb_uid"=>$uid,"hb_id"=>$id))->save($draw);
if($result){
$this->success("编辑成功!", U("user/center/index"));
}else{
echo "画板编辑失败!";
}
}else{
echo "画板编辑失败!";
}
}
//用户中心删除画板
public function delete()
{
$this->check_login();
$uid = sp_get_current_userid();
$id = I("get.id", 0, 'intval');
$huaban_model = M("Huaban");
$result = $huaban_model->where(array("hb_id" => $id, "hb_uid" => $uid))->delete();
if ($result) {
$this->success("画板删除成功!", U("user/center/index"));
} else {
$this->error("画板删除失败!");
}
}
//用户的画板里面的采集详情页
public function drawDetail(){
$hid = I('get.id',0,'intval');
$huaban_model = M("Huaban");
$huaban = $huaban_model->where(array("hb_id"=>$hid))->find();
$post_model = M("Posts");
$postCount = $post_model->where(array("post_hb_id"=>$hid))->count();
$hbgz_model = M("Hbgz");
$hbgzCount = $hbgz_model->where(array("hbgz_hbid"=>$hid))->count();
$this->assign($huaban);
$this->assign("postCount",$postCount);
$this->assign("hbgzCount",$hbgzCount);
$this->display(":drawdetail");
}
//本画板下的所有采集
public function caiji(){
$hid = I('get.id',0,'intval');
$users_model = M('Users');
$post_model = M("Posts");
$count = $post_model->count();
$page = new \Think\Page($count,16);
$list = $users_model
->alias("a")
->join("tb_posts b on a.id =b.post_author")
->field("b.id as pid,a.id as uid,a.user_nicename,a.avatar,b.post_love,b.post_title")
->where(array("post_hb_id"=>$hid))
->order('post_date desc')
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($list);
}
}
<file_sep><?php
namespace User\Controller;
use Common\Controller\MemberbaseController;
class CenterController extends MemberbaseController
{
function _initialize()
{
parent::_initialize();
}
// 用户中心
//获取用户画板
public function index()
{
$fl_model = M("Xingqu_fenlei");
$categroy = $fl_model->where("xqfl_area = 3")->select();
$this->assign("category",$categroy);
$this->assign($this->user);
$this->display(':center');
}
public function caiji(){
$this->assign($this->user);
$this->display(':collect');
}
//获取用户喜欢
public function love(){
$this->assign($this->user);
$this->display(':love');
}
//获取用户标签
public function tag(){
$this->assign($this->user);
$this->display(":tag");
}
//用户标签详情页
public function tagDetail(){
$tid = I('get.id',0,'intval');
$tag_model = M("Tag");
$tag = $tag_model->where(array("tag_id"=>$tid))->find();
$tagname = $tag["tag_name"];
$this->assign("tagname",$tagname);
$tagp_model = M("Tag_posts");
$pcount = $tagp_model->where(array("tp_tag_id"=>$tid))->count();
$this->assign("pcount",$pcount);
$this->assign("tid",$tid);
$this->assign($this->user);
$this->display(":tag_detail");
}
//获取用户的粉丝
public function fans(){
$this->assign($this->user);
$this->display(":fans");
}
//获取用户创建的画板详情
public function drawDetail(){
$uid = sp_get_current_userid();
$huaban_model = M("Huaban");
$count = $huaban_model->where(array("hb_u_id" =>$uid))->count();
$page = new \Think\Page($count,16);
$Model = M(); // 实例化一个model对象 没有对应任何数据表
$xingqu = $Model ->query("Select a.hb_id ,a.hb_name,GROUP_CONCAT(id) as pidList from (select * from tb_huaban where hb_u_id='$uid') a left join tb_posts b on a.hb_id = b.post_hb_id GROUP BY hb_id limit $page->firstRow,$page->listRows");
echo json_encode($xingqu);
}
//用户创建画板
public function createDraw(){
if(IS_POST){
$uid = sp_get_current_userid();
$huaban_model = M("Huaban");
$hbname = $_POST["hbname"];
$flid = $_POST["fl"];
$data["hb_name"] = $hbname;
$data["hb_term_id"] = $flid;
$data["hb_u_id"] = $uid;
$data["hb_create_time"] = date("Y-m-d H:i:s", time());;
$huaban = $huaban_model->add($data);
if($huaban){
$this->success("画板创建成功!");
}else{
$this->error("画板创建失败!");
}
}
}
//获取用户采集的详情
public function collectDetail()
{
$uid = sp_get_current_userid();
$postsUser_model = M("Posts");
$count = $postsUser_model->where(array("post_author"=>$uid))->count();
$page = new \Think\Page($count,16);
$postsUser = $postsUser_model->where(array("post_author" => $uid))
->alias("a")
->join("tb_users c on a.post_author = c.id")
->field("a.id as pid,c.id as uid,a.post_img_url,a.post_title,a.post_love,c.user_nicename")
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($postsUser);
}
//用户中心显示用户的喜欢
public function loveView(){
$uid = sp_get_current_userid();
$love_model = M("Love");
$count = $love_model->count();
$page = new \Think\Page($count,16);
$love = $love_model->where(array("love_users_id"=>$uid))
->alias("a")
->join("tb_posts b on a.love_posts_id = b.id")
->join("tb_users c on b.post_author = c.id")
->field("b.id as pid,c.id as uid,b.post_title,b.post_love,c.user_nicename")
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($love);
}
//用户标签
public function tagView(){
$uid = sp_get_current_userid();
$Model = M();
$tag = $Model->query("select a.tag_id,a.tag_name,count(tp_post_id) as pcount from (select * from tb_tag where tag_users_id = '$uid') a left join tb_tag_posts b on a.tag_id = b.tp_tag_id group by tag_id");
echo json_encode($tag);
}
//用户标签详情
public function tagDetailView(){
$tid = I('get.id',0,'intval');
// var_dump($tid);
$tag_post_model = M("Tag_posts");
$count = $tag_post_model->where(array("tp_tag_id"=>$tid))->count();
$page = new \Think\Page($count,16);
$tag_post = $tag_post_model->where(array("tp_tag_id"=>$tid))
->alias("a")
->join("tb_posts b on a.tp_post_id = b.id")
->join("tb_users c on b.post_author =c.id")
->field("a.tp_id,b.id as pid,c.id as uid,c.user_nicename,b.post_love,b.post_title")
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($tag_post);
}
//删除单个标签
public function deleteTag(){
$tid = I('get.tid',0,'intval');
$tag_model = M("Tag");
$tag_post_model = M("Tag_posts");
$tag = $tag_model->where(array("tag_id"=>$tid))->delete();
$tag_post = $tag_post_model->where(array("tp_tag_id"=>$tid))->delete();
if($tag&&$tag_post){
echo 1;
}else{
echo 0;
}
}
//标签的批量删除
public function deleteMoreTag(){
$tids = implode(",",$_GET["tids"]);
$tag_model = M("Tag");
$tag_post_model = M("Tag_posts");
$tag = $tag_model->where("tag_id in ($tids)")->delete();
$tag_post = $tag_post_model->where("tp_tag_id in ($tids)")->delete();
if($tag==true&&$tag_post==true){
echo 1; //批量删除标签成功
}else{
echo 0; //批量删除标签失败
}
}
//用户资料编辑
public function infoCheck(){
$uid = sp_get_current_userid();
$name = $_GET["name"];
$sign = $_GET["sign"];
$data["user_nicename"] = $name;
$data["signature"] = $sign;
$user_model = M("Users");
$user = $user_model->where(array("id"=>$uid))->save($data);
if($user){
echo 1;
}else{
echo 0;
}
}
//个人中心修改密码提交
public function editPassword(){
$oldPassword = $_GET["oldpassword"];
$password = $_GET["password"];
$rePassword = $_GET["repassword"];
$uid = sp_get_current_userid();
$user_model = M("Users");
$pass = $user_model->where(array('id'=>$uid))->find();
if(sp_compare_password($oldPassword, $pass['user_pass'])){
if($password==$rePassword){
if(sp_compare_password($password, $pass['user_<PASSWORD>'])){
echo 2; //新密码和原密码相同
}else{
$data['user_pass']=sp_password($password);
$r=$user_model->where(array("id"=>$uid))->save($data);
if($r){
echo 3; //修改成功
}
else{
echo 4; //修改失败
}
}
}else{
echo 1; //两次密码输入不一致
}
}else{
echo 0;//原密码不正确
}
}
//更换手机号码
public function phoneChange(){
$phone = $_GET["phone"];
$uid = sp_get_current_userid();
$user_model = M("Users");
$users = $user_model->where(array("id"=>$uid))->find();
if($phone!=$users['mobile']){
$data["mobile"] = $phone;
$user = $user_model->where(array("id"=>$uid))->save($data);
if($user){
echo 1; //更换手机号码成功
}
else{
echo 0; //更换手机号码失败
}
}
echo 3; //修改后手机号与原手机号相同
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: Admin
* Date: 2018/1/21
* Time: 17:58
*/
namespace Portal\Controller;
use Common\Controller\HomebaseController;
class UserController extends HomebaseController
{
//获取他人的画板
public function index()
{
$uid = I('get.id',0,'intval');
$users_model = M("Users");
$users = $users_model->where(array("id"=>$uid))->select();
$this->assign("user",$users);
$this->display(':User/center');
}
//获取他人的采集
public function caiji(){
$uid = I('get.id',0,'intval');
$users_model = M("Users");
$users = $users_model->where(array("id"=>$uid))->select();
$this->assign("user",$users);
$this->display(':User/collect');
}
//获取他人的喜欢
public function love(){
$uid = I('get.id',0,'intval');
$users_model = M("Users");
$users = $users_model->where(array("id"=>$uid))->select();
$this->assign("user",$users);
$this->display(':User/love');
}
//获取他人的标签
public function tag(){
$uid = I('get.id',0,'intval');
$users_model = M("Users");
$users = $users_model->where(array("id"=>$uid))->select();
$this->assign("user",$users);
$this->display(":User/tag");
}
//他人标签详情页
public function tagDetail(){
$uid = I('get.uid',0,'intval');
$tid = I('get.tid',0,'intval');
$tag_model = M("Tag");
$tag = $tag_model->where(array("tag_id"=>$tid))->find();
$tagname = $tag["tag_name"];
$this->assign("tagname",$tagname);
$tagp_model = M("Tag_posts");
$pcount = $tagp_model->where(array("tp_tag_id"=>$tid))->count();
$users_model = M("Users");
$users = $users_model->where(array("id"=>$uid))->select();
$this->assign("user",$users);
$this->assign("pcount",$pcount);
$this->assign("tid",$tid);
$this->display(":User/tag_detail");
}
//获取他人的关注的兴趣点
public function hisInterest(){
$uid = I('get.id',0,'intval');
$users_model = M("Users");
$users = $users_model->where(array("id"=>$uid))->select();
$this->assign("user",$users);
$this->display(":User/interest");
}
//获取他人关注的用户
public function hisUser(){
$uid = I('get.id',0,'intval');
$users_model = M("Users");
$users = $users_model->where(array("id"=>$uid))->select();
$this->assign("user",$users);
$this->display(":User/user");
}
//获取他人关注的画板
public function hisDraw(){
$uid = I('get.id',0,'intval');
$users_model = M("Users");
$users = $users_model->where(array("id"=>$uid))->select();
$this->assign("user",$users);
$this->display(":User/draw");
}
//获取他人的粉丝
public function fans(){
$uid = I('get.id',0,'intval');
$users_model = M("Users");
$users = $users_model->where(array("id"=>$uid))->select();
$this->assign("user",$users);
$this->display(":User/fans");
}
//获取用户的关注数、粉丝数、采集数、画板数、喜欢数、标签数
public function userCount()
{
$uid = I('get.id',0,'intval');
$huabanUser_model = M("Huaban");
$caijiUser_model = M("Posts");
$loveUser_model = M("Love");
$tagUser_model = M("Tag");
$usergz_model = M("Yonghu_gz");
$huabanCount = $huabanUser_model->where(array("hb_u_id" => $uid))->count();
$caijiCount = $caijiUser_model->where(array("post_author" => $uid))->count();
$loveCount = $loveUser_model->where(array("love_users_id" => $uid))->count();
$tagCount = $tagUser_model->where(array("tag_users_id" => $uid))->count();
$pidCount = $usergz_model->where(array("usergz_uid_pid"=>$uid))->count();
$childCount = $usergz_model->where(array("usergz_uid_childid"=>$uid))->count();
$data["gcount"] = $pidCount;
$data["fcount"] = $childCount;
$data["hcount"] = $huabanCount;
$data["ccount"] = $caijiCount;
$data["lcount"] = $loveCount;
$data["tcount"] = $tagCount;
echo json_encode($data);
}
//获取用户创建的画板详情
public function drawDetail(){
$uid = I('get.id',0,'intval');
$huaban_model = M("Huaban");
$count = $huaban_model->where(array("hb_u_id" =>$uid))->count();
$page = new \Think\Page($count,20);
$Model = M(); // 实例化一个model对象 没有对应任何数据表
$xingqu = $Model ->query("Select a.hb_id ,a.hb_name,GROUP_CONCAT(id) as pidList from (select * from tb_huaban where hb_u_id='$uid') a left join tb_posts b on a.hb_id = b.post_hb_id GROUP BY hb_id limit $page->firstRow,$page->listRows");
echo json_encode($xingqu);
}
//获取用户采集的详情
public function collectDetail()
{
$uid = I('get.id',0,'intval');
$postsUser_model = M("Posts");
$count = $postsUser_model->where(array("post_author"=>$uid))->count();
$page = new \Think\Page($count,16);
$postsUser = $postsUser_model->where(array("post_author" => $uid))
->alias("a")
->join("tb_users c on a.post_author = c.id")
->field("a.id as pid,c.id as uid,a.post_img_url,a.post_title,a.post_love,c.user_nicename")
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($postsUser);
}
//获取用户自己的喜欢详情
public function loveView(){
$uid = I('get.id',0,'intval');
$love_model = M("Love");
$count = $love_model->count();
$page = new \Think\Page($count,16);
$love = $love_model->where(array("love_users_id"=>$uid))
->alias("a")
->join("tb_posts b on a.love_posts_id = b.id")
->join("tb_users c on b.post_author = c.id")
->field("b.id as pid,c.id as uid,b.post_title,b.post_love,c.user_nicename")
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($love);
}
//用户的画板里面的采集详情页
public function huaban(){
$hid = I('get.id',0,'intval');
$huaban_model = M("Huaban");
$huaban = $huaban_model->where(array("hb_id"=>$hid))->find();
$post_model = M("Posts");
$postCount = $post_model->where(array("post_hb_id"=>$hid))->count();
$hbgz_model = M("Hbgz");
$hbgzCount = $hbgz_model->where(array("hbgz_hbid"=>$hid))->count();
$this->assign($huaban);
$this->assign("postCount",$postCount);
$this->assign("hbgzCount",$hbgzCount);
$this->display(":huaban");
}
//本画板下的所有采集
public function huabanDetail(){
$hid = I('get.id',0,'intval');
$users_model = M('Users');
$post_model = M("Posts");
$count = $post_model->count();
$page = new \Think\Page($count,16);
$list = $users_model
->alias("a")
->join("tb_posts b on a.id =b.post_author")
->field("b.id as pid,a.id as uid,a.user_nicename,a.avatar,b.post_love,b.post_title")
->where(array("post_hb_id"=>$hid))
->order('post_date desc')
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($list);
}
//用户标签
public function tagView(){
$uid = I('get.id',0,'intval');
$Model = M();
$tag = $Model->query("select a.tag_id,a.tag_name,count(tp_post_id) as pcount from (select * from tb_tag where tag_users_id = '$uid') a left join tb_tag_posts b on a.tag_id = b.tp_tag_id group by tag_id");
echo json_encode($tag);
}
//用户标签详情
public function tagDetailView(){
$tid = I('get.id',0,'intval');
// var_dump($tid);
$tag_post_model = M("Tag_posts");
$count = $tag_post_model->where(array("tp_tag_id"=>$tid))->count();
$page = new \Think\Page($count,16);
$tag_post = $tag_post_model->where(array("tp_tag_id"=>$tid))
->alias("a")
->join("tb_posts b on a.tp_post_id = b.id")
->join("tb_users c on b.post_author =c.id")
->field("a.tp_id,b.id as pid,c.id as uid,c.user_nicename,b.post_love,b.post_title")
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($tag_post);
}
//用户关注的兴趣点详情
public function interestDetailFollow()
{
$uid = I('get.id',0,'intval');
$xqdgz_model = M("Xqd_guanzhu");
$count = $xqdgz_model->where(array("xqdgz_uid"=>$uid))->count();
$page = new \Think\Page($count,20);
$Model = M(); // 实例化一个model对象 没有对应任何数据表
$xingqu = $Model->query("select b.xq_id,b.xq_name,GROUP_CONCAT(c.id) as pidList from (select * from tb_xqd_guanzhu where xqdgz_uid='$uid') a left join tb_xingqu b on a.xqdgz_xqid = b.xq_id left join tb_posts c on b.xq_id = c.post_xq_id group by xq_id limit $page->firstRow,$page->listRows");
echo json_encode($xingqu);
}
//用户关注的用户详情
public function userDetailFollow()
{
$uid = I('get.id',0,'intval');
$usergz_model = M("Yonghu_gz");
$count = $usergz_model->where(array("usergz_uid_childid"=>$uid))->count();
$page = new \Think\Page($count,20);
$Model = M(); // 实例化一个model对象 没有对应任何数据表
$yonghu = $Model->query("select usergz_uid_childid,user_nicename,caiji_count,count(usergz_uid_childid) as huaban_count,pidList FROM
(
select usergz_uid_childid,user_nicename,count(usergz_uid_childid) as caiji_count,pidList from
(
select usergz_uid_childid,b.user_nicename ,GROUP_CONCAT(c.id) as pidList from (select usergz_uid_childid from tb_yonghu_gz where usergz_uid_pid='$uid') a
left join tb_users b on a.usergz_uid_childid = b.id
left join tb_posts c on a.usergz_uid_childid = c.post_author
) a GROUP BY usergz_uid_childid
) a
left join tb_huaban d on a.usergz_uid_childid = d.hb_u_id limit $page->firstRow,$page->listRows");
echo json_encode($yonghu);
}
//用户的粉丝详情
public function fansDetailFollow(){
$uid = I('get.id',0,'intval');
$usergz_model = M("Yonghu_gz");
$count = $usergz_model->where(array("usergz_uid_pid"=>$uid))->count();
$page = new \Think\Page($count,20);
$Model = M(); // 实例化一个model对象 没有对应任何数据表
$yonghu = $Model->query("select usergz_uid_pid,user_nicename,caiji_count,count(usergz_uid_pid) as huaban_count FROM
(
select usergz_uid_pid,user_nicename,count(usergz_uid_pid) as caiji_count from
(
select usergz_uid_pid,b.user_nicename from (select usergz_uid_pid from tb_yonghu_gz where usergz_uid_childid='$uid') a
left join tb_users b on a.usergz_uid_pid = b.id
left join tb_posts c on a.usergz_uid_pid = c.post_author
) a GROUP BY usergz_uid_pid
) a
left join tb_huaban d on a.usergz_uid_pid = d.hb_u_id GROUP BY usergz_uid_pid limit $page->firstRow,$page->listRows");
echo json_encode($yonghu);
}
//用户关注的画板详情
public function drawDetailFollow()
{
$uid = I('get.id',0,'intval');
$hbgz_model = M("Hbgz");
$count = $hbgz_model->where(array("hbgz_uid"=>$uid))->count();
$page = new \Think\Page($count,20);
$Model = M(); // 实例化一个model对象 没有对应任何数据表
$huaban = $Model->query("select b.hb_id,b.hb_name,GROUP_CONCAT(c.id) as pidList from (select * from tb_hbgz where hbgz_uid='$uid') a left join tb_huaban b on a.hbgz_hbid = b.hb_id left join tb_posts c on b.hb_id = c.post_hb_id group by hb_id limit $page->firstRow,$page->listRows");
echo json_encode($huaban);
}
//用户关注用户按钮的状态
public function userFollowStatus(){
$upid = I('get.id',0,'intval');
$uid = sp_get_current_userid();
$usergz_model = M("Yonghu_gz");
$usergz = $usergz_model->where(array("usergz_uid_pid"=>$uid,"usergz_uid_childid"=>$upid))->select();
if($usergz){
echo 1;
}else{
echo 0;
}
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: 周前
* Date: 2018/1/6
* Time: 10:04
*/
namespace User\Controller;
use Common\Controller\MemberbaseController;
class CollectController extends MemberbaseController
{
function _initialize()
{
parent::_initialize();
}
//用户中心采集列表显示
public function index()
{
$uid = sp_get_current_userid();
$huabanUser_model = M("Huaban");
$caijiUser_model = M("Posts");
$loveUser_model = M("Love");
$tagUser_model = M("Tag");
$huabanCount = $huabanUser_model->where(array("hb_u_id"=>$uid))->count();
$caijiCount = $caijiUser_model->where(array("post_author"=>$uid))->count();
$loveCount = $loveUser_model->where(array("love_users_id"=>$uid))->count();
$tagCount = $tagUser_model->where(array("tag_users_id"=>$uid))->count();
$this->assign("huabanCount",$huabanCount);
$this->assign("caijiCount",$caijiCount);
$this->assign("loveCount",$loveCount);
$this->assign("tagCount",$tagCount);
$this->assign($this->user);
$this->display(':collect');
}
//获取用户采集的详情
public function collectDetail()
{
$uid = sp_get_current_userid();
$postsUser_model = M("Posts");
$count = $postsUser_model->where(array("post_author"=>$uid))->count();
$page = new \Think\Page($count,16);
$postsUser = $postsUser_model->where(array("post_author" => $uid))
->alias("a")
->join("tb_users c on a.post_author = c.id")
->field("a.id as pid,c.id as uid,a.post_img_url,a.post_title,a.post_love,c.user_nicename")
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($postsUser);
}
//用户采集
public function do_collect()
{
}
//用户采集编辑
public function edit_collect()
{
$uid = sp_get_current_userid();
$pid = I('get.id',0,'intval');
$post_model = M("Posts");
$post = $post_model->where(array("id"=>$pid))->find();
$huaban_model = M("Huaban");
$huaban = $huaban_model->where(array("hb_u_id"=>$uid))->field("hb_id,hb_name")->select();
/* $tagpost_model = M("Tag_posts");
$tagpost = $tagpost_model->where(array("tp_post_id"))
->join("tb_tag b on a.tp_tag_id = tag_id")
->select();*/
$this->assign($post);
$this->assign("huaban",$huaban);
// $this->assign("tagpost",$tagpost);
$this->display(":edit_collect");
}
//用户采集编辑提交
public function edit_post_collect()
{
}
//用户采集删除
public function delete_collect()
{
$uid = sp_get_current_userid();
$pid = I('get.id',0,'intval');
//删除采集列表中的采集
$post_model = M("Posts");
$post = $post_model->where(array("id"=>$pid,"post_author"=>$uid))->delete();
//删除标签下面这个采集
$tag_post_model = M("Tag_posts");
$tag_post = $tag_post_model->where(array("tp_post_id"=>$pid))->delete();
//删除其他用户喜欢这个采集
$love_model = M("Love");
$love = $love_model->where(array("love_posts_id"=>$pid))->delete();
if($post==true&&$tag_post==true&&$love==true){
$this->success("采集删除成功!");
}else{
$this->error("采集删除失败!");
}
}
//用户批量删除采集
public function deleteMoreCollect(){
$pids = implode(",",$_GET["pids"]);
//删除采集列表中的采集
$post_model = M("Posts");
$post = $post_model->where("id in ($pids)")->delete();
//删除标签下面这个采集
$tag_post_model = M("Tag_posts");
$tag_post = $tag_post_model->where("tp_post_id in ($pids)")->delete();
//删除其他用户喜欢这个采集
$love_model = M("Love");
$love = $love_model->where("love_posts_id in ($pids)")->delete();
if($post==true&&$tag_post==true&&$love==true){
echo 1; //批量删除采集成功
}else{
echo 0; //批量删除采集失败
}
}
//用户自己的标签
public function label()
{
$uid = sp_get_current_userid();
$tag_model = M("Tag");
$tag = $tag_model
->where(array("tag_user_id" => $uid))
->select();
echo json_encode($tag);
}
//用户自己的喜欢
public function love()
{
$uid = sp_get_current_userid();
$love_model = M("Love");
$love = $love_model
->alias("a")
->join("tb_posts ON a.love_posts_id = tb_posts.id")
->where(array("love_users_id" => $uid))
->select();
echo json_encode($love);
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Admin
* Date: 2018/1/19
* Time: 16:14
*/
namespace Portal\Controller;
use Common\Controller\HomebaseController;
class InterestDetailController extends HomebaseController
{
//兴趣分类采集详情页
public function index(){
$flid = I('get.id',0,'intval');
$fl_model = M("Xingqu_fenlei");
$fl = $fl_model->where(array("xqfl_id"=>$flid))->find();
$xingqu_model = M("Xingqu");
$xingqu = $xingqu_model->where(array("xq_fl_id"=>$flid))->limit(5)->select();
$this->assign($fl);
$this->assign("xingqu",$xingqu);
$this->display(":category");
}
//兴趣分类画板详情页
public function huaban(){
$flid = I('get.id',0,'intval');
$fl_model = M("Xingqu_fenlei");
$fl = $fl_model->where(array("xqfl_id"=>$flid))->find();
$huaban_model = M("Huaban");
$huaban = $huaban_model->where(array("hb_xqd_id"=>$flid))->limit(5)->select();
// var_dump($huaban);
$this->assign($fl);
$this->assign("huaban",$huaban);
$this->display(":huabanfl");
}
//兴趣分类下的采集
public function interestCollect(){
$flid = I('get.id',0,'intval');
$xingqu_model = M("Xingqu");
$xingqu = $xingqu_model->where(array("xq_fl_id"=>$flid))->getfield("xq_id",true);
$ids = implode(",",$xingqu);
$users_model = M('Users');
$post_model = M("Posts");
$count = $post_model->count();
$page = new \Think\Page($count,16);
$list = $users_model
->alias("a")
->join("tb_posts b on a.id =b.post_author")
->field("b.id as pid,a.id as uid,a.user_nicename,a.avatar,b.post_title,b.post_love,b.post_img_url,b.recommended,b.post_date")
->where("post_xq_id in ($ids)")
->order('post_date desc')
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($list);
}
//画板分类下的采集
public function huabanCollect(){
$flid = I('get.id',0,'intval');
$huaban_model = M("Huaban");
$huaban = $huaban_model->where(array("hb_xqd_id"=>$flid))->getfield("hb_id",true);
$ids = implode(",",$huaban);
$users_model = M('Users');
$post_model = M("Posts");
$count = $post_model->count();
$page = new \Think\Page($count,16);
$list = $users_model
->alias("a")
->join("tb_posts b on a.id =b.post_author")
->field("b.id as pid,a.id as uid,a.user_nicename,a.avatar,b.post_love,b.post_img_url,b.recommended,b.post_date")
->where("post_hb_id in ($ids)")
->order('post_date desc')
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($list);
}
//兴趣详情页
public function interest()
{
$xid = I('get.xid',0,'intval');
// $flid = I('get.fid',0,'intval');
if($this->user){
$this->assign("isLogin",1);
}
else{
$this->assign("isLogin",0);
}
$xingqu_model = M("Xingqu");
$xingqu = $xingqu_model->where(array("xq_id"=>$xid))->find();
$flid = $xingqu["xq_fl_id"];
if($this->user){
$this->assign("isLogin",1);
}
else{
$this->assign("isLogin",0);
} $xingqus = $xingqu_model->where(array("xq_fl_id"=>$flid))->limit(5)->select();
$this->assign($xingqu);
$this->assign("xingqus",$xingqus);
$this->display(":xq_detail");
}
//兴趣详情页下的采集
public function detailCollect()
{
$xid = I('get.xid',0,'intval');
$users_model = M('Users');
$post_model = M("Posts");
$count = $post_model->count();
$page = new \Think\Page($count,16);
$list = $users_model
->alias("a")
->join("tb_posts b on a.id =b.post_author")
->field("b.id as pid,a.id as uid,a.user_nicename,a.avatar,b.post_title,b.post_love,b.post_img_url,b.recommended,b.post_date")
->where(array("post_xq_id"=>$xid))
->order('post_date desc')
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($list);
}
//判断兴趣关注状态
public function interestgz(){
$xid = I('get.id',0,'intval');
$uid = sp_get_current_userid();
$xqgz_model = M("Xqd_guanzhu");
$xqd = $xqgz_model->where(array("xqdgz_uid"=>$uid,"xqdgz_xqid"=>$xid))->find();
if($xqd){
echo 1;
}
else{
echo 0;
}
}
}<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo ($user_nicename); ?>欧澜芝的个人主页</title>
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/new.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/collect.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/palette.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/header.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/lable.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
</head>
<body>
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/collect/index');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/love/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<!--用户中心头部-->
<div class="yesterday">
<div class="yesterday_1">
<div class="yesterday_1_1">
<a href="<?php echo U('User/center/index');?>"><img src="<?php echo sp_get_user_avatar_url($avatar);?>"></a>
</div>
<div class="yesterday_1_2">
<div class="yesterday_1_2_1"><span id="fcount"></span></div>
<div class="yesterday_1_2_2"><span id="gcount"></span></div>
</div>
<div class="yesterday_1_3">
<a href="<?php echo U('User/center/fans');?>"> <div class="yesterday_1_3_1">粉丝</div></a>
<div class="yesterday_1_3_2"></div>
<a href="<?php echo U('User/follow/userFollow');?>"> <div class="yesterday_1_3_3">关注</div></a>
</div>
</div>
<div class="yesterday_2">
<div class="yesterday_2_1"><?php echo ($user_nicename); ?></div>
<div class="yesterday_2_2"><?php echo ($signature); ?></div>
</div>
<div class="yesterday_3">
<a href="<?php echo U('user/profile/edit');?>"><div class="yesterday_3_1">账号设置</div></a>
</div>
</div>
<!--红色部分-->
<div class="hongse">
<input type="hidden" name="id" id="id" value="<?php echo ($id); ?>" />
<a href="<?php echo U('User/center/index');?>">
<div class="hongse_1">
<div class="hongse_1_1" ><span id="hcount"></span></div>
<div class="hongse_1_2" >画板</div>
</div>
</a>
<a href="<?php echo U('User/center/caiji');?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1" ><span id="ccount"></span></div>
<div class="hongse_1_2" >采集</div>
</div></a>
<a href="<?php echo U('User/center/love');?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1" style="color: white;"><span id="lcount"></span></div>
<div class="hongse_1_2" style="color: white;">喜欢</div>
<div class="heng" style="width: 50px;height: 3px;background: white;margin: 0 auto;margin-top: -0.5rem"></div>
</div></a>
<a href="<?php echo U('User/center/tag');?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1"><span id="tcount"></span></div>
<div class="hongse_1_2">标签</div>
</div></a>
</div>
<!--中间部分-->
<div class="lable-detail-box">
<div class="middle-box" id="love"></div>
<div style="clear: both"></div>
</div>
<div class="nomore">
<div class="nomore_1" style="font-family: 微软雅黑;font-size:1rem" id="load">查看更多</div>
<a href="#"><i class="iconfont icon-daosanjiao" style="color: black"></i></a>
</div>
<script type="text/javascript">
//全局变量
var GV = {
ROOT: "/",
WEB_ROOT: "/",
JS_ROOT: "public/js/"
};
</script>
<!-- Placed at the end of the document so the pages load faster -->
<script src="/public/js/jquery.js"></script>
<script src="/public/js/wind.js"></script>
<script src="/themes/simplebootx/Public/assets/simpleboot/bootstrap/js/bootstrap.min.js"></script>
<script src="/public/js/frontend.js"></script>
<script>
$(function(){
$('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });
$("#main-menu li.dropdown").hover(function(){
$(this).addClass("open");
},function(){
$(this).removeClass("open");
});
$.post("<?php echo U('user/index/is_login');?>",{},function(data){
if(data.status==1){
if(data.user.avatar){
$("#main-menu-user .headicon").attr("src",data.user.avatar.indexOf("http")==0?data.user.avatar:"<?php echo sp_get_image_url('[AVATAR]','!avatar');?>".replace('[AVATAR]',data.user.avatar));
}
$("#main-menu-user .user-nicename").text(data.user.user_nicename!=""?data.user.user_nicename:data.user.user_login);
$("#main-menu-user li.login").show();
}
if(data.status==0){
$("#main-menu-user li.offline").show();
}
/* $.post("<?php echo U('user/notification/getLastNotifications');?>",{},function(data){
$(".nav .notifactions .count").text(data.list.length);
}); */
});
;(function($){
$.fn.totop=function(opt){
var scrolling=false;
return this.each(function(){
var $this=$(this);
$(window).scroll(function(){
if(!scrolling){
var sd=$(window).scrollTop();
if(sd>100){
$this.fadeIn();
}else{
$this.fadeOut();
}
}
});
$this.click(function(){
scrolling=true;
$('html, body').animate({
scrollTop : 0
}, 500,function(){
scrolling=false;
$this.fadeOut();
});
});
});
};
})(jQuery);
$("#backtotop").totop();
});
</script>
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/swiper.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/assets/js/slippry.min.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/assets/js/classie.js"></script>
<script src="/themes/simplebootx/Public/assets/js/modalEffects.js"></script>
<script type="text/javascript">
var id = $("#id").val();
console.log(id);
$.ajax({
type: "GET",
url: "/index.php?g=portal&m=user&a=userCount",
dataType: "json",
data:{
id:id
},
success:function(data){
console.log(data);
document.getElementById('hcount').innerHTML=data.hcount;
document.getElementById('ccount').innerHTML=data.ccount;
document.getElementById('lcount').innerHTML=data.lcount;
document.getElementById('tcount').innerHTML=data.tcount;
document.getElementById('fcount').innerHTML=data.fcount;
document.getElementById('gcount').innerHTML=data.gcount;
}
});
var pageIndex=1;
function getPostList(page) {
$.ajax({
type: "GET",
url: "/index.php?g=user&m=love&a=loveView&p="+page,
dataType: "json",
success: function (data) {
for (var i = 0; i < data.length; i++) {
console.log(data);
var pid = data[i].pid;
var uid = data[i].uid;
$("#love").append(
'<div class="lable-box">' +
'<div class="img-detail-box">' +
'<a href="index.php?g=&m=Article&a=posts&pid='+pid+'"><img src="index.php?g=&m=Index&a=imgCollect&id=' + pid + '"></a>' +
'</div>' +
'<div class="user-box">' +
'<div class="user-touxiang">' +
'<img src="index.php?g=user&m=public&a=avatar&id=' + uid + '">' +
'</div>' +
'<div class="title-box-right">' +
'<div class="title-left">' +
data[i].post_title +
'</div>' +
'<div class="title-right">' +
'<a href="#">' +
'<i class="iconfont icon-guanzhu" style="color: red"></i>' +
'<font id="num-like" style="color: #989998">12'+data[i].post_love+'</font>' +
'</a>' +
/* '<a href="#">' +
'<font style="float: right">' +
'<i class="iconfont icon-fenxiang"></i>' +
'</font>' +*/
'</a>' +
'</div>' +
'</div>' +
'<div class="user-name">'+data[i].user_nicename+'</div>' +
'</div>' +
'</div>'
)
}
if(data.length<16)
{
$("#load").text("╮(・o・)╭没有更多了.....");
}
pageIndex++;
}
});
}
getPostList(pageIndex);
$("#load").click(function()
{
getPostList(pageIndex);
});
$(function() {
$(".tags_enter").blur(function() { //焦点失去触发
var txtvalue=$(this).val().trim();
if(txtvalue!=''){
addTag($(this));
$(this).parents(".tags").css({"border-color": "#d5d5d5"})
}
}).keydown(function(event) {
var key_code = event.keyCode;
var txtvalue=$(this).val().trim();
if (key_code == 13&& txtvalue != '') { //enter
addTag($(this));
}
if (key_code == 32 && txtvalue!='') { //space
addTag($(this));
}
});
$(".close").live("click", function() {
$(this).parent(".tag").remove();
});
$(".tags").click(function() {
$(this).css({"border-color": "#d5d5d5"})
}).blur(function() {
$(this).css({"border-color": "#d5d5d5"})
})
})
function addTag(obj) {
var tag = obj.val();
if (tag != '') {
var i = 0;
$(".tag").each(function() {
if ($(this).text() == tag + "×") {
$(this).addClass("tag-warning");
setTimeout("removeWarning()", 400);
i++;
}
})
obj.val('');
if (i > 0) { //说明有重复
return false;
}
$("#form-field-tags").before("<span class='tag'>" + tag + "<button class='close' type='button'>×</button></span>"); //添加标签
}
}
function removeWarning() {
$(".tag-warning").removeClass("tag-warning");
}
</script>
<script type="text/javascript">
var login = document.getElementById('login');
/*var uploadphoto = document.getElementById('uploadphoto');*/
var over = document.getElementById('over');
function show()
{
login.style.display = "block";
/*uploadphoto.style.display="block";*/
over.style.display = "block";
}
function hide()
{
login.style.display = "none";
/* uploadphoto.style.display="none";*/
over.style.display = "none";
}
$(".nav-box .right-menu .close-menu").click(function(){
$(".login-ul").slideUp();
$(".nav-box-ul").slideUp();
$(this).parent().removeClass("active");
});
$(".nav-box .right-menu .open-menu").click(function(){
$(".login-ul").slideDown();
$(".nav-box-ul").slideDown();
$(this).parent().addClass("active");
});
</script>
</body>
</html><file_sep><?php
/**
* Created by PhpStorm.
* User: 周前
* Date: 2018/1/7
* Time: 18:59
*/
namespace Portal\Controller;
use Common\Controller\HomebaseController;
use Portal\Model\XingquModel;
/**
* 最新
*/
class NewestController extends HomebaseController
{
public function index(){
$category_model = M("Xingqu_fenlei");
$one = $category_model->where("xqfl_area = 1")->select();
$two = $category_model->where("xqfl_area = 2")->select();
$three= $category_model->where("xqfl_area = 3")->select();
$xingqu_model = M("Xingqu");
$xingqu = $xingqu_model->limit(4)->select();
$this->assign("one",$one);
$this->assign("two",$two);
$this->assign("three",$three);
$this->assign("xingqu",$xingqu);
$this->display(":newest");
}
//最新页的全部采集
public function collect(){
$users_model = M('Users');
$post_model = M("Posts");
$count = $post_model->count();
$page = new \Think\Page($count,16);
$list = $users_model
->alias("a")
->join("tb_posts b on a.id =b.post_author")
->field("b.id as pid,a.id as uid,a.user_nicename,a.avatar,b.post_love,b.post_title,b.post_img_url,b.recommended,b.post_date")
->order('post_date desc')
->where("post_xq_id != 0")
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($list);
}
//获取兴趣图片
public function imgXingqu(){
$xingqu_model = M("Xingqu");
$id=I("get.id",0,"intval");
$xingqu_img = $xingqu_model->field("xq_img")->where(array("xq_id" =>$id))->find();
$img = $xingqu_img['xq_img'];
$should_show_default=false;
if(empty($img)){
$should_show_default=true;
}else {
if (strpos($img, "http") === 0) {
header("Location: $img");
exit();
} else {
$img_dir = C("UPLOADPATH");
$img = $img_dir . $img;
if (file_exists($img)) {
$imageInfo = getimagesize($img);
if ($imageInfo !== false) {
$fp = fopen($img, "r");
$file_size = filesize($img);
$mime = $imageInfo['mime'];
header("Content-type: $mime");
header("Accept-Length:" . $file_size);
$buffer = 259 * 313;
$file_count = 0;
//向浏览器返回数据
while (!feof($fp) && $file_count < $file_size) {
$file_content = fread($fp, $buffer);
$file_count += $buffer;
echo $file_content;
flush();
ob_flush();
}
fclose($fp);
} else {
$should_show_default = true;
}
} else {
$should_show_default = true;
}
}
}
if($should_show_default){
$imageInfo = getimagesize("public/images/haibao.png");
if ($imageInfo !== false) {
$mime=$imageInfo['mime'];
header("Content-type: $mime");
echo file_get_contents("public/images/haibao.png");
}
}
exit();
}
}<file_sep><?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
class XingqufenleiController extends AdminbaseController{
protected $xingqufenlei_model;
protected $xingqu_model;
public function _initialize()
{
parent::_initialize();
$this->xingqufenlei_model = D("Common/XingquFenlei");
$this->xingqu_model=D("Common/Xingqu");
}
///首页列表
public function index()
{
$User = M('XingquFenlei'); // 实例化User对象
$count=$User->count();
$page = $this->page($count, 10);
$xingqus = $User->limit($page->firstRow.','.$page->listRows)
->order('xqfl_id')
->select();
$this->assign('xingqus',$xingqus);
$this->assign("page", $page->show('Admin'));// 赋值分页输出
$this->display();
}
public function add()
{
$this->display('add');
}
public function add_post()
{
if(IS_POST){
if ($this->xingqufenlei_model->create()!==false) {
if ($this->xingqufenlei_model->add()!==false) {
$this->success("添加成功!", U("xingqufenlei/index"));
} else {
$this->error("添加失败!");
}
} else {
$this->error($this->xingqufenlei_model->getError());
}
}
}
// 兴趣分类删除
public function delete(){
$id = I("get.id", 0, 'intval');
if ($this->xingqufenlei_model->delete($id) !== false) {
$slide_obj=M("Xingqu");
$slide_obj->where(array('xq_fl_id'=>$id))->save(array("xq_fl_id"=>0));
$this->success("删除成功!");
} else {
$this->error("删除失败!");
}
}
//兴趣分类编辑
public function edit()
{
$id = I("get.id",0,'intval');
$xingqus=$this->xingqufenlei_model->where(array('xqfl_id'=>$id))->find();
$this->assign($xingqus);
$this->display();
}
public function edit_post()
{
if(IS_POST){
if ($this->xingqufenlei_model->create()!==false) {
if ($this->xingqufenlei_model->save()!==false) {
$this->success("修改成功!", U("xingqufenlei/index"));
} else {
$this->error("修改失败!");
}
} else {
$this->error($this->xingqufenlei_model->getError());
}
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: Admin
* Date: 2018/1/7
* Time: 16:44
*/
namespace User\Controller;
use Common\Controller\MemberbaseController;
/*
* 用户关注行为
*/
class InterestController extends MemberbaseController
{
//用户关注的兴趣点
public function interest()
{
$uid = sp_get_current_userid();
$xqUsers_model = M('Xqd_guanzhu');
$xqgz = $xqUsers_model
->alias("a")
->join("tb_xingqu ON a.xqdgz_xqid = tb_xingqu.xq_id")
->where(array("xqdgz_uid" => $uid))
->select();
echo json_encode($xqgz);
}
//用户关注的用户
public function user()
{
$uid = sp_get_current_userid();
$usergz_model = M('Yonghu_gz');
$usergz = $usergz_model
->alias("a")
->join("tb_users ON a.usergz_uid_childid = tb_users.id")
->where(array("usergz_uid_pid" => $uid))
->select();
echo json_encode($usergz);
}
//用户点击关注兴趣点
public function do_interest()
{
$session_user = session('user');
if (!empty($session_user)) {
$uid = session("user.id");
$xid = I('get.xid', 0, 'intval');;
$xqgz_model = M("Xqd_guanzhu");
$xqgz = $xqgz_model->where(array("xqdgz_uid"=>$uid,"xqdgz_xqid"=>$xid))->find();
if($xqgz){
$this->error("亲,您已经关注过啦!");
}else{
$xqdgz["xqdgz_uid"] = $uid;
$xqdgz["xqdgz_xqid"] = $xid;
$xqdgz["xqdgz_create_time"] = time();
$result = $xqgz_model->add($xqdgz);
if($result){
$this->success("关注兴趣点成功!");
}else{
$this->error("关注兴趣点失败!");
}
}
}
}
}<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>室内设计</title>
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/palette.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/design.css">
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/lable.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/collect.css">
<link href="/themes/simplebootx/Public/new/css/share.css" rel="stylesheet" type="text/css"><!--分享-->
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<style>
@media (min-width:1020px)and (max-width:1620px){
.middle{
width: 87%;
height: auto;
margin: 0 auto;
}
}
.lable-box:hover .following{
display: block;
}
.lable-box:hover a{
text-decoration: none;
}
.following{
position: relative;
bottom: 410px;
width: 30%;
height: 2.5rem;
border: 1px solid grey;
z-index: 99;
color: black;
border-radius: 5px;
left: 65%;
background: rgba(233,233,233,0.8);
outline: medium;
display: none;
}
.following:hover{
background: rgba(233,233,233,0.9);
-webkit-box-shadow: 1px 1px 4px rgba(0,0,0,0.4);
-moz-box-shadow: 1px 1px 4px rgba(0,0,0,0.4);
box-shadow: 1px 1px 4px rgba(0,0,0,0.4);
}
</style>
</head>
<body>
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/collect/index');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/love/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<div class="shineisheji" style="margin-top:68px">
<input type="hidden" id="hid" value="<?php echo ($hb_id); ?>" name="hb_id">
<div class="interior">
<div class="interior-1"><?php echo ($hb_name); ?></div>
<div class="interior-2">
<a href="#" style="text-decoration: none"><div class="interior-2-1"><div class="interior-2-4"><img src="/themes/simplebootx/Public/new/image/huaban.png"></div><li><?php echo ($postCount); ?>采集</li></div></a>
<div class="interior-2-2"></div>
<a href="#" style="text-decoration: none"> <div class="interior-2-3"><div class="interior-2-5"><img src="/themes/simplebootx/Public/new/image/eye.png"></div><li><?php echo ($hbgzCount); ?>关注</li></div></a>
</div>
</div>
<div class="compiles">
<div class="dropdown-2">
<div class="dropbtn"><div class="compile"><a href="javascript:void(0)" style="text-decoration: none;color: #A0A1A0;"><div class="compile-3"id="share" >分享<img src="/themes/simplebootx/Public/new/image/enjoy.png"></div></a></div></div>
<!--<div class="dropdown-1">
<div class="dropdown-content" style="margin-top: 20px;margin-left: -20px;z-index: 9999" >
<div class="jiantou" style="width: 15px;height: 15px;background: #F9F9F9;position: absolute;right: 20px;margin-top: -5px;z-index: 1;transform:rotate(60deg);
-ms-transform:rotate(60deg); /* IE 9 */
-moz-transform:rotate(60deg); /* Firefox */
-webkit-transform:rotate(60deg); /* Safari 和 Chrome */
-o-transform:rotate(60deg); /* Opera */"></div>
<a href="#"style="text-decoration: none;margin-top: 1rem"><img src="/themes/simplebootx/Public/new/image/bo.png"> 腾讯微博</a>
<a href="#"style="text-decoration: none;"><img src="/themes/simplebootx/Public/new/image/Q.png"> QQ好友</a>
<a href="#"style="text-decoration: none;"><img src="/themes/simplebootx/Public/new/image/douban.png"> 豆瓣</a>
<a href="#"style="text-decoration: none;"><img src="/themes/simplebootx/Public/new/image/renren.png"> 人人网</a>
</div>
</div>-->
</div>
<!-- <div class="compile-1"><a href="#"style="text-decoration: none; color: #A0A1A0;"><li>批量处理</li></a></div>
<div class="compile-2"><a href="<?php echo U('User/draw/edit_draw',array('id'=>$hb_id));?>"style="text-decoration: none; color: #A0A1A0;"><li>编辑画板</li></a></div>-->
</div>
</div>
<!--内容-->
<div class="lable-detail-box">
<div class="middle-box" id="caiji-box">
</div>
</div>
<div style="clear: both"></div>
</div>
<!--没有更多-->
<div class="nomore" id="load">
<div class="nomore_1" style="font-family: 微软雅黑;font-size:1.4rem" >╮(╯﹏╰)╭ 查看更多</div>
<a href="#"><i class="iconfont icon-daosanjiao" style="color: black"></i></a>
</div>
<script type="text/javascript">
//全局变量
var GV = {
ROOT: "/",
WEB_ROOT: "/",
JS_ROOT: "public/js/"
};
</script>
<!-- Placed at the end of the document so the pages load faster -->
<script src="/public/js/jquery.js"></script>
<script src="/public/js/wind.js"></script>
<script src="/themes/simplebootx/Public/assets/simpleboot/bootstrap/js/bootstrap.min.js"></script>
<script src="/public/js/frontend.js"></script>
<script>
$(function(){
$('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });
$("#main-menu li.dropdown").hover(function(){
$(this).addClass("open");
},function(){
$(this).removeClass("open");
});
$.post("<?php echo U('user/index/is_login');?>",{},function(data){
if(data.status==1){
if(data.user.avatar){
$("#main-menu-user .headicon").attr("src",data.user.avatar.indexOf("http")==0?data.user.avatar:"<?php echo sp_get_image_url('[AVATAR]','!avatar');?>".replace('[AVATAR]',data.user.avatar));
}
$("#main-menu-user .user-nicename").text(data.user.user_nicename!=""?data.user.user_nicename:data.user.user_login);
$("#main-menu-user li.login").show();
}
if(data.status==0){
$("#main-menu-user li.offline").show();
}
/* $.post("<?php echo U('user/notification/getLastNotifications');?>",{},function(data){
$(".nav .notifactions .count").text(data.list.length);
}); */
});
;(function($){
$.fn.totop=function(opt){
var scrolling=false;
return this.each(function(){
var $this=$(this);
$(window).scroll(function(){
if(!scrolling){
var sd=$(window).scrollTop();
if(sd>100){
$this.fadeIn();
}else{
$this.fadeOut();
}
}
});
$this.click(function(){
scrolling=true;
$('html, body').animate({
scrollTop : 0
}, 500,function(){
scrolling=false;
$this.fadeOut();
});
});
});
};
})(jQuery);
$("#backtotop").totop();
});
</script>
<!--script-->
<!-- Initialize Swiper -->
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/classie.js"></script>
<script src="/themes/simplebootx/Public/new/js/modalEffects.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script type="text/javascript" src="/themes/simplebootx/Public/new/js/share.js"></script><!--分享-->
<script>
var hid = $("#hid").val();
console.log(hid);
var pageIndex=1;
function getPostList(page) {
$.ajax({
type: "GET",
url: "/index.php?g=Portal&m=user&a=huabanDetail&p="+page,
dataType: "json",
data: {
id: hid
},
success: function (data) {
console.log(data);
for(var i=0;i<data.length;i++) {
var pid = data[i].pid;
var uid = data[i].uid;
$("#caiji-box").append(
'<div class="lable-box">' +
'<div class="img-detail-box">' +
'<a href="index.php?g=&m=Article&a=posts&pid='+pid+'"><img src="index.php?g=&m=Index&a=imgCollect&id=' + pid + '"></a>' +
'</div>' +
'<div class="user-box">' +
'<a href="index.php?g=Portal&m=user&a=index&id='+uid+'">'+
'<div class="user-touxiang">' +
'<img src="index.php?g=user&m=public&a=avatar&id=' + uid + '">' +
'</div></a>' +
'<div class="title-box-right">' +
'<div class="title-left">' +
data[i].post_title +
'</div>' +
'<div class="title-right">' +
'<a href="#">' +
'<i class="iconfont icon-guanzhu" style="color: red"></i>' +
'<font id="num-like" style="color: #989998">'+data[i].post_love+'</font>' +
'</a>' +
/* '<a href="#">' +
'<font style="float: right">' +
'<i class="iconfont icon-fenxiang"></i>' +
'</font>' +*/
'</a>' +
'</div>' +
'</div>' +
'<div class="user-name">'+data[i].user_nicename+'</div>' +
'</div>' +
'</div>'
)
}
if(data.length<16)
{
$("#load").text("╮(・o・)╭没有更多了.....");
}
pageIndex++;
}
});
}
getPostList(pageIndex);
$("#load").click(function()
{
getPostList(pageIndex);
});
var login = document.getElementById('login');
/*var uploadphoto = document.getElementById('uploadphoto');*/
var over = document.getElementById('over');
function show()
{
login.style.display = "block";
/*uploadphoto.style.display="block";*/
over.style.display = "block";
}
function hide()
{
login.style.display = "none";
/* uploadphoto.style.display="none";*/
over.style.display = "none";
}
$(".nav-box .right-menu .close-menu").click(function(){
$(".login-ul").slideUp();
$(".nav-box-ul").slideUp();
$(this).parent().removeClass("active");
});
$(".nav-box .right-menu .open-menu").click(function(){
$(".login-ul").slideDown();
$(".nav-box-ul").slideDown();
$(this).parent().addClass("active");
});
$('#share').shareConfig({
Shade : true, //是否显示遮罩层
Event:'click', //触发事件
Content : 'Share', //内容DIV ID
Title : '分享给朋友' //显示标题
});
</script>
</body>
</html><file_sep><?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
class XingquController extends AdminbaseController{
protected $xingqu_model;
protected $posts_model;
protected $xingqufenlei_model;
///首页列表
public function _initialize()
{
parent::_initialize();
$this->xingqu_model = D("Common/Xingqu");
$this->xingqufenlei_model = D("Common/XingquFenlei");
$this->posts_model=D("Common/Posts");
}
public function index()
{
$cates=array(
array("xqfl_id"=>"0","xqfl_name"=>"默认分类"),
);
$xqfls=$this->xingqufenlei_model->field("xqfl_id,xqfl_name")
->select();
if($xqfls){
$xqfls=array_merge($cates,$xqfls);
}else{
$xqfls=$cates;
}
$this->assign("xqfls",$xqfls);
$where=array();
$id = I('post.xqfl_id',0,'intval');
if(!empty($id)){
$where=array('xq_fl_id'=>$id);
}
$this->assign("xq_fl_id",$id);
$User = M('Xingqu'); // 实例化User对象
$count=$User->count();
$page = $this->page($count, 10);
$xingqu = $User->limit($page->firstRow.','.$page->listRows)
->where($where)
->alias("a")
->join("tb_xingqu_fenlei ON a.xq_fl_id=tb_xingqu_fenlei.xqfl_id")
->order('xq_id')
->select();
$this->assign('xingqu',$xingqu);
$this->assign("page", $page->show('Admin'));// 赋值分页输出
$this->display();
}
//兴趣添加
public function add()
{
$xqfls=$this->xingqufenlei_model->field("xqfl_id,xqfl_name")->select();
$this->assign("xqfls",$xqfls);
$this->display();
}
public function add_post()
{
if(IS_POST){
if ($this->xingqu_model->create()!==false) {
if ($this->xingqu_model->add()!==false) {
$this->success("添加成功!", U("xingqu/index"));
} else {
$this->error("添加失败!");
}
} else {
$this->error($this->xingqu_model->getError());
}
}
}
// 兴趣编辑
public function edit(){
$xqfls=$this->xingqufenlei_model->field("xqfl_id,xqfl_name")->select();
$id = I("get.id",0,'intval');
$xq=$this->xingqu_model->where(array('xq_id'=>$id))->find();
$this->assign($xq);
$this->assign("xqfls",$xqfls);
$this->display();
}
// 兴趣编辑提交
public function edit_post(){
if(IS_POST){
if ($this->xingqu_model->create()!==false) {
if ($this->xingqu_model->save()!==false) {
$this->success("保存成功!", U("xingqu/index"));
} else {
$this->error("保存失败!");
}
} else {
$this->error($this->xingqu_model->getError());
}
}
}
// 兴趣删除
public function delete(){
if(isset($_POST['ids'])){
$ids = implode(",", $_POST['ids']);
$data['slide_status']=0;
if ($this->xingqu_model->where("xq_id in ($ids)")->delete()!==false) {
$this->success("删除成功!");
} else {
$this->error("删除失败!");
}
}else{
$id = I("get.id",0,'intval');
if ($this->xingqu_model->delete($id)!==false) {
$this->success("删除成功!");
} else {
$this->error("删除失败!");
}
}
}
//兴趣内容
public function content()
{
$id = I("get.id",0,'intval');
$User = M('Xingqu'); // 实例化User对象
$count=$User->count();
$page = $this->page($count, 10);
$xingqu = $User->limit($page->firstRow.','.$page->listRows)
->alias("a")
->join("tb_posts ON a.xq_id=tb_posts.post_xq_id")
->where(array("post_xq_id"=>$id))
->select();
$this->assign('xingqu',$xingqu);
$this->assign("page", $page->show('Admin'));// 赋值分页输出
$this->display();
}
//兴趣内容编辑
public function edits()
{
$xingqu=$this->xingqu_model->select();
$id = I("get.id",0,'intval');
$posts=$this->posts_model
->where(array('id'=>$id))->find();
$this->assign($posts);
$this->assign("xingqu",$xingqu);
$this->display();
}
// 兴趣内容编辑提交
public function edits_post(){
if(IS_POST){
$id = I("post.id",0,'intval');
if ($this->posts_model->create()!==false) {
if ($this->posts_model->where("id = $id")->save()!==false) {
$this->success("保存成功!", U("xingqu/content"));
} else {
$this->error("保存失败!");
}
} else {
$this->error($this->posts_model->getError());
}
}
}
//兴趣内容删除
public function deletes(){
$id = I("get.id",0,'intval');
//var_dump($id);
if ($this->posts_model->where("id = $id")->delete()!==false) {
$this->success("删除成功!", U("xingqu/content"));
} else {
$this->error("删除失败!");
}
}
}<file_sep><?php if (!defined('THINK_PATH')) exit();?><html><!DOCTYPE HTML>
<head>
<title>欧兰芝</title>
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/swiper.min.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
<style>
body{
background-image: url("/themes/simplebootx/Public/new/image/hb-edit-bg.png");
background-size: cover;
}
.dropdown:hover .dropdown-menu {
display: block;
}
.dropdown-menu li a:hover{
background: #C1A062;
}
.dropdown-toggle-touxiang img:hover{
opacity: 0.9;
}
.tip-login{
width: auto;
height: auto;
position:absolute;
top:50%;
left:50%;
margin:-230px 0 0 -315px;
}
.info-tip{
width: 100%;
height: auto;
position: relative;
z-index: 9;
text-align: center;
font-size: 5rem;
color: #B25900;
font-family: 华文行楷;
top:-20rem
}
.tishi{
width: auto;
height: auto;
position: relative;
z-index: 9;
font-size: 2.5rem;
top: 2.5rem;
text-align: center;
text-shadow: -1px -1px 1px #fff, 1px 1px 1px #fff;
}
@media screen and (max-width: 468px) {
.dropdown:hover .dropdown-menu {
display: none;
}
.tip-login{
width: 100%;
height: auto;
left: 0%;
margin-left: 0;
margin-top: -12rem;
}
.tip-login img{
max-width: 100%;
}
.tishi{
font-size: 2.5rem;
}
.info-tip{
font-size: 3rem;
top: -14rem;
}
}
</style>
</head>
<body class="met-navfixed">
<!--[if lte IE 8]>
<div class="text-center padding-top-50 padding-bottom-50 bg-blue-grey-100">
<p class="browserupgrade font-size-18">你正在使用一个<strong>过时</strong>的浏览器。请<a href="http://browsehappy.com/" target="_blank">升级您的浏览器</a>,以提高您的体验。</p>
</div>
<![endif]-->
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/collect/index');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/love/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<div class="tip-login">
<img src="/themes/simplebootx/Public/new/image/tip-ban.fw.png" style="max-width: 100%">
<?php if(isset($message)): ?><div class="info-tip"><?php echo($message); ?>(^_^)</div>
<?php else: ?>
<div class="info-tip"><?php echo($error); ?>(>﹏<)</div><?php endif; ?>
<div class="tishi">欧兰芝温馨提示:页面自动<a id="href" href="<?php echo($jumpUrl); ?>"> 跳转 </a>等待时间:<b id="wait"><?php echo($waitSecond); ?></b></div>
</div>
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/assets/js/classie.js"></script>
<script src="/themes/simplebootx/Public/assets/js/modalEffects.js"></script>
<!-- Initialize Swiper -->
<script>
$(".nav-box .right-menu .close-menu").click(function(){
$(".login-ul").slideUp();
$(".nav-box-ul").slideUp();
$(this).parent().removeClass("active");
});
$(".nav-box .right-menu .open-menu").click(function(){
$(".login-ul").slideDown();
$(".nav-box-ul").slideDown();
$(this).parent().addClass("active");
});
(function(){
var wait = document.getElementById('wait'),href = document.getElementById('href').href;
var interval = setInterval(function(){
var time = --wait.innerHTML;
if(time <= 0) {
location.href = href;
clearInterval(interval);
};
}, 1000);
})();
</script>
</body>
</html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>手机号注册</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/register.css">
<link rel="stylesheet" media="screen and (max-width: 600px)" href="/themes/simplebootx/Public/new/css/small.css" />
<link rel="stylesheet" href="/themes/simplebootx/Public/new/js/layer/theme/default/layer.css">
</head>
<body>
<div class="reg-box">
<div class="logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="wanshanxinxi">
<div class="wanshanxinxi_p">
<p>欢迎您注册欧澜芝!请使用手机号和密码来完成注册。</p>
</div>
<div class="form1">
<div class="div1_form">
<div class="div2_form"><p>手机号:</p></div>
<div class="div3_form">
<input type="text" name="phone" id="phone" >
</div>
</div>
</div>
<div class="form1">
<div class="div1_form">
<div class="div2_form"><p>昵称:</p></div>
<div class="div3_form">
<input type="text" name="name" id="name">
</div>
</div>
</div>
<div class="form1">
<div class="div1_form">
<div class="div2_form"><p>密码:</p></div>
<div class="div3_form">
<input type="password" name="password" id="password">
</div>
</div>
</div>
<div class="form1">
<div class="div1_form">
<div class="div2_form"><p>确认密码:</p></div>
<div class="div3_form">
<input type="password" name="repassword" id="repassword" >
</div>
</div>
</div>
</div>
<div class="yanzhengma">
</div>
<div class="bt">
<input type="submit" onclick="check()" value="注册新用户" style="width: 8rem; height: 2.5rem;border:0px;
background-color: #FF4562;border-radius: 5px;font-size:1.2rem;color: white" >
</div>
</div>
</body>
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/new/js/layer/layer.js"></script>
<script src="/themes/simplebootx/Public/new/js/classie.js"></script>
<script src="/themes/simplebootx/Public/new/js/modalEffects.js"></script>
<script>
function check(){
var phone = $("#phone").val();
var name = $("#name").val();
var password = $("#password").val();
var repassword = $("#repassword").val();
var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
if(!phone){
layer.msg('欧澜芝提醒:手机号不能为空', {icon: 2});
return false;
}
if(!(/^1[34578]\d{9}$/.test(phone))){
layer.msg('欧澜芝提醒:手机号不合法"', {icon: 2});
return false;
}
if(!name){
layer.msg('欧澜芝提醒:昵称不能为空', {icon: 2});
return false;
}
if(!password&&!repassword){
layer.msg('欧澜芝提醒:密码不能为空!', {icon: 2});
return false;
}
if(password!=repassword){
layer.msg('欧澜芝提醒:两次密码输入不一致!', {icon: 2});
return false;
}
$.ajax({
type: "GET",
url: "/index.php?g=User&m=login&a=mobileRegister",
dataType: "json",
data:{
phone:phone,
name:name,
password:<PASSWORD>
},
success:function(data){
console.log(data);
if(data==5){
layer.msg('欧澜芝提醒:该手机号已被注册!', {icon: 2});
return false;
}
if(data.status==1){
layer.msg('欧澜芝提醒:恭喜您注册成功!', {icon: 1});
window.location.href=data.url
return true;
}
}
})
}
</script>
</html><file_sep><?php
/**
* Created by PhpStorm.
* User: Admin
* Date: 2018/1/13
* Time: 10:41
*/
namespace Portal\Controller;
use Common\Controller\HomebaseController;
use Portal\Model\XingquModel;
/**
* 活动
*/
class ActivityController extends HomebaseController{
public function index(){
$activity_model = M("Activity");
$activity = $activity_model->select();
$activityRecommend = $activity_model->where("hd_recommend=1")->select();
$this->assign("activity",$activity);
$this->assign("activityRecommend",$activityRecommend);
$this->display(":activity");
}
//获取活动图片地址
public function imgActivity(){
$activity_model = M("Activity");
$id=I("get.id",0,"intval");
$activity_img = $activity_model->field("hd_img_url")->where(array("id" =>$id))->find();
$img = $activity_img['hd_img_url'];
$should_show_default=false;
if(empty($img)){
$should_show_default=true;
}else {
if (strpos($img, "http") === 0) {
header("Location: $img");
exit();
} else {
$img_dir = C("UPLOADPATH");
$img = $img_dir . $img;
if (file_exists($img)) {
$imageInfo = getimagesize($img);
if ($imageInfo !== false) {
$fp = fopen($img, "r");
$file_size = filesize($img);
$mime = $imageInfo['mime'];
header("Content-type: $mime");
header("Accept-Length:" . $file_size);
$buffer = 259 * 313;
$file_count = 0;
//向浏览器返回数据
while (!feof($fp) && $file_count < $file_size) {
$file_content = fread($fp, $buffer);
$file_count += $buffer;
echo $file_content;
flush();
ob_flush();
}
fclose($fp);
} else {
$should_show_default = true;
}
} else {
$should_show_default = true;
}
}
}
if($should_show_default){
$imageInfo = getimagesize("public/images/haibao.png");
if ($imageInfo !== false) {
$mime=$imageInfo['mime'];
header("Content-type: $mime");
echo file_get_contents("public/images/haibao.png");
}
}
exit();
}
}<file_sep><?php
/*
*/
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <<EMAIL>>
// +----------------------------------------------------------------------
namespace Portal\Controller;
use Common\Controller\HomebaseController;
/**
* 首页
*/
class GatherController extends HomebaseController
{
//采集页面
public function index()
{
$userInfo=session('user');
if(!$userInfo)
{
$url="Location:/index.php?g=user&m=login&a=index&redirecturl="."https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
header($url);
}
else{
$Huaban = M("Huaban");
$data["hb_u_id"]=$userInfo["id"];
$list=$Huaban->where($data)->order('hb_id desc')->select();
//var_dump($list);
$this->assign("tag_users_id",$userInfo["id"]);
$this->assign("list",$list);
$this->assign("media",$_GET["media"]);
$this->assign("post_source",$_GET["url"]);
$this->assign("description",$_GET["description"]);
$this->display();
}
}
//批量采集页面
public function caijiAll()
{
$userInfo=session('user');
$imgList=$_POST["params"];
if(!$userInfo)
{
$url="/index.php?g=user&m=login&a=index&redirecturl="."https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo "<form style='display:none;' id='form1' name='form1' method='post' action='".$url."'><input name='params' type='text' value='{$imgList}' /></form><script type='text/javascript'>function load_submit(){document.form1.submit()}load_submit();</script>";
}
else{
$Huaban = M("Huaban");
$data["hb_u_id"]=$userInfo["id"];
$list=$Huaban->where($data)->order('hb_id desc')->select();
$this->assign("tag_users_id",$userInfo["id"]);
$this->assign("list",$list);
$this->assign("imgList",$imgList);
$this->display();
}
}
//插件下载页面
public function plugin()
{
$this->display();
}
//创建画板接口
public function addHuaban()
{
$Huaban = M("Huaban");
$userInfo=session('user');
$data["hb_name"]=$_POST["hb_name"];
$data["hb_u_id"]=$userInfo["id"];
$rs=$Huaban->where($data)->find();
$rsList=[];
if($rs)
{
$rsList["code"]=1001;
}
else
{
$dataAdd["hb_u_id"]=$userInfo["id"];
$dataAdd["hb_name"]=$_POST["hb_name"];
$dataAdd["hb_create_time"]=date("Y-m-d H:i:s");
$rsId=$Huaban->add($dataAdd);
$data["hb_u_id"]=$userInfo["id"];
$dataFind["hb_u_id"]=$userInfo["id"];
$list=$Huaban->where($dataFind)->order('hb_id desc')->select();
$rsList["code"]=1000;
$rsList["data"]=$list;
}
echo json_encode($rsList);
}
//采集信息提交
public function addCaiji(){
$url=$_POST["post_yl_img_url"];
$userInfo=session('user');
$Posts = M("Posts");
$dataPosts["post_author"]=$userInfo["id"];
$dataPosts["post_yl_img_url"]=$url;
$rsFind=$Posts->where($dataPosts)->find();
if($rsFind)
{
echo -1;
}
else{
$houzui=".".explode("/",getimagesize($url)["mime"])[1];
$filename=uniqid().rand(1000,9999).$houzui;
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt ( $ch, CURLOPT_URL, $url );
ob_start ();
curl_exec ( $ch );
$return_content = ob_get_contents ();
ob_end_clean ();
$return_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
$fp=@fopen("data/upload/downloadImg/".$filename,"a"); //将文件绑定到流
if($fp){
fwrite($fp,$return_content); //写入文件}
$addData["post_img_url"]="downloadImg/".$filename;
$addData["post_yl_img_url"]=$url;
$addData["post_title"]=$_POST["post_miaoshu"];
$addData["post_hb_id"]=$_POST["post_hb_id"];
$addData["post_source"]=$_POST["post_source"];
$addData["post_author"]=$userInfo["id"];
$addData["post_date"]=date("Y-m-d H:i:s");
$rs=$Posts->add($addData);
if($rs)
{
$Tag = M("tag");
$addAllData=json_decode($_POST["tag_list"],1);
$Tag_posts = M("Tag_posts");
for($i=0;$i<count($addAllData);$i++)
{
$rsFind=$Tag->where($addAllData[$i])->find();
$data1["tp_post_id"]=$rs;
if($rsFind)
{
$data1["tp_tag_id"]=$rsFind["tag_id"];
$rs1=$Tag_posts->add($data1);
}
else
{
$addAllData[$i]["tag_create_time"]=date("Y-m-d H:i:s");
$tagAddRsId=$Tag->add($addAllData[$i]);
$data1["tp_tag_id"]=$tagAddRsId;
$rs1=$Tag_posts->add($data1);
}
}
echo 1;
}
else{
echo 0;
}
}
}
}
//批量采集信息提交
public function addCaijiList(){
$userInfo=session('user');
$Posts = M("Posts");
$imgList=json_decode($_POST["img_list"],1);
for($i=0;$i<count($imgList);$i++)
{
$url=$imgList[$i]["post_yl_img_url"];
$dataPosts["post_author"]=$userInfo["id"];
$dataPosts["post_yl_img_url"]=$url;
$rsFind=$Posts->where($dataPosts)->find();
if(!$rsFind)
{
$houzui=".".explode("/",getimagesize($url)["mime"])[1];
$filename=uniqid().rand(1000,9999).$houzui;
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt ( $ch, CURLOPT_URL, $url );
ob_start ();
curl_exec ( $ch );
$return_content = ob_get_contents ();
ob_end_clean ();
$return_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
$fp=@fopen("data/upload/downloadImg/".$filename,"a"); //将文件绑定到流
if($fp){
fwrite($fp,$return_content); //写入文件}
}
$addData["post_img_url"]="downloadImg/".$filename;
$addData["post_yl_img_url"]=$url;
$addData["post_title"]=$imgList[$i]["post_miaoshu"];
$addData["post_hb_id"]=$_POST["post_hb_id"];
$addData["post_source"]=$imgList[$i]["post_source"];
$addData["post_author"]=$userInfo["id"];
$addData["post_date"]=date("Y-m-d H:i:s");
$rs=$Posts->add($addData);
}
}
$Tag = M("tag");
$addAllData=json_decode($_POST["tag_list"],1);
$Tag_posts = M("Tag_posts");
for($i=0;$i<count($addAllData);$i++)
{
$rsFind=$Tag->where($addAllData[$i])->find();
$data1["tp_post_id"]=$rs;
if($rsFind)
{
$data1["tp_tag_id"]=$rsFind["tag_id"];
$rs1=$Tag_posts->add($data1);
}
else
{
$addAllData[$i]["tag_create_time"]=date("Y-m-d H:i:s");
$tagAddRsId=$Tag->add($addAllData[$i]);
$data1["tp_tag_id"]=$tagAddRsId;
$rs1=$Tag_posts->add($data1);
}
}
echo 1;
}
}
<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo ($user_nicename); ?>欧澜芝的个人主页</title>
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/palette.css">
<link href="/themes/simplebootx/Public/new/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/header.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/follow.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/user.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
</head>
<body>
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/collect/index');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/love/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<!--用户中心头部-->
<div class="yesterday">
<div class="yesterday_1">
<div class="yesterday_1_1">
<a href="#"><img src="<?php echo U('User/public/avatar',array('id'=>$user[0][id]));?>"></a>
</div>
<div class="yesterday_1_2">
<div class="yesterday_1_2_1"><span id="fcount"></span></div>
<div class="yesterday_1_2_2"><span id="gcount"></span></div>
</div>
<div class="yesterday_1_3">
<a href="<?php echo U('Portal/user/fans',array('id'=>$user[0][id]));?>"> <div class="yesterday_1_3_1">粉丝</div></a>
<div class="yesterday_1_3_2"></div>
<a href="<?php echo U('Portal/user/hisUser',array('id'=>$user[0][id]));?>"> <div class="yesterday_1_3_3">关注</div></a>
</div>
</div>
<div class="yesterday_2">
<div class="yesterday_2_1"><?php echo ($user[0]["user_nicename"]); ?></div>
<div class="yesterday_2_2"><?php echo ($user[0]["signature"]); ?></div>
</div>
<div class="yesterday_3" id="guanzhu">
</div>
</div>
<!--红色部分-->
<div class="hongse">
<input type="hidden" name="id" id="id" value="<?php echo ($user[0][id]); ?>" />
<a href="<?php echo U('Portal/user/index',array('id'=>$user[0][id]));?>">
<div class="hongse_1">
<div class="hongse_1_1"><span id="hcount"></span></div>
<div class="hongse_1_2">画板</div>
</div>
</a>
<a href="<?php echo U('Portal/user/caiji',array('id'=>$user[0][id]));?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1"><span id="ccount"></span></div>
<div class="hongse_1_2">采集</div>
</div></a>
<a href="<?php echo U('Portal/user/love',array('id'=>$user[0][id]));?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1"><span id="lcount"></span></div>
<div class="hongse_1_2">喜欢</div>
</div></a>
<a href="<?php echo U('Portal/user/tag',array('id'=>$user[0][id]));?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1"><span id="tcount"></span></div>
<div class="hongse_1_2">标签</div>
</div></a>
</div>
<div class="middle-box" id="fans">
</div>
</div>
<div style="clear: both"></div>
<!--没有更多-->
<div class="nomore" id="load">
<div class="nomore_1" style="font-family: 微软雅黑;font-size:1.4rem">╮(╯﹏╰)╭ 查看更多</div>
<a href="#"><i class="iconfont icon-daosanjiao" style="color: black"></i></a>
</div>
<!--底部-->
<script type="text/javascript">
//全局变量
var GV = {
ROOT: "/",
WEB_ROOT: "/",
JS_ROOT: "public/js/"
};
</script>
<!-- Placed at the end of the document so the pages load faster -->
<script src="/public/js/jquery.js"></script>
<script src="/public/js/wind.js"></script>
<script src="/themes/simplebootx/Public/assets/simpleboot/bootstrap/js/bootstrap.min.js"></script>
<script src="/public/js/frontend.js"></script>
<script>
$(function(){
$('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });
$("#main-menu li.dropdown").hover(function(){
$(this).addClass("open");
},function(){
$(this).removeClass("open");
});
$.post("<?php echo U('user/index/is_login');?>",{},function(data){
if(data.status==1){
if(data.user.avatar){
$("#main-menu-user .headicon").attr("src",data.user.avatar.indexOf("http")==0?data.user.avatar:"<?php echo sp_get_image_url('[AVATAR]','!avatar');?>".replace('[AVATAR]',data.user.avatar));
}
$("#main-menu-user .user-nicename").text(data.user.user_nicename!=""?data.user.user_nicename:data.user.user_login);
$("#main-menu-user li.login").show();
}
if(data.status==0){
$("#main-menu-user li.offline").show();
}
/* $.post("<?php echo U('user/notification/getLastNotifications');?>",{},function(data){
$(".nav .notifactions .count").text(data.list.length);
}); */
});
;(function($){
$.fn.totop=function(opt){
var scrolling=false;
return this.each(function(){
var $this=$(this);
$(window).scroll(function(){
if(!scrolling){
var sd=$(window).scrollTop();
if(sd>100){
$this.fadeIn();
}else{
$this.fadeOut();
}
}
});
$this.click(function(){
scrolling=true;
$('html, body').animate({
scrollTop : 0
}, 500,function(){
scrolling=false;
$this.fadeOut();
});
});
});
};
})(jQuery);
$("#backtotop").totop();
});
</script>
<!--script-->
<!-- Initialize Swiper -->
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/new/js/classie.js"></script>
<script src="/themes/simplebootx/Public/new/js/modalEffects.js"></script>
<script type="text/javascript">
var id = $("#id").val();
console.log(id);
//关注按钮状态
$.ajax({
type: "GET",
url: "/index.php?g=portal&m=user&a=userFollowStatus",
dataType: "json",
data:{
id:id
},
success:function(data){
console.log(data);
if(data==0){
$("#guanzhu").append(
'<div class="yesterday_3_1 " ><button class="userclick">关注+</button></div>'
)
}else{
$("#guanzhu").append(
'<div class="yesterday_3_1 "><button class="userclick">已关注</button></div>'
)
}
}
});
$("body").on("click",".userclick",function()
{
if($(this).text()=="关注+")
{
$.ajax({
type: "GET",
url: "/index.php?g=User&m=follow&a=clickUserFollow",
dataType: "json",
data:{
id:id
},
success:function(data){
if(data.status == 0){
alert(data.info);
$(location).attr('href', data.url);
}
if(data ==1){
alert("亲,自己不能关注自己哦!")
}
}
})
$(this).text("已关注")
}
else{
$.ajax({
type: "GET",
url: "/index.php?g=User&m=follow&a=clickCancelUser",
dataType: "json",
data:{
id:id
},
success:function(data){
}
})
$(this).text("关注+")
}
});
$.ajax({
type: "GET",
url: "/index.php?g=portal&m=user&a=userCount",
dataType: "json",
data:{
id:id
},
success:function(data){
console.log(data);
document.getElementById('hcount').innerHTML=data.hcount;
document.getElementById('ccount').innerHTML=data.ccount;
document.getElementById('lcount').innerHTML=data.lcount;
document.getElementById('tcount').innerHTML=data.tcount;
document.getElementById('fcount').innerHTML=data.fcount;
document.getElementById('gcount').innerHTML=data.gcount;
}
});
//用户粉丝详情
var pageIndex=1;
function getPostList(page) {
$.ajax({
type: "GET",
url: "/index.php?g=portal&m=user&a=fansDetailFollow&p="+page,
dataType: "json",
data:{
id:id
},
success: function (data) {
console.log(data);
var html = "";
for(var i=0; i< data.length; i++) {
var uid = data[i].usergz_uid_pid;
if(data[i].pidlist!==null) {
$("#fans").append(
'<div class="follow-box-user">' +
'<a href="index.php?g=portal&m=user&a=index&id='+uid+'">' +
'<img src="/themes/simplebootx/Public/new/image/user-bg.jpg">' +
'<div class="box-title-user">' +
data[i].huaban_count+'画板 '+data[i].caiji_count+' 采集' +
'</div>' +
'<div class="img-row-user">'+'</div>' +
'<a href="#"><button class="following-user"><i class="iconfont icon-jia1"></i> 关注</button></a>' +
'<div class="user-touxiang"><img src="index.php?g=user&m=public&a=avatar&id='+uid+'"></div>' +
'<div class="user-name">'+data[i].user_nicename+'</div>' +
'</a>' +
'</div>'
)
}
if(data.length<20)
{
$("#load").text("╮(・o・)╭没有更多了.....");
}
pageIndex++;
}
}
});
}
getPostList(pageIndex);
$("#load").click(function()
{
getPostList(pageIndex);
});
var login = document.getElementById('login');
var over = document.getElementById('over');
function show()
{
login.style.display = "block";
over.style.display = "block";
}
function hide()
{
login.style.display = "none";
over.style.display = "none";
}
$(".nav-box .right-menu .close-menu").click(function(){
$(".login-ul").slideUp();
$(".nav-box-ul").slideUp();
$(this).parent().removeClass("active");
});
$(".nav-box .right-menu .open-menu").click(function(){
$(".login-ul").slideDown();
$(".nav-box-ul").slideDown();
$(this).parent().addClass("active");
});
function show()
{
login.style.display = "block";
over.style.display = "block";
}
function hide()
{
login.style.display = "none";
over.style.display = "none";
}
</script>
</body>
</html><file_sep><?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
class HuabanController extends AdminbaseController{
protected $huaban_model;
protected $xingqu_model;
protected $posts_model;
public function _initialize() {
parent::_initialize();
$this->huaban_model = D("Common/Huaban");
$this->posts_model=D("Common/Posts");
}
///首页列表
public function index()
{
$User = M('Huaban'); // 实例化User对象
$count=$User->count();
$page = $this->page($count, 10);
$huaban = $User->limit($page->firstRow.','.$page->listRows)
->order("hb_id")
->select();
$this->assign("huaban",$huaban);
$this->assign("page", $page->show('Admin'));// 赋值分页输出
$this->display();
}
//编辑
public function edit()
{
$id = I("get.id",0,'intval');
$huaban=$this->huaban_model->where(array('hb_id'=>$id))->find();
$this->assign($huaban);
$this->display();
}
//编辑提交
public function edit_post()
{
// var_dump($id);
if(IS_POST){
if ($this->huaban_model->create()!==false) {
if ($this->huaban_model->save()!==false) {
$this->success("保存成功!", U("huaban/index"));
} else {
$this->error("保存失败!");
}
} else {
$this->error($this->huaban_model->getError());
}
}
}
public function delete(){
$id = I("get.id",0,'intval');
//var_dump($id);
if ($this->huaban_model->delete($id)!==false) {
$this->success("删除成功!");
} else {
$this->error("删除失败!");
}
}
public function content()
{
$id = I("get.id",0,'intval');
// var_dump($id);
$User = M('Huaban'); // 实例化User对象
$count=$User->count();
$page = $this->page($count, 10);
$posts = $User->limit($page->firstRow.','.$page->listRows)
->alias("a")
->join("tb_posts ON a.hb_id=tb_posts.post_xq_id")
->where(array('post_hb_id'=>$id))
->select();
$this->assign('posts',$posts);
$this->assign("page", $page->show('Admin'));// 赋值分页输出
$this->display();
}
public function edits()
{
$xingqu=$this->huaban_model->select();
$id = I("get.id",0,'intval');
$posts=$this->posts_model
->where(array('id'=>$id))->find();
$this->assign($posts);
$this->assign("xingqu",$xingqu);
$this->display();
}
public function edits_post()
{
$id = I("post.id",0,'intval');
if(IS_POST){
if ($this->posts_model->create()!==false) {
if ($this->posts_model->where("id = $id")->save()!==false) {
$this->success("保存成功!", U("huaban/content"));
} else {
$this->error("保存失败!");
}
} else {
$this->error($this->posts_model->getError());
}
}
}
//画板内容删除
public function deletes()
{
$id = I("get.id",0,'intval');
//var_dump($id);
if ($this->posts_model->where("id = $id")->delete()!==false) {
$this->success("删除成功!");
} else {
$this->error("删除失败!");
}
}
}<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>编辑画板</title>
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/header.css">
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/edit.css">
</head>
<body>
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li><a href="#">最新</a>
<!-- <ul>
<li><a href="#">我的推荐</a></li>
<li><a href="#">我的关注</a></li>
<li><a href="#">我的画板</a></li>
<li><a href="#">用户</a></li>
</ul>-->
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<<div class="login-ul" id="user"></div>
</nav>
<!--内容-->
<div class="palette-1">
<form action="<?php echo U('User/draw/edit_post');?>" method="post">
<div class="bianjihuaban">编辑画板/<?php echo ($hb_name); ?></div>
<div class="biaoti">标题
<input type="text" value="<?php echo ($hb_name); ?>" name="hb_name" style="font-size: 16px;outline: none;width: 40%;height: 3rem;margin-left: 6rem;padding-left: 0.5rem">
<input type="hidden" value="<?php echo ($hb_id); ?>" name="hb_id">
</div>
<div class="describe"><div style="float: left">描述</div><textarea name="hb_descp" style="outline: none;margin-left: 6.4rem;font-size: 16px;padding-left: 0.5rem"><?php echo ($hb_descp); ?></textarea></div>
<div class="describe-1">分类
<select style="border: 0px;outline: medium;width:40.3%;height: 3rem;background-color: white;margin-left: 6.4rem;border: 1.5px solid gainsboro" name="hb_term_id">
<?php if(is_array($category)): foreach($category as $key=>$vo): $hid_selected=$hb_term_id==$vo['xqfl_id']?"selected":""; ?>
<option value="<?php echo ($vo["xqfl_id"]); ?>"<?php echo ($hid_selected); ?> ><?php echo ($vo["xqfl_name"]); ?></option><?php endforeach; endif; ?>
</select> </div>
<div class="describe-2">删除<a href="<?php echo U('User/draw/delete',array('id'=>$hb_id));?>"><button >删除画板</button></a></div>
<div class="describe-3"><button type="submit">保存设置</button></div>
</form>
</div>
<script type="text/javascript">
//全局变量
var GV = {
ROOT: "/",
WEB_ROOT: "/",
JS_ROOT: "public/js/"
};
</script>
<!-- Placed at the end of the document so the pages load faster -->
<script src="/public/js/jquery.js"></script>
<script src="/public/js/wind.js"></script>
<script src="/themes/simplebootx/Public/assets/simpleboot/bootstrap/js/bootstrap.min.js"></script>
<script src="/public/js/frontend.js"></script>
<script>
$(function(){
$('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });
$("#main-menu li.dropdown").hover(function(){
$(this).addClass("open");
},function(){
$(this).removeClass("open");
});
$.post("<?php echo U('user/index/is_login');?>",{},function(data){
if(data.status==1){
if(data.user.avatar){
$("#main-menu-user .headicon").attr("src",data.user.avatar.indexOf("http")==0?data.user.avatar:"<?php echo sp_get_image_url('[AVATAR]','!avatar');?>".replace('[AVATAR]',data.user.avatar));
}
$("#main-menu-user .user-nicename").text(data.user.user_nicename!=""?data.user.user_nicename:data.user.user_login);
$("#main-menu-user li.login").show();
}
if(data.status==0){
$("#main-menu-user li.offline").show();
}
/* $.post("<?php echo U('user/notification/getLastNotifications');?>",{},function(data){
$(".nav .notifactions .count").text(data.list.length);
}); */
});
;(function($){
$.fn.totop=function(opt){
var scrolling=false;
return this.each(function(){
var $this=$(this);
$(window).scroll(function(){
if(!scrolling){
var sd=$(window).scrollTop();
if(sd>100){
$this.fadeIn();
}else{
$this.fadeOut();
}
}
});
$this.click(function(){
scrolling=true;
$('html, body').animate({
scrollTop : 0
}, 500,function(){
scrolling=false;
$this.fadeOut();
});
});
});
};
})(jQuery);
$("#backtotop").totop();
});
</script>
<!--script-->
<!-- Initialize Swiper -->
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script type="text/javascript">
$.ajax({
type: "GET",
url: "/index.php?g=&m=Index&a=getUser",
dataType: "json",
success: function (data) {
var uid =data.id;
//console.log(uid);
if(data == 0){
$("#user").append(
'<ul id="nav-login">'+
'<li id="login"><a href="index.php?g=user&m=login&a=index"><i class="iconfont icon-denglu"></i></a></li>'+
'</ul>'
)
}else{
$("#user").append(
'<ul id="nav-login">'+
'<li id="jia"><a href="#" ><i class="iconfont icon-jia1"></i></a></li>'+
'<li id="info"><a href="#"><i class="iconfont icon-xinxi1"></i></a></li>'+
'<li><a href="index.php?g=user&m=center&a=index"><div style="width: 27px;height: 27px;border-radius: 50%;"><img src="index.php?g=user&m=public&a=avatar&id='+uid+'"></div></a></li>'+
'</ul>'
)
}
}
});
</script>
</body>
</html><file_sep><?php if (!defined('THINK_PATH')) exit();?><html><!DOCTYPE HTML>
<head>
<title>批量采集</title>
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<style>
body,textarea,input{font-family: microsoft yahei;}
.clear-input{
width:338px;
display: inline-block;
padding: 0 10px;
height: 36px;
font-size: 14px;
line-height: 1;
color: #777;
background: #FCFCFC;
border: 1px solid #CCC;
border-radius: 3px;
box-shadow: inset 0 1px 2px rgba(0,0,0,.05);
-webkit-transition: color .2s linear,border-color .3s linear;
margin-top:30px;
margin-bottom:10px;
}
.scrollable{height:250px;overflow: auto;}
.btn-link{
background: linear-gradient( #F45D68, #E54646);
color: #fff;
box-shadow: inset 0 1px 0 rgba(255,255,255,.08),0 1px 0 rgba(255,255,255,.1);
border: 1px solid #C90000;
padding: 0 20px;
border-radius: 3px;
height: 36px;
line-height: 36px;
display: inline-block;
cursor: pointer;
}
.btn-link:hover{opacity:0.8;}
.huaban-list{margin:0;padding:0;}
.huaban-list li{background:#f8f8f8;padding:10px 20px;list-style:none;margin:0;margin-bottom:10px;color:#4a4a4a;font-size:12px;position:relative;cursor:pointer;}
.huaban-list li img{position: absolute;right:10px;top:9px;width:20px;display:none;}
.huaban-list li.active img{display: block;}
.create-huaban{cursor: pointer;display:none;}
.tag-inputs {
position: relative
}
.tag-input {
display: inline-block;
border: 1px solid #ccc;
border-radius: 2px;
padding: 6px;
background-color: #fcfcfc;
box-shadow: 0 1px 2px 0 rgba(0,0,0,.1) inset;
cursor: text;
width: 316px;
padding: 2px 6px;
}
.tag-inputs .placeholder {
position: absolute;
top: 8px;
left: 16px;
color: #bbb
}
.tag-input>input {
border: 0;
background-color: transparent;
box-shadow: none;
width: 98px;
height: 24px;
vertical-align: middle
}
.tag-input>input:hover,.tag-input>input:focus {
box-shadow: none
}
.tag-input>.tag-labels {
display: inline;
vertical-align: middle
}
.tag-input>.tag-labels>.tag-label {
display: inline-block;
border-radius: 1px;
margin: 2px 4px;
padding: 6px 12px;
font-size: 14px;
font-weight: 300;
line-height: 1.2;
text-shadow: 0 1px 0 rgba(255,255,255,.5);
color: #4a4a4a;
background-color: #ededed;
cursor: pointer
}
.tag-input>.tag-labels>.tag-label>.close {
display: inline-block;
width: 10px;
height: 10px;
margin-left: 8px;
background-image: url("/img/close_mini.svg");
background-position: 0 0;
background-repeat: no-repeat
}
.tag-input>.tag-labels>.tag-label:hover>.close {
background-position: 0 -30px
}
.add-tag{border:1px solid #CCC;color:#666;display:inline-block;cursor:pointer;padding:8px 10px;margin-left:6px;border-radius:4px;box-shadow: inset 0 1px 2px rgba(0,0,0,.05);font-size:14px;}
.tag-labels{word-wrap: break-word;word-break: break-all;max-height:60px;overflow:auto;}
.tag-labels .tag{margin:2px 2px;color:#fff;background:#888;padding:1px 6px;display:inline-block;}
.tag-labels .tag span{cursor: pointer;}
ul,li{margin:0;padding:0;list-style: none;}
#imgListCol li{width:46%;float:left;position:relative;margin:2%;height:60px;background-size:cover;background-position:center center;}
#imgListCol li .remove-img{border:1px solid #C90000;border-radius:50%;color:#C90000;width:16px;height:16px;display:inline-block;position:absolute;right:2px;top:2px;cursor:pointer;text-align:center;line-height:16px;background:#fff;display:none;}
#imgListCol li:hover .remove-img{display:block;}
</style>
</head>
<body style="background:#efeeec;">
<div style="width:590px;height:540px;margin:20px auto 0 auto;">
<div style="width:220px;float:left;height:100%;background:#f2f2f2;">
<div style="display:table;height:100%;width:220px;padding:0 15px;box-sizing:border-box;">
<div style="display:table-cell;width:190px;vertical-align:middle;">
<ul id="imgListCol">
</ul>
</div>
</div>
<div id="imgList" style="display:none;"><?php echo ($imgList); ?></div>
</div>
<div style="width:370px;float:left;height:540px;background:#fff;position:relative;">
<div style="width:338px;margin:0 auto;">
<input placeholder="搜索或创建画板" class="clear-input search-input">
<div class="scrollable">
<ul class="huaban-list">
<?php if(is_array($list)): foreach($list as $key=>$vo): ?><li data-id="<?php echo ($vo["hb_id"]); ?>">
<?php echo ($vo["hb_name"]); ?>
<img src="/img/widgets/gou.png" />
</li><?php endforeach; endif; ?>
</ul>
</div>
<div style="padding:12px 0 12px 0;border-bottom:1px solid #eee;margin-bottom:10px;">
<span class="create-huaban">
+ 创建画板<span></span>
</span>
</div>
<div class="tag-labels"></div>
<div>
<input class="clear-input taginput" style="margin:10px 0;width:250px;" placeholder="输入标签文字"><span class="add-tag">添加标签</span>
</div>
<div style="height:60px;background:#fafafa;position:absolute;bottom:0;left:0;width:100%;padding:13px 12px;box-sizing:border-box;text-align:right;">
<!-- <span style="display:inline-block;float:left;margin-top:6px;">
分享到:
<span><input type="checkbox" />
<img src="/img/widgets/weiboIcon.png" />
</span>
<span><input type="checkbox" />
<img style="width:14px;" src="/img/widgets/kongjianIcon.png" />
</span>-->
</span>
<span class="btn-link"> 采下来</span>
</div>
</div>
</div>
</div>
<input type="hidden" id="tag_users_id" value="<?php echo ($tag_users_id); ?>" />
<script type="text/javascript">
//全局变量
var GV = {
ROOT: "/",
WEB_ROOT: "/",
JS_ROOT: "public/js/"
};
</script>
<!-- Placed at the end of the document so the pages load faster -->
<script src="/public/js/jquery.js"></script>
<script src="/public/js/wind.js"></script>
<script src="/themes/simplebootx/Public/assets/simpleboot/bootstrap/js/bootstrap.min.js"></script>
<script src="/public/js/frontend.js"></script>
<script>
$(function(){
$('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });
$("#main-menu li.dropdown").hover(function(){
$(this).addClass("open");
},function(){
$(this).removeClass("open");
});
$.post("<?php echo U('user/index/is_login');?>",{},function(data){
if(data.status==1){
if(data.user.avatar){
$("#main-menu-user .headicon").attr("src",data.user.avatar.indexOf("http")==0?data.user.avatar:"<?php echo sp_get_image_url('[AVATAR]','!avatar');?>".replace('[AVATAR]',data.user.avatar));
}
$("#main-menu-user .user-nicename").text(data.user.user_nicename!=""?data.user.user_nicename:data.user.user_login);
$("#main-menu-user li.login").show();
}
if(data.status==0){
$("#main-menu-user li.offline").show();
}
/* $.post("<?php echo U('user/notification/getLastNotifications');?>",{},function(data){
$(".nav .notifactions .count").text(data.list.length);
}); */
});
;(function($){
$.fn.totop=function(opt){
var scrolling=false;
return this.each(function(){
var $this=$(this);
$(window).scroll(function(){
if(!scrolling){
var sd=$(window).scrollTop();
if(sd>100){
$this.fadeIn();
}else{
$this.fadeOut();
}
}
});
$this.click(function(){
scrolling=true;
$('html, body').animate({
scrollTop : 0
}, 500,function(){
scrolling=false;
$this.fadeOut();
});
});
});
};
})(jQuery);
$("#backtotop").totop();
});
</script>
<script>
Date.prototype.Format = function (fmt) { //author: meizz
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
var imgList=JSON.parse(unescape($("#imgList").text()));
console.log(imgList);
for(var i=0;i<imgList.length;i++)
{
$("#imgListCol").append('<li data-description="'+imgList[i].description+'" data-post_yl_img_url="'+imgList[i].imgUrl+'" data-source="'+imgList[i].url+'" style="background-image:url('+imgList[i].imgUrl+')">'+
'<span class="remove-img">×</span>'+
'</li>');
}
$("#imgListCol .remove-img").click(function()
{
$(this).parent().remove();
});
$(".huaban-list li").eq(0).addClass("active");
$(".btn-link").click(function()
{
var tagList=[];
$(".tag-labels .tag-text").each(function()
{
var tagObj={};
tagObj.tag_users_id=$("#tag_users_id").val();
tagObj.tag_name=$(this).text().trim();
tagList.push(tagObj);
});
var imgList=[];
$("#imgListCol li").each(function()
{
var imgObj={};
imgObj.post_yl_img_url=$(this).attr("data-post_yl_img_url");
imgObj.post_miaoshu=$(this).attr("data-description");
imgObj.post_source=$(this).attr("data-source");
imgList.push(imgObj);
});
console.log(imgList);
$.ajax({
url:'/index.php/Portal/Gather/addCaijiList',
type:'POST',
data:{
img_list:JSON.stringify(imgList),
post_hb_id:$(".huaban-list .active").attr("data-id"),
tag_list:JSON.stringify(tagList)
},
success:function(data){
if(data==1)
{
alert("采集成功!");
window.close();
}
else if(data=="-1")
{
alert("已经采集过了,不能重复采集!")
}
else
{
alert("采集失败,请重新尝试!");
}
}
});
});
$(".huaban-list").on("click","li",function()
{
$(".huaban-list li").removeClass("active");
$(this).addClass("active");
});
$(".add-tag").click(function()
{
var tagStr=$(".taginput").val().trim();
var xiangtongFlag=1;
$(".tag-labels .tag-text").each(function()
{
if(tagStr==$(this).text())
{
alert("不能添加相同的标签");
$(".taginput").val("");
xiangtongFlag=0;
}
});
if(xiangtongFlag)
{
$(".tag-labels").append('<span class="tag"><span class="tag-text">'+tagStr+'</span><span class="remove">×</span></span>');
$(".taginput").val("");
}
});
$(".tag-labels").on("click",".tag .remove",function()
{
$(this).parent().remove();
});
$(".search-input").on("propertychange",function()
{
createHuaban($(this));
});
$(".search-input").on("input",function()
{
createHuaban($(this));
});
function createHuaban($obj)
{
if($obj.val()!="")
{
$(".create-huaban").show();
$(".create-huaban span").text("'"+$obj.val()+"'");
}
else
{
$(".create-huaban").hide();
}
}
$(".create-huaban").click(function()
{
var hbName=$(".search-input").val().trim();
if(hbName!="")
{
$.ajax({
url:'/index.php/Portal/Gather/addHuaban',
type:'POST',
dataType:'json',
data:{
hb_name:hbName
},
success:function(data){
console.log(data)
if(data["code"]==1000)
{
var html="";
for(var i=0;i<data.data.length;i++)
{
html=html+'<li data-id="'+data.data[i].hb_id+'">'+data.data[i].hb_name+'<img src="/img/widgets/gou.png"></li>';
}
$(".huaban-list").empty();
$(".huaban-list").append(html);
$(".huaban-list li").eq(0).addClass("active");
$(".search-input").val("");
$(".create-huaban span").text("");
$(".create-huaban").hide();
}
else if(data["code"]==1001)
{
alert("已经存在同名的画布。");
$(".search-input").val("");
}
else
{
alert("创建失败,请重新尝试。")
}
}
});
}
});
</script>
</body>
</html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>忘记密码</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/login.css">
<link rel="stylesheet" media="screen and (max-width: 600px)" href="/themes/simplebootx/Public/new/css/small.css" />
</head>
<style>
.yanzhengma{
width: 80px;
height: 30px;
margin-top: -115px;
float: right;
z-index: 999;
position: relative;
margin-right:3rem;
}
</style>
<body>
<div class="border">
<div class="shuzhe">
<img src="/themes/simplebootx/Public/new/image/shuzhe.jpg">
</div>
<div class="shuzhe1">
<div class="shuzhe2">
<li class="text">FORGOT PASSWORD</li>
<li class="text-1">we will give you the best service</li>
</div>
<div class="shuzhe3"></div>
<form method="post" action="<?php echo U('user/login/doforgot_password');?>">
<div class="zhanghao" style="margin-top: 50px">
<div class="zhanghao-1"> <img src="/themes/simplebootx/Public/new/image/zhanghao.png"></div>
<div class="zhanghao-2"><input type="name" name="email" placeholder="请输入邮箱" style="background-color: #E7EBEE ;border:0px;height: 3rem;padding-left: 0.5rem"></div>
<div class="mima">
<div class="zhanghao-1"> <img src="/themes/simplebootx/Public/new/image/password.png"></div>
<div class="zhanghao-2"><input type="text" name="verify" placeholder="请输入验证码"style="background-color: #E7EBEE;border:0px;height: 3rem;padding-left: 0.5rem"></div>
</div>
</div>
<div class="denglu"><input type="submit" value="找回密码"style="width: 25rem; height: 4rem;border:0px;background-color: #FE4C7E; color: white;" ></div>
<div class="yanzhengma"><?php echo sp_verifycode_img('length=3&font_size=14&width=80&height=30&charset=1234567890&use_noise=1&use_curve=0');?></div>
</form>
<div class="bottom" style="margin-top: 50px">
<a href="<?php echo U('user/login/index');?>"> <li class="text-2">点击登录></li></a>
<div class="bottom-1"> <li class="text-3">还没有账号密码?</li></div>
<div class="bottom-2"><a href="<?php echo leuu('user/register/index');?>"><li class="text-4">点击注册 ></li></a></div>
</div>
</div>
</div>
<div class="last">
<div class="last-1"><li class="text-5">Copyright 2006-2016 Built by Asis. All rights reserved.</li></div>
<div class="last-1"><li class="text-5">Read the boring legal stuff</li></div>
</div>
</body>
</html><file_sep><?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
class PostsController extends AdminbaseController{
protected $posts_model;
protected $huaban_model;
protected $xingqu_model;
protected $users_model;
public function _initialize() {
parent::_initialize();
$this->posts_model = D("Common/Posts");
$this->xingqu_model=D("Common/Xingqu");
$this->huaban_model=D("Common/Huaban");
$this->users_model=D("Common/Users");
}
public function index(){
$User = M('Posts'); // 实例化User对象
$count=$User->count();
$page = $this->page($count, 10);
$list = $User->limit($page->firstRow.','.$page->listRows)
->alias("a")
->field("a.id as pid,tb_users.id as uid,a.*,user_nicename")
->join("tb_users ON a.post_author = tb_users.id")
->order("id")
//->join("tb_huaban ON a.post_hb_id=tb_huaban.hb_id")
//->join("tb_xingqu ON a.post_xq_id=tb_xingqu.xq_id")
->select();
$this->assign('posts',$list);// 赋值数据集
$this->assign("page", $page->show('Admin'));// 赋值分页输出
//var_dump($posts);
$this->display();
}
public function add()
{
$user=$this->users_model->field("id,user_nicename")->select();
$this->assign("user",$user);
$this->display('add');
}
////
public function post_add()
{
if (IS_POST) {
$_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
$_POST['post']['post_date']=date("Y-m-d H:i:s",time());
$_POST['post']['recommened']=$_POST['recommended'];
$_POST['post']['post_author']=$_POST['post_author'];
$page=I("post.post");
$page['smeta']=json_encode($_POST['smeta']);
$page['post_content']=htmlspecialchars_decode($page['post_content']);
$result=$this->posts_model->add($page);
if ($result) {
$this->success("添加成功!");
} else {
$this->error("添加失败!");
}
}
}
//删除
public function delete(){
if(isset($_POST['ids'])){
$ids = implode(",", $_POST['ids']);
$data['slide_status']=0;
if ($this->posts_model->where("id in ($ids)")->delete()!==false) {
$this->success("删除成功!");
} else {
$this->error("删除失败!");
}
}else{
$id = I("get.id",0,'intval');
if ($this->posts_model->where(" id = $id")->delete()!==false) {
$this->success("删除成功!");
} else {
$this->error("删除失败!");
}
}
}
//编辑
public function edit()
{
$xingqu=$this->xingqu_model->field("xq_id,xq_name")->select();
$id = I("get.id",0,'intval');
$post=$this->posts_model->where(array('id'=>$id))->find();
$this->assign("post",$post);
$this->assign("xingqu",$xingqu);
$this->display();
}
//编辑提交
public function edit_post(){
$id = I("post.id",0,'intval');
if(IS_POST){
if ($this->posts_model->create()!==false) {
if ($this->posts_model->where("id = $id")->save()!==false) {
$this->success("保存成功!", U("posts/index"));
} else {
$this->error("保存失败!");
}
} else {
$this->error($this->posts_model->getError());
}
}
}
}
<file_sep><?php if (!defined('THINK_PATH')) exit();?><html><!DOCTYPE HTML>
<head>
<title>欧兰芝插件</title>
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link href="favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/swiper.min.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/other.css">
<style>
.dropdown:hover .dropdown-menu {
display: block;
}
.dropdown-menu li a:hover{
background: #C1A062;
}
.dropdown-toggle-touxiang img:hover{
opacity: 0.9;
}
@media screen and (max-width: 468px) {
.dropdown:hover .dropdown-menu {
display: none;
}
}
.title:hover{
background: #FAFAFA
}
.button:hover{
opacity: 0.9
}
@keyframes typing { from { width: 0; } }
@keyframes blink-caret { 50% { border-color: transparent; } }
.banner-box{
width: 100%;
height: 350px;
overflow: hidden;
margin-top: 6rem;
margin-bottom: 4rem
}
.banner-box img{
width: 100%;
height: 100%;
object-fit: cover;
-webkit-filter: blur(15px);
-moz-filter: blur(15px);
-o-filter: blur(15px);
-ms-filter: blur(15px);
filter: blur(5px);
}
.banner-title {
font: bold 200% Consolas, Monaco, monospace;
border-right: .05em solid;
width: 16.5em; /* fallback */
width: 30ch; /* # of chars */
white-space: nowrap;
overflow: hidden;
animation: typing 3s steps(30, end), /* # of steps = # of chars */
blink-caret .8s step-end infinite alternate;
position: relative;
color: white;
font-size: 40px;
top:-70%;
font-weight: 700;
right: -50%;
width: 300px;
height: auto;
margin-left: -150px;
text-shadow: 5px 5px 8px rgba(0,0,0,0.7);
}
.banner-sub-title{
position: relative;
color: white;
font-size: 18px;
top:-65%;
right: -50%;
width: 420px;
height: auto;
font-weight: 700;
line-height: 30px;
margin-left: -200px
}
.button{
width:280px;height:55px;background-color:#E54646;margin:0 auto;font-size:22px;margin-top:20px;color:white;border-radius:5px
}
.button a{
text-transform: none
}
.sub{
width:250px;height:50px;margin:0 auto;font-size:13px;
}
.left-part{
width:50%;float:left
}
.right-part{
width:50%;float:right
}
</style>
</head>
<body class="met-navfixed">
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="index.html" class="active">首页</a></li>
<li><a href="found/found.html">发现</a></li>
<!-- <li id="new"><a href="new/new.html">最新</a>
</li>-->
<li class="dropdown">
<a href="new/new.html" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="#" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的推荐</a></li>
<li><a href="user/user.html" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的关注</a></li>
<li><a href="palette/palette.html" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="#" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
<li><a href="#" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">主题</a></li>
</ul>
</li>
<li><a href="activity/activity.html">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="image/menu.png" />
<img class="close-menu" src="image/closeMenu.png" />
</div>
<div class="login-ul">
<ul id="nav-login">
<!-- <li id="jia"><a href="#" ><i class="iconfont icon-jia1"></i></a></li>-->
<li id="info"><a href="#"><i class="iconfont icon-xinxi1"></i><div class="dote" ></div></a></li>
<li class="dropdown" >
<a href="palette/palette.html" class="dropdown-toggle">
<div class="dropdown-toggle-touxiang" style="width: 27px;height: 27px;border-radius: 50%;"><img src="/themes/simplebootx/Public/new/image/touxiang.png"></div></a>
<ul class="dropdown-menu" style="min-width: 12rem;background: white;margin-left: -100px;margin-top: 20px">
<div style="position: absolute;width: 13px;height: 13px;background-color: white;z-index: -1;right: 18px;top: -6px;transform:rotate(45deg);-ms-transform:rotate(45deg);-moz-transform:rotate(45deg);-webkit-transform:rotate(45deg);-o-transform:rotate(45deg);"></div>
<li style="min-width: 100%"><a href="user/user.html" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%;color: grey"><i class="iconfont icon-guanzhu" style="font-size: 1.8rem;float: left;margin-right: 0.8rem"></i>已关注<font style="float: right">271</font></a></li>
<li><a href="palette/palette.html" style="font-size: 1.5rem;line-height: 30px;min-width: 100%;color: grey"><i class="iconfont icon-huaban" style="font-size: 1.8rem;float: left;margin-right: 0.8rem" ></i>画板<font style="float: right">20</font></a></li>
<li><a href="#" style="font-size: 1.5rem;line-height: 30px;min-width: 100%;color: grey"><i class="iconfont icon-fensi" style="font-size: 1.8rem;float: left;margin-right: 0.8rem"></i>粉丝<font style="float: right">41</font></a></li>
<li><a href="setting/setting.html" style="font-size: 1.5rem;line-height: 30px;min-width: 100%;color: grey;text-align: center">设置</a></li>
<li><a href="#" style="font-size: 1.5rem;line-height: 30px;min-width: 100%;color: grey;text-align: center">退出</a></li>
</ul>
</li>
<li id="login"><a href="#"><i class="iconfont icon-denglu"></i></a></li>
</ul>
</div>
</nav>
<div class="banner-box">
<img src="/themes/simplebootx/Public/new/image/111.jpg">
<div class="banner-title" >欧澜芝采集工具</div>
<div class="banner-sub-title">使用欧澜芝采集工具,<br>你可以方便地保存任意网站上的图片、视频和截图</div>
</div>
<div class="body" style="margin-top:6rem">
<div class="wrapper">
<div class="units">
<div class="unit chrome ">
<div class="title " style="font-size:18px">
<i class="iconfont icon-chrome" style="font-size:20px;margin-right:5px;margin-left:10px"></i> Chrome 浏览器
<i></i>
<div class="arrow"></div>
</div>
<div class="inner">
<div class="software clearfix">
<div class="install-area">
<div onclick="" class="button text-center">
安装花瓣 Chrome 扩展
</div>
<div class="sub text-center" style="">
你还可以选择安装
<a class="go">书签栏采集工具</a>
</div>
</div>
<h4 style="border-bottom: 2px solid gainsboro;padding-bottom:10px">如何使用花瓣 Chrome 扩展?</h4>
<div class="left-part">
<h4>方法一</h4>
<p>浏览网页时,看到页面上感兴趣的图片、网页、视频,点击右上角的花瓣图标,选择相应功能进行采集。</p>
<img src="/themes/simplebootx/Public/new/pluginImg/about_tools_chrome_01.jpg" width="478" height="320" data-baiduimageplus-ignore="1" />
</div>
<div class="right-part" >
<h4>方法二</h4>
<p>浏览网页时,把鼠标停留在你喜欢的图片上,点击右键,选择“采集到花瓣”(此方法不起作用时,推荐方法一)</p>
<img src="/themes/simplebootx/Public/new/pluginImg/about_tools_chrome_02.jpg" width="478" height="320" data-baiduimageplus-ignore="1" />
</div>
</div>
<div style="display: none" class="script clearfix">
<div class="install-area">
<div class="button white">
<a href="javascript:(function(a,b,c,d){a[c]?a[c].ui.show():(d=b.createElement('script'),d.id='huaban_script',d.setAttribute('charset','utf-8'),d.src='https://hb.pro.youzewang.com/public/gather/plugin.js?'+Math.floor(+new Date/1e7),b.body.appendChild(d))})(window,document,'HUABAN_GLOBAL');" onclick="app.alert('请把按钮拖动到书签栏');return false;" class="mask-button">
拖动此按钮到书签栏
</a>
</div>
<div class="sub">
返回安装
<a class="go">花瓣 Chrome 扩展</a>
</div>
</div>
<div class="left-part">
<h4>使用方法</h4>
<p>拖动上面的按钮到你的书签栏上。浏览网页时,点击书签栏上的“采集到花瓣”即可。</p>
<img src="/themes/simplebootx/Public/new/pluginImg/about_tools_chrome_bookmark.jpg" width="478" height="320" data-baiduimageplus-ignore="1" />
</div>
</div>
</div>
</div>
<div class="unit firefox">
<div class="title" style="font-size:18px">
<i class="iconfont icon-firefox" style="font-size:20px;margin-right:5px;margin-left:10px"></i> Firefox(火狐)浏览器
<i></i>
<div class="arrow"></div>
</div>
<div class="inner">
<div class="software clearfix">
<div class="install-area">
<div class="button text-center" > <a target="_blank" href="###" style="color:white" >安装花瓣 Firefox 附加组件</a></div>
<div class="sub">
你还可以选择安装
<a class="go">书签栏采集工具</a>
</div>
</div>
<h3>如何使用花瓣 Firefox 附加组件</h3>
<div class="left-part">
<h4>方法一</h4>
<p>浏览网页时,看到页面上感兴趣的图片、网页、视频,点击右上角的花瓣图标,选择相应功能进行采集。</p>
<img src="/themes/simplebootx/Public/new/pluginImg/about_tools_firefox_01.jpg" width="478" height="320" data-baiduimageplus-ignore="1" />
</div>
<div class="right-part">
<h4>方法二</h4>
<p>浏览网页时,把鼠标停留在你喜欢的图片上,点击右键,选择“采集到花瓣”(此方法不起作用时,推荐方法一)</p>
<img src="/themes/simplebootx/Public/new/pluginImg//about_tools_firefox_02.jpg" width="478" height="320" data-baiduimageplus-ignore="1" />
</div>
</div>
<div style="display: none" class="script clearfix">
<div class="install-area">
<div class="button white">
<font style="color:#767676">拖动此按钮到书签栏</font>
<a href="javascript:(function(a,b,c,d){a[c]?a[c].ui.show():(d=b.createElement('script'),d.id='huaban_script',d.setAttribute('charset','utf-8'),d.src='https://hb.pro.youzewang.com/public/gather/plugin.js?'+Math.floor(+new Date/1e7),b.body.appendChild(d))})(window,document,'HUABAN_GLOBAL');" onclick="app.alert('请把按钮拖动到书签栏');return false;" class="mask-button">采集到花瓣</a>
</div>
<div class="sub">
返回安装
<a class="go">花瓣 Firefox 附加组件</a>
</div>
</div>
<div class="left-part">
<h4>使用方法</h4>
<p>拖动上面的按钮到你的书签栏上。浏览网页时,点击书签栏上的“采集到花瓣”即可。</p>
<img src="/themes/simplebootx/Public/new/pluginImg/about_tools_firefox_bookmark.jpg" width="478" height="320" data-baiduimageplus-ignore="1" />
</div>
</div>
</div>
</div>
<div class="unit ie">
<div class="title" style="font-size:18px">
<i class="iconfont icon-msnui-logo-ie" style="font-size:22px;margin-right:5px;margin-left:10px"></i> IE 浏览器
<i></i>
<div class="arrow"></div>
</div>
<div class="inner">
<div style="display: none" class="software clearfix">
<div class="install-area">
<a target="_blank" href="//hbfile.b0.upaiyun.com/extensions/huaban-windows-ie-extension-setup.exe" class="button">安装 IE 插件</a>
<div class="sub">
你还可以选择安装
<a class="go">书签栏采集工具</a>
</div>
</div>
<h3>如何使用花瓣 IE 插件?</h3>
<div class="left-part">
<img src="/themes/simplebootx/Public/new/pluginImg/about_tools_ie.jpg" width="478" height="320" data-baiduimageplus-ignore="1" />
</div>
<div class="right-part">
<p style="margin-top: 130px">浏览网页时,看到页面上感兴趣的图片、视频,点击右键,选择“采集图片(视频)到花瓣”</p>
</div>
</div>
<div class="script clearfix">
<div class="install-area">
<div class="button white text-center">
<a href="javascript:(function(a,b,c,d){a[c]?a[c].ui.show():(d=b.createElement('script'),d.id='huaban_script',d.setAttribute('charset','utf-8'),d.src='https://hb.pro.youzewang.com/public/gather/plugin.js?'+Math.floor(+new Date/1e7),b.body.appendChild(d))})(window,document,'HUABAN_GLOBAL');" onclick="app.alert('请把按钮拖动到书签栏');return false;" class="mask-button">拖动此按钮到书签栏</a>
</div>
<div class="sub">
你还可以选择安装
<a class="go">花瓣 IE 插件</a>
</div>
</div>
<div class="left-part">
<h4>使用方法</h4>
<p>拖动上面的按钮到你的书签栏上。浏览网页时,点击书签栏上的“采集到花瓣”即可。</p>
<img src="/themes/simplebootx/Public/new/pluginImg/about_tools_ie_bookmark.jpg" width="478" height="320" data-baiduimageplus-ignore="1" />
</div>
</div>
</div>
</div>
<div class="unit others " style="height: 54px;margin-bottom:3rem">
<div class="title" style="font-size:18px;">
<i class="iconfont icon-iconfontquestion" style="font-size:22px;margin-right:5px;margin-left:10px"></i> 其它浏览器
<i></i>
<div class="arrow"></div>
</div>
<div class="inner" >
<div class="script clearfix">
<div class="install-area">
<div class="button white">
<font style="color:#767676">拖动此按钮到书签栏</font>
<a href="javascript:(function(a,b,c,d){a[c]?a[c].ui.show():(d=b.createElement('script'),d.id='huaban_script',d.setAttribute('charset','utf-8'),d.src='https://hb.pro.youzewang.com/public/gather/plugin.js?'+Math.floor(+new Date/1e7),b.body.appendChild(d))})(window,document,'HUABAN_GLOBAL');" onclick="app.alert('请把按钮拖动到书签栏');return false;" class="mask-button">采集到花瓣</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="margin-top:100px;width100%;height:1px"></div>
<!-- foot -->
<div class="footer" >
<div class="footer_1">
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div style="clear: both"></div>
</div>
<div class="footer_2">
<div class="footer_2_1"><a href="#">关注我们</a></div>
<div class="footer_2_2"><a href="#">信息博客</a><br><a href="#">新浪博客</a><br><a href="#">官方微信</a></div>
<div class="footer_2_2"><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a></div>
</div>
<div style="clear: both"></div>
<div class="footer_3">Copyright2016-2017 Heifeiku Leijan Technology Co.Ltd All Rights Reserved<br>
皖ICP备17010401号-2皖公网安备3301080233301号
</div>
</div>
<script type="text/javascript">
//全局变量
var GV = {
ROOT: "/",
WEB_ROOT: "/",
JS_ROOT: "public/js/"
};
</script>
<!-- Placed at the end of the document so the pages load faster -->
<script src="/public/js/jquery.js"></script>
<script src="/public/js/wind.js"></script>
<script src="/themes/simplebootx/Public/assets/simpleboot/bootstrap/js/bootstrap.min.js"></script>
<script src="/public/js/frontend.js"></script>
<script>
$(function(){
$('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });
$("#main-menu li.dropdown").hover(function(){
$(this).addClass("open");
},function(){
$(this).removeClass("open");
});
$.post("<?php echo U('user/index/is_login');?>",{},function(data){
if(data.status==1){
if(data.user.avatar){
$("#main-menu-user .headicon").attr("src",data.user.avatar.indexOf("http")==0?data.user.avatar:"<?php echo sp_get_image_url('[AVATAR]','!avatar');?>".replace('[AVATAR]',data.user.avatar));
}
$("#main-menu-user .user-nicename").text(data.user.user_nicename!=""?data.user.user_nicename:data.user.user_login);
$("#main-menu-user li.login").show();
}
if(data.status==0){
$("#main-menu-user li.offline").show();
}
/* $.post("<?php echo U('user/notification/getLastNotifications');?>",{},function(data){
$(".nav .notifactions .count").text(data.list.length);
}); */
});
;(function($){
$.fn.totop=function(opt){
var scrolling=false;
return this.each(function(){
var $this=$(this);
$(window).scroll(function(){
if(!scrolling){
var sd=$(window).scrollTop();
if(sd>100){
$this.fadeIn();
}else{
$this.fadeOut();
}
}
});
$this.click(function(){
scrolling=true;
$('html, body').animate({
scrollTop : 0
}, 500,function(){
scrolling=false;
$this.fadeOut();
});
});
});
};
})(jQuery);
$("#backtotop").totop();
});
</script>
<script src="/themes/simplebootx/Public/new/js/swiper.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/assets/js/slippry.min.js"></script>
<!-- Initialize Swiper -->
<script>
$(".units .unit .title").click(function()
{
$(this).toggleClass("on");
$(this).next().toggle("slow");
});
$(".go").click(function()
{
$(this).parent().parent().parent().hide();
$(this).parent().parent().parent().next().show();
});
</script>
</body>
</html><file_sep><?php
/**
* Created by PhpStorm.
* User: Admin
* Date: 2018/1/10
* Time: 16:37
*/
namespace Portal\Model;
use Common\Model\CommonModel;
class HuabanModel extends CommonModel {
}<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/palette.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/foundDetail.css">
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/lable.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<title>最新分类</title>
</head>
<body>
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/collect/index');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/love/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<div class="cephalosome">
<img src="/themes/simplebootx/Public/new/image/banner2.jpg" style="width: 100%;height: 100%;object-fit: cover; -webkit-filter: blur(3px); /* Chrome, Opera */-moz-filter: blur(3px);-ms-filter: blur(3px); filter: blur(3px);">
<div class="cephalosome-1" style="z-index: 999;position: relative;top: -50%;margin-top: -5rem"><?php echo ($xqfl_name); ?></div>
<input type="hidden" name="flid" value="<?php echo ($xqfl_id); ?>" id="flid">
</div>
<div class="morefound"><img src="/themes/simplebootx/Public/new/image/huojian.png"> 更多发现</div>
<div class="morefound-1">
<?php if(is_array($xingqu)): foreach($xingqu as $key=>$vo): ?><a href="<?php echo U('portal/InterestDetail/interest',array('xid'=>$vo['xq_id']));?>"><div class="morefound-1-2"><img src="<?php echo U('portal/newest/imgXingqu',array('id'=>$vo['xq_id']));?>"><p><?php echo ($vo["xq_name"]); ?></p></div></a><?php endforeach; endif; ?>
</div>
<div class="morefound-2">
<div class="morefound-2-1" id="cj-box">
</div>
</div>
<!--没有更多-->
<div class="nomore" id="load">
<div class="nomore_1" style="font-family: 微软雅黑;">╮(╯﹏╰)╭ 查看更多</div>
<a href="#"><i class="iconfont icon-daosanjiao" style="color: black"></i></a>
</div>
<script type="text/javascript">
//全局变量
var GV = {
ROOT: "/",
WEB_ROOT: "/",
JS_ROOT: "public/js/"
};
</script>
<!-- Placed at the end of the document so the pages load faster -->
<script src="/public/js/jquery.js"></script>
<script src="/public/js/wind.js"></script>
<script src="/themes/simplebootx/Public/assets/simpleboot/bootstrap/js/bootstrap.min.js"></script>
<script src="/public/js/frontend.js"></script>
<script>
$(function(){
$('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });
$("#main-menu li.dropdown").hover(function(){
$(this).addClass("open");
},function(){
$(this).removeClass("open");
});
$.post("<?php echo U('user/index/is_login');?>",{},function(data){
if(data.status==1){
if(data.user.avatar){
$("#main-menu-user .headicon").attr("src",data.user.avatar.indexOf("http")==0?data.user.avatar:"<?php echo sp_get_image_url('[AVATAR]','!avatar');?>".replace('[AVATAR]',data.user.avatar));
}
$("#main-menu-user .user-nicename").text(data.user.user_nicename!=""?data.user.user_nicename:data.user.user_login);
$("#main-menu-user li.login").show();
}
if(data.status==0){
$("#main-menu-user li.offline").show();
}
/* $.post("<?php echo U('user/notification/getLastNotifications');?>",{},function(data){
$(".nav .notifactions .count").text(data.list.length);
}); */
});
;(function($){
$.fn.totop=function(opt){
var scrolling=false;
return this.each(function(){
var $this=$(this);
$(window).scroll(function(){
if(!scrolling){
var sd=$(window).scrollTop();
if(sd>100){
$this.fadeIn();
}else{
$this.fadeOut();
}
}
});
$this.click(function(){
scrolling=true;
$('html, body').animate({
scrollTop : 0
}, 500,function(){
scrolling=false;
$this.fadeOut();
});
});
});
};
})(jQuery);
$("#backtotop").totop();
});
</script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/new/js/classie.js"></script>
<script src="/themes/simplebootx/Public/new/js/modalEffects.js"></script>
<script>
var flid = $("#flid").val();
// console.log(flid);
var pageIndex=1;
function getPostList(page) {
$.ajax({
type: "GET",
url: "/index.php?g=&m=InterestDetail&a=interestCollect&p="+page,
dataType: "json",
data:{
id:flid
},
success:function(data){
console.log(data);
for(var i =0; i<data.length;i++){
var pid = data[i].pid;
var uid = data[i].uid;
$("#cj-box").append(
'<div class="lable-box">' +
'<div class="img-detail-box">' +
'<a href="index.php?g=&m=Article&a=posts&pid='+pid+'"><img src="index.php?g=&m=Index&a=imgCollect&id=' + pid + '"></a>' +
'</div>' +
'<div class="user-box">' +
'<a href="index.php?g=Portal&m=user&a=index&id='+uid+'">'+
'<div class="user-touxiang">' +
'<img src="index.php?g=user&m=public&a=avatar&id=' + uid + '">' +
'</div></a>' +
'<div class="title-box-right">' +
'<div class="title-left">' +
data[i].post_title +
'</div>' +
'<div class="title-right">' +
'<a href="#">' +
'<i class="iconfont icon-guanzhu" style="color: red"></i>' +
'<font id="num-like" style="color: #989998">'+data[i].post_love+'</font>' +
'</a>' +
/* '<a href="#">' +
'<font style="float: right">' +
'<i class="iconfont icon-fenxiang"></i>' +
'</font>' +*/
'</a>' +
'</div>' +
'</div>' +
'<div class="user-name">'+data[i].user_nicename+'</div>' +
'</div>' +
'</div>'
)
}
$("#cj-box").append(
'<div style="clear: both"></div>'
)
if(data.length<16)
{
$("#load").text("╮(・o・)╭没有更多了.....");
}
pageIndex++;
}
})
}
getPostList(pageIndex);
$("#load").click(function()
{
getPostList(pageIndex);
});
</script>
</body>
</html><file_sep><?php
/*
* _______ _ _ _ _____ __ __ ______
* |__ __| | (_) | | / ____| \/ | ____|
* | | | |__ _ _ __ | | _| | | \ / | |__
* | | | '_ \| | '_ \| |/ / | | |\/| | __|
* | | | | | | | | | | <| |____| | | | |
* |_| |_| |_|_|_| |_|_|\_\\_____|_| |_|_|
*/
/*
* _________ ___ ___ ___ ________ ___ __ ________ _____ ______ ________
* |\___ ___\\ \|\ \|\ \|\ ___ \|\ \|\ \ |\ ____\|\ _ \ _ \|\ _____\
* \|___ \ \_\ \ \\\ \ \ \ \ \\ \ \ \ \/ /|\ \ \___|\ \ \\\__\ \ \ \ \__/
* \ \ \ \ \ __ \ \ \ \ \\ \ \ \ ___ \ \ \ \ \ \\|__| \ \ \ __\
* \ \ \ \ \ \ \ \ \ \ \ \\ \ \ \ \\ \ \ \ \____\ \ \ \ \ \ \ \_|
* \ \__\ \ \__\ \__\ \__\ \__\\ \__\ \__\\ \__\ \_______\ \__\ \ \__\ \__\
* \|__| \|__|\|__|\|__|\|__| \|__|\|__| \|__|\|_______|\|__| \|__|\|__|
*/
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <<EMAIL>>
// +----------------------------------------------------------------------
namespace Portal\Controller;
use Common\Controller\HomebaseController;
/**
* 首页
*/
class IndexController extends HomebaseController
{
//首页
public function index()
{
$this->display(":index");
}
//获取用户登录信息
public function getUser(){
$user = session("user");
if($user){
//用户采集数
$uid = sp_get_current_userid();
$posts_model = M("posts");
$postCount = $posts_model->where(array("post_author"=>$uid))->count();
//用户喜欢数
$love_model = M("Love");
$loveCount = $love_model->where(array("love_users_id"=>$uid))->count();
//用户关注
$xqgz_model = M("Xqd_guanzhu");
$xqdCount = $xqgz_model->where(array("xqdgz_uid"=>$uid))->count();
$usergz_model =M("Yonghu_gz");
$userCount = $usergz_model->where(array("usergz_uid_pid"=>$uid))->count();
$hbgz_model = M("hbgz");
$hbgzCount = $hbgz_model->where(array("hbgz_uid"=>$uid))->count();
$gzCount = $xqdCount+$userCount+$hbgzCount;
$data['post'] = $postCount;
$data['love'] = $loveCount;
$data['gz'] = $gzCount;
$data["user"] = $user;
echo json_encode($data);
//echo json_encode($user);
}else{
echo 0;
}
}
//采集列表
public function getPostList()
{
$users_model = M('Users');
$post_model = M("Posts");
$count = $post_model->count();
$page = new \Think\Page($count,16);
$list = $users_model
->alias("a")
->join("tb_posts b on a.id =b.post_author")
->field("b.id as pid,a.id as uid,a.user_nicename,a.avatar,b.post_title,b.post_love,b.post_img_url,b.recommended,b.post_date")
->order('post_date desc')
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($list);
}
//为您推荐
public function getRecommended()
{
$users_model = M('Users');
$post_model = M("Posts");
$count = $post_model->count();
$page = new \Think\Page($count,16);
$list = $users_model
->alias("a")
->join("tb_posts b on a.id =b.post_author")
->field("b.id as pid,a.id as uid,a.user_nicename,a.avatar,b.post_title,b.post_love,b.post_img_url,b.recommended,b.post_date")
->order('post_date desc')
->where("recommended = 1")
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($list);
}
//获取采集图片地址
public function imgCollect(){
$posts_model = M("Posts");
$id=I("get.id",0,"intval");
$post_img = $posts_model->field("post_img_url")->where(array("id" =>$id))->find();
$img = $post_img['post_img_url'];
$should_show_default=false;
if(empty($img)){
$should_show_default=true;
}else {
if (strpos($img, "http") === 0) {
header("Location: $img");
exit();
} else {
$img_dir = C("UPLOADPATH");
$img = $img_dir . $img;
if (file_exists($img)) {
$imageInfo = getimagesize($img);
if ($imageInfo !== false) {
$fp = fopen($img, "r");
$file_size = filesize($img);
$mime = $imageInfo['mime'];
header("Content-type: $mime");
header("Accept-Length:" . $file_size);
$buffer = 259 * 313;
$file_count = 0;
//向浏览器返回数据
while (!feof($fp) && $file_count < $file_size) {
$file_content = fread($fp, $buffer);
$file_count += $buffer;
echo $file_content;
flush();
ob_flush();
}
fclose($fp);
} else {
$should_show_default = true;
}
} else {
$should_show_default = true;
}
}
}
if($should_show_default){
$imageInfo = getimagesize("public/images/haibao.png");
if ($imageInfo !== false) {
$mime=$imageInfo['mime'];
header("Content-type: $mime");
echo file_get_contents("public/images/haibao.png");
}
}
exit();
}
//私信列表
public function message(){
$sixin_model = M("Sixin");
$sixin = $sixin_model->select();
echo json_encode($sixin);
}
}
<file_sep><?php if (!defined('THINK_PATH')) exit();?><div class="pinglun">评论</div>
<!-- <div class="pinglun-box-scroll">-->
<?php if(is_array($comments)): foreach($comments as $key=>$vo): ?><div class="pinglun-info">
<div class="info-box">
<div class="touxiang-box small"> <img src="<?php echo U('user/public/avatar',array('id'=>$vo['uid']));?>"></div>
<div class="item-inner">
<div class="item-inner-text" style="margin-top: 1rem;">
<div class="item-title"><?php echo ($vo["full_name"]); ?></div>
<div class="item-title-right"><?php echo date('Y年m月d日 H:i',strtotime($vo['createtime']));?></div>
</div>
</div>
</div>
<div class="pinglun-content" >
<?php echo ($vo["content"]); ?>
</div>
</div><?php endforeach; endif; ?>
<!--/div>-->
<form action="<?php echo U('comment/comment/post');?>" method="post">
<div class="huifu">
<div style="width: 95%;height: auto;margin: 0 auto">
<input type ="text" placeholder="点击填写评论" name="content" ></div>
<input type="hidden" name="post_table" value="<?php echo ($post_table); ?>"/>
<input type="hidden" name="post_id" value="<?php echo ($post_id); ?>"/>
<input type="hidden" name="to_uid" value="0"/>
<input type="hidden" name="parentid" value="0"/>
<button type="submit" class="fabu" >发布</button>
</div>
</form><file_sep><?php if (!defined('THINK_PATH')) exit();?><html><!DOCTYPE HTML>
<head>
<title>活动</title>
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/activity.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/swiper.min.css">
<!-- <style>
.banner-box{
width: 50%;
height: 350px;
position: absolute;
left:27%;
z-index: 9999;
background-color:rgba(0,0,0,0.4);
top: 22%;
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
</style>-->
</head>
<body class="met-navfixed">
<!--[if lte IE 8]>
<div class="text-center padding-top-50 padding-bottom-50 bg-blue-grey-100">
<p class="browserupgrade font-size-18">你正在使用一个<strong>过时</strong>的浏览器。请<a href="http://browsehappy.com/" target="_blank">升级您的浏览器</a>,以提高您的体验。</p>
</div>
<![endif]-->
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>" >首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>" >发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/center/caiji');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/center/love');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>" class="active">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<!-- 幻灯片-->
<?php $home_slides=sp_getslide("portal_activity"); $home_slides=empty($home_slides)?$default_home_slides:$home_slides; ?>
<div class="slide-box">
<div class="row" >
<div class="col-md-12" style="padding: 0px">
<!-- Swiper -->
<div class="swiper-container">
<div class="swiper-wrapper">
<?php if(is_array($home_slides)): foreach($home_slides as $key=>$vo): ?><div class="swiper-slide"><a href="<?php echo ($vo["slide_url"]); ?>"><img src="<?php echo sp_get_asset_upload_path($vo['slide_pic']);?>" alt=""></a></div><?php endforeach; endif; ?>
</div>
<!-- Add Pagination -->
<div class="swiper-pagination"></div>
<!-- Add Arrows -->
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
</div>
</div>
</div>
<!-- 内容 -->
<div class="hd-box-top" style="width: auto;height: auto;margin-top:2rem">
<div class="hd-box">
<div class="tip">
<ul style="">
<li> <i class="iconfont icon-huo" style="font-size: 2.8rem;color: white"></i></li>
<li style="margin-left: 2px">最火</li>
</ul>
</div>
<div class="huodong-box">
<?php if(is_array($activityRecommend)): foreach($activityRecommend as $key=>$vo): ?><div class="huodong">
<div class="huodong-image-box">
<a href="<?php echo ($vo["hd_url"]); ?>" target="_blank"><img src="<?php echo sp_get_asset_upload_path($vo['hd_img_url']);?>"></a>
</div>
<div class="huodong-bottom-box">
<div class="title">
<?php echo ($vo["hd_name"]); ?></div>
<div class="star">
<i class="iconfont icon-xingzhuang60kaobei2" style="font-size: 1rem;color: black"></i>
<i class="iconfont icon-xingzhuang60kaobei2" style="font-size: 1rem;color: black"></i>
<i class="iconfont icon-xingzhuang60kaobei2" style="font-size: 1rem;color: black"></i>
<i class="iconfont icon-xingzhuang60kaobei2" style="font-size: 1rem;color: grey"></i>
<i class="iconfont icon-xingzhuang60kaobei2" style="font-size: 1rem;color: grey"></i>
</div>
</div>
</div><?php endforeach; endif; ?>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<!--<button class="more-box">点击查看更多>>>></button>-->
<div class="com-mide">
<div class="hd-box">
<div class="tip">
<ul style="">
<li> <i class="iconfont icon-quanbu" style="font-size: 2.8rem;color: white"></i></li>
<li style="margin-left: 2px">全部</li>
</ul>
</div>
<div class="huodong-box">
<?php if(is_array($activity)): foreach($activity as $key=>$vo): ?><div class="huodong">
<div class="huodong-image-box">
<a href="<?php echo ($vo["hd_url"]); ?>" target="_blank"><img src="<?php echo sp_get_asset_upload_path($vo['hd_img_url']);?>"></a>
</div>
<div class="huodong-bottom-box">
<div class="title">
<?php echo ($vo["hd_name"]); ?></div>
<div class="star">
<i class="iconfont icon-xingzhuang60kaobei2" style="font-size: 1rem;color: black"></i>
<i class="iconfont icon-xingzhuang60kaobei2" style="font-size: 1rem;color: black"></i>
<i class="iconfont icon-xingzhuang60kaobei2" style="font-size: 1rem;color: black"></i>
<i class="iconfont icon-xingzhuang60kaobei2" style="font-size: 1rem;color: grey"></i>
<i class="iconfont icon-xingzhuang60kaobei2" style="font-size: 1rem;color: grey"></i>
</div>
</div>
</div><?php endforeach; endif; ?>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<!--<button class="more-box">点击查看更多>>>></button>-->
<!-- foot -->
<div class="footer" >
<div class="footer_1">
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div style="clear: both"></div>
</div>
<div class="footer_2">
<div class="footer_2_1"><a href="#">关注我们</a></div>
<div class="footer_2_2"><a href="#">信息博客</a><br><a href="#">新浪博客</a><br><a href="#">官方微信</a></div>
<div class="footer_2_2"><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a></div>
</div>
<div style="clear: both"></div>
<div class="footer_3">Copyright2016-2017 Heifeiku Leijan Technology Co.Ltd All Rights Reserved<br>
皖ICP备17010401号-2皖公网安备3301080233301号
</div>
</div>
<script type="text/javascript">
//全局变量
var GV = {
ROOT: "/",
WEB_ROOT: "/",
JS_ROOT: "public/js/"
};
</script>
<!-- Placed at the end of the document so the pages load faster -->
<script src="/public/js/jquery.js"></script>
<script src="/public/js/wind.js"></script>
<script src="/themes/simplebootx/Public/assets/simpleboot/bootstrap/js/bootstrap.min.js"></script>
<script src="/public/js/frontend.js"></script>
<script>
$(function(){
$('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });
$("#main-menu li.dropdown").hover(function(){
$(this).addClass("open");
},function(){
$(this).removeClass("open");
});
$.post("<?php echo U('user/index/is_login');?>",{},function(data){
if(data.status==1){
if(data.user.avatar){
$("#main-menu-user .headicon").attr("src",data.user.avatar.indexOf("http")==0?data.user.avatar:"<?php echo sp_get_image_url('[AVATAR]','!avatar');?>".replace('[AVATAR]',data.user.avatar));
}
$("#main-menu-user .user-nicename").text(data.user.user_nicename!=""?data.user.user_nicename:data.user.user_login);
$("#main-menu-user li.login").show();
}
if(data.status==0){
$("#main-menu-user li.offline").show();
}
/* $.post("<?php echo U('user/notification/getLastNotifications');?>",{},function(data){
$(".nav .notifactions .count").text(data.list.length);
}); */
});
;(function($){
$.fn.totop=function(opt){
var scrolling=false;
return this.each(function(){
var $this=$(this);
$(window).scroll(function(){
if(!scrolling){
var sd=$(window).scrollTop();
if(sd>100){
$this.fadeIn();
}else{
$this.fadeOut();
}
}
});
$this.click(function(){
scrolling=true;
$('html, body').animate({
scrollTop : 0
}, 500,function(){
scrolling=false;
$this.fadeOut();
});
});
});
};
})(jQuery);
$("#backtotop").totop();
});
</script>
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/swiper.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/classie.js"></script>
<script src="/themes/simplebootx/Public/new/js/modalEffects.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<!-- Initialize Swiper -->
<script>
var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
paginationClickable: true,
spaceBetween: 30,
centeredSlides: true,
autoplay: 5000,
autoplayDisableOnInteraction: false
});
$(".nav-box .right-menu .close-menu").click(function(){
$(".login-ul").slideUp();
$(".nav-box-ul").slideUp();
$(this).parent().removeClass("active");
});
$(".nav-box .right-menu .open-menu").click(function(){
$(".login-ul").slideDown();
$(".nav-box-ul").slideDown();
$(this).parent().addClass("active");
});
</script>
</body>
</html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo ($user_nicename); ?>欧澜芝的个人主页</title>
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/palette.css">
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/header.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/lable.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
</head>
<body>
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/collect/index');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/love/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<!--用户中心头部-->
<div class="yesterday">
<div class="yesterday_1">
<div class="yesterday_1_1">
<a href="<?php echo U('User/center/index');?>"><img src="<?php echo sp_get_user_avatar_url($avatar);?>"></a>
</div>
<div class="yesterday_1_2">
<div class="yesterday_1_2_1"><span id="fcount"></span></div>
<div class="yesterday_1_2_2"><span id="gcount"></span></div>
</div>
<div class="yesterday_1_3">
<a href="<?php echo U('User/center/fans');?>"> <div class="yesterday_1_3_1">粉丝</div></a>
<div class="yesterday_1_3_2"></div>
<a href="<?php echo U('User/follow/userFollow');?>"> <div class="yesterday_1_3_3">关注</div></a>
</div>
</div>
<div class="yesterday_2">
<div class="yesterday_2_1"><?php echo ($user_nicename); ?></div>
<div class="yesterday_2_2"><?php echo ($signature); ?></div>
</div>
<div class="yesterday_3">
<a href="<?php echo U('user/profile/edit');?>"><div class="yesterday_3_1">账号设置</div></a>
</div>
</div>
<!--红色部分-->
<div class="hongse">
<input type="hidden" name="id" id="id" value="<?php echo ($id); ?>" />
<a href="<?php echo U('User/center/index');?>">
<div class="hongse_1">
<div class="hongse_1_1" ><span id="hcount"></span></div>
<div class="hongse_1_2" >画板</div>
</div>
</a>
<a href="<?php echo U('User/center/caiji');?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1" ><span id="ccount"></span></div>
<div class="hongse_1_2" >采集</div>
</div></a>
<a href="<?php echo U('User/center/love');?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1"><span id="lcount"></span></div>
<div class="hongse_1_2">喜欢</div>
</div></a>
<a href="<?php echo U('User/center/tag');?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1" style="color: white;"><span id="tcount"></span></div>
<div class="hongse_1_2" style="color: white">标签</div>
<div class="heng" style="width: 50px;height: 3px;background: white;margin: 0 auto;margin-top: -0.5rem"></div>
</div></a>
</div>
<!--标签类型-->
<div class="title-detail">
<a href="<?php echo U('User/center/tag');?>">所有标签</a>
<input type="button" name="button" id="button1" value="全选">
<button class="done" id="done">完成</button>
<button class="delete" id="delete">删除</button>
<button class="label-button" style="">编辑标签</button>
</div>
<!--标签内容-->
<div class="lable-detail-box" id="tag-box">
</div>
<!--没有更多-->
<!--<div class="nomore">
<div class="nomore_1" style="font-family: 微软雅黑;font-size:1.4rem">╮(╯﹏╰)╭ 没有更多了.....</div>
<a href="#"><i class="iconfont icon-daosanjiao" style="color: black"></i></a>
</div>-->
<!--script-->
<!-- Initialize Swiper -->
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/new/js/classie.js"></script>
<script src="/themes/simplebootx/Public/new/js/modalEffects.js"></script>
<script type="text/javascript">
var id = $("#id").val();
console.log(id);
$.ajax({
type: "GET",
url: "/index.php?g=portal&m=user&a=userCount",
dataType: "json",
data:{
id:id
},
success:function(data){
console.log(data);
document.getElementById('hcount').innerHTML=data.hcount;
document.getElementById('ccount').innerHTML=data.ccount;
document.getElementById('lcount').innerHTML=data.lcount;
document.getElementById('tcount').innerHTML=data.tcount;
document.getElementById('fcount').innerHTML=data.fcount;
document.getElementById('gcount').innerHTML=data.gcount;
}
});
$(document).ready(function(){
$(".icon").click(function(){
$(this).parent().remove();
});
});
var login = document.getElementById('login');
var over = document.getElementById('over');
function show()
{
login.style.display = "block";
over.style.display = "block";
}
function hide()
{
login.style.display = "none";
over.style.display = "none";
}
$(".nav-box .right-menu .close-menu").click(function(){
$(".login-ul").slideUp();
$(".nav-box-ul").slideUp();
$(this).parent().removeClass("active");
});
$(".nav-box .right-menu .open-menu").click(function(){
$(".login-ul").slideDown();
$(".nav-box-ul").slideDown();
$(this).parent().addClass("active");
});
$.ajax({
type: "GET",
url: "/index.php?g=User&m=center&a=tagView",
dataType: "json",
success:function(data) {
for (var i = 0; i < data.length; i++) {
$("#tag-box").append(
'<a href="/index.php?g=User&m=center&a=tagDetail&id='+data[i].tag_id+'" class="lable">' + data[i].tag_name + '<span class="extra">' + data[i].pcount + '</span><i data-tag-id="'+data[i].tag_id+'" id="tagClick" class="iconfont icon-cha1 icon"></i></a>'
)
}
}
});
$("#tag-box").on('click',".icon",function(){
var tag_id= $(this).attr("data-tag-id");
if(window.confirm('你确定要删除此标签吗?')){
$.ajax({
type: "GET",
url: "/index.php?g=User&m=center&a=deleteTag",
dataType: "json",
data:{
tid:tag_id
},
success:function(data){
window.location.href="/index.php?g=User&m=center&a=tag"
}
})
}else{
window.location.href="/index.php?g=User&m=center&a=tag"
}
});
$(".label-button").click(function(){
$("#button1").show();
$("#done").show();
$("#delete").show();
$(".label-button").hide();
});
$("#delete").click(function(){
$("#button1").hide();
$("#done").hide();
$("#delete").hide();
$(".label-button").show();
});
$("#done").click(function(){
$("#button1").hide();
$("#done").hide();
$("#delete").hide();
$(".label-button").show();
});
</script>
</body>
</html><file_sep><?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
class SixinController extends AdminbaseController{
protected $sixin_model;
public function _initialize()
{
parent::_initialize();
$this->sixin_model=D("Common/Sixin");
}
//私信列表
public function index()
{
$Sixin = M('Sixin'); // 实例化Sixin对象
$count=$Sixin->count();
$page = $this->page($count, 10);
$list = $Sixin->limit($page->firstRow.','.$page->listRows)->order('sx_id')->select();
$this->assign("sixin",$list);
$this->assign("page", $page->show('Admin'));// 赋值分页输出
$this->display();
}
public function add()
{
$this->display();
}
//私信内容添加
public function add_post()
{
$_POST['post']['sx_title']=$_POST['sx_title'];
$_POST['post']['sx_content']=$_POST['sx_content'];
$_POST['post']['sx_time']=date("Y-m-d H:i:s",time());
$sixin=I("post.post");
$sixin['sx_content']=htmlspecialchars_decode($sixin['sx_content']);
$result=$this->sixin_model->add($sixin);
if ($result) {
$this->success("添加成功!");
} else {
$this->error("添加失败!");
}
}
//编辑
public function edit()
{
$id = I("get.id",0,'intval');
$sixin=$this->sixin_model->where(array('sx_id'=>$id))->find();
$this->assign("sixin",$sixin);
$this->display();
}
//编辑提交
public function edit_post()
{
if(IS_POST){
if ($this->sixin_model->create()!==false) {
if ($this->sixin_model->save()!==false) {
$this->success("保存成功!", U("sixin/index"));
} else {
$this->error("保存失败!");
}
} else {
$this->error($this->sixin_model->getError());
}
}
}
//删除
public function delete()
{
if(isset($_POST['ids'])){
$ids = implode(",", $_POST['ids']);
$data['slide_status']=0;
if ($this->sixin_model->where("sx_id in ($ids)")->delete()!==false) {
$this->success("删除成功!");
} else {
$this->error("删除失败!");
}
}else{
$id = I("get.id",0,'intval');
if ($this->sixin_model->delete($id)!==false) {
$this->success("删除成功!");
} else {
$this->error("删除失败!");
}
}
}
}<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登录</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/login.css">
<link rel="stylesheet" media="screen and (max-width: 600px)" href="/themes/simplebootx/Public/new/css/small.css" />
</head>
<body>
<div class="border">
<div class="shuzhe">
<img src="/themes/simplebootx/Public/new/image/shuzhe.jpg">
</div>
<div class="shuzhe1">
<div class="shuzhe2">
<li class="text">WELCOM TO JOIN US</li>
<li class="text-1">we will give you the best service</li>
</div>
<div class="shuzhe3"></div>
<div class="shuzhe4">
<div class="border1">
<div class="border1-1"></div>
</div>
<div class="border2"><div class="border2-1">使用第三方账号登录</div></div>
<div class="border3"><div class="border3-1"></div></div>
</div>
<div class="login">
<div class="login-1"><a href="<?php echo U('api/oauth/login',array('type'=>'qq'));?>"><img src="/themes/simplebootx/Public/new/image/qq.png"></a></div>
<div class="login-1"><a href="<?php echo U('api/oauth/login',array('type'=>'sina'));?>"><img src="/themes/simplebootx/Public/new/image/weibo.png"></a></div>
<div class="login-1"><a href="<?php echo U('api/oauth/login',array('type'=>'weixin'));?>"><img src="/themes/simplebootx/Public/new/image/weixin.png"></a></div>
</div>
<form method="post" class="js-ajax-form" action="<?php echo U('user/login/dologin');?>">
<div class="zhanghao">
<div class="zhanghao-1"> <img src="/themes/simplebootx/Public/new/image/zhanghao.png"></div>
<div class="zhanghao-2"><input type="name" id="input_username" name="username" placeholder="请输入手机号/邮箱/用户名" style=" background: transparent;border:0px;height: 3rem;padding-left: 0.5rem" required></div>
<div class="mima">
<div class="zhanghao-1"> <img src="/themes/simplebootx/Public/new/image/password.png"></div>
<div class="zhanghao-2"><input type="<PASSWORD>" id="input_password" name="password" placeholder="<PASSWORD>"style="background-color: #E7EBEE;border:0px;height: 3rem;padding-left: 0.5rem" required></div>
</div>
</div>
<div class="denglu"><button type="submit" class="js-ajax-submit" style="width: 25rem; height: 4rem;border:0px;background-color: #FE4C7E; color: white;" >登录</button></div>
</form>
<div class="bottom">
<a href="<?php echo U('user/login/forgot_password');?>"> <li class="text-2">忘记密码 ></li></a>
<div class="bottom-1"> <li class="text-3">还没有账号密码?</li></div>
<div class="bottom-2"><a href="<?php echo leuu('user/register/index');?>"><li class="text-4">点击注册 ></li></a></div>
</div>
</div>
</div>
<div class="last">
<div class="last-1"><li class="text-5">Copyright 2006-2016 Built by Asis. All rights reserved.</li></div>
<div class="last-1"><li class="text-5">Read the boring legal stuff</li></div>
</div>
<form id="myForm" style="display:none;" action="<?php echo ($redirecturl); ?>" method="post">
<input id="loginParams" name="params" value="<?php echo ($params); ?>">
</form>
</body>
</html>
<script type="text/javascript">
//全局变量
var GV = {
ROOT: "/",
WEB_ROOT: "/",
JS_ROOT: "public/js/"
};
</script>
<!-- Placed at the end of the document so the pages load faster -->
<script src="/public/js/jquery.js"></script>
<script src="/public/js/wind.js"></script>
<script src="/themes/simplebootx/Public/assets/simpleboot/bootstrap/js/bootstrap.min.js"></script>
<script src="/public/js/frontend.js"></script>
<script>
$(function(){
$('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });
$("#main-menu li.dropdown").hover(function(){
$(this).addClass("open");
},function(){
$(this).removeClass("open");
});
$.post("<?php echo U('user/index/is_login');?>",{},function(data){
if(data.status==1){
if(data.user.avatar){
$("#main-menu-user .headicon").attr("src",data.user.avatar.indexOf("http")==0?data.user.avatar:"<?php echo sp_get_image_url('[AVATAR]','!avatar');?>".replace('[AVATAR]',data.user.avatar));
}
$("#main-menu-user .user-nicename").text(data.user.user_nicename!=""?data.user.user_nicename:data.user.user_login);
$("#main-menu-user li.login").show();
}
if(data.status==0){
$("#main-menu-user li.offline").show();
}
/* $.post("<?php echo U('user/notification/getLastNotifications');?>",{},function(data){
$(".nav .notifactions .count").text(data.list.length);
}); */
});
;(function($){
$.fn.totop=function(opt){
var scrolling=false;
return this.each(function(){
var $this=$(this);
$(window).scroll(function(){
if(!scrolling){
var sd=$(window).scrollTop();
if(sd>100){
$this.fadeIn();
}else{
$this.fadeOut();
}
}
});
$this.click(function(){
scrolling=true;
$('html, body').animate({
scrollTop : 0
}, 500,function(){
scrolling=false;
$this.fadeOut();
});
});
});
};
})(jQuery);
$("#backtotop").totop();
});
</script><file_sep><?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <<EMAIL>>
namespace Portal\Controller;
use Common\Controller\HomebaseController;
class ArticleController extends HomebaseController
{
private $uid;
//文章内页
public function index()
{
$article_id = I('get.pid', 0, 'intval');
$term_id = I('get.cid', 0, 'intval');
$posts_model = M("Posts");
$article = $posts_model
->alias("a")
->field('a.*,c.user_login,c.user_nicename,b.term_id')
->join("__TERM_RELATIONSHIPS__ b ON a.id = b.object_id")
->join("__USERS__ c ON a.post_author = c.id")
->where(array('a.id' => $article_id, 'b.term_id' => $term_id))
->find();
if (empty($article)) {
header('HTTP/1.1 404 Not Found');
header('Status:404 Not Found');
if (sp_template_file_exists(MODULE_NAME . "/404")) {
$this->display(":404");
}
return;
}
$terms_model = M("Terms");
$term = $terms_model->where(array('term_id' => $term_id))->find();
$posts_model->where(array('id' => $article_id))->setInc('post_hits');
$article_date = $article['post_date'];
$join = '__POSTS__ as b on a.object_id =b.id';
$join2 = '__USERS__ as c on b.post_author = c.id';
$term_relationships_model = M("TermRelationships");
$next = $term_relationships_model
->alias("a")
->join($join)->join($join2)
->where(array('b.id' => array('gt', $article_id), "post_date" => array("egt", $article_date), "a.status" => 1, 'a.term_id' => $term_id, 'post_status' => 1))
->order("post_date asc,b.id asc")
->find();
$prev = $term_relationships_model
->alias("a")
->join($join)->join($join2)
->where(array('b.id' => array('lt', $article_id), "post_date" => array("elt", $article_date), "a.status" => 1, 'a.term_id' => $term_id, 'post_status' => 1))
->order("post_date desc,b.id desc")
->find();
$this->assign("next", $next);
$this->assign("prev", $prev);
$smeta = json_decode($article['smeta'], true);
$content_data = sp_content_page($article['post_content']);
$article['post_content'] = $content_data['content'];
$this->assign("page", $content_data['page']);
$this->assign($article);
$this->assign("smeta", $smeta);
$this->assign("term", $term);
$this->assign("article_id", $article_id);
$tplname = $term["one_tpl"];
$tplname = empty($smeta['template']) ? $tplname : $smeta['template'];
$tplname = sp_get_apphome_tpl($tplname, "article");
$this->display(":$tplname");
}
//采集首页
public function posts()
{
$pid = I('get.pid', 0, 'intval');
$post_model = M("Posts");
$posts = $post_model
->alias("a")
->join("tb_users b on a.post_author = b.id")
->where(array("a.id" => $pid))
->field("a.id as pid,b.id as uid,b.user_nicename,a.post_like,a.post_title,a.post_content,a.post_img_url,a.post_date")
->find();
session("uid", $posts["uid"]);
$this->assign("pids",$posts[pid]);
$this->assign($posts);
$this->display(":article");
}
//他的采集
public function hisCollect()
{
$uid = session("uid");
/*
$users_model = M("Users");
$users= $users_model
->where(array("id" =>$uid))
->field("user_nicename,avatar")
->find();
*/
$posts_model = M("Posts");
$count = $posts_model->where(array("post_author"=>$uid))->count();
$page = new \Think\Page($count,16);
$list = $posts_model
->alias("a")
->where(array("post_author"=>$uid))
->join("tb_users c on a.post_author = c.id")
->field("a.id as pid,c.id as uid,a.post_love,a.post_img_url,c.user_nicename")
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($list);
}
//采集喜欢
public function do_love(){
$this->check_login();
$pid = $_POST['id'];
$uid = sp_get_current_userid();
$love_model = M("Love");
$posts_model = M("Posts");
$love=$love_model->where(array("love_users_id"=>$uid,"love_posts_id"=>$pid))->find();
//echo json_encode($love);
if(!$love){
$data["love_posts_id"] = $pid;
$data["love_users_id"] = $uid;
$love_model->add($data);
$post["post_love"] = array("exp","post_love+1");
$posts_model->where(array("id"=>$pid))->save($post);
echo 1;
}else{
$love_model->where(array("love_users_id"=>$uid,"love_posts_id"=>$pid))->delete();
$post["post_love"] = array("exp","post_love-1");
$posts_model->where(array("id"=>$pid))->save($post);
echo 0;
}
}
//采集显示
public function loveView(){
$this->check_login();
$pid = $_POST['id'];
$uid = sp_get_current_userid();
$love_model = M("Love");
$love=$love_model->where(array("love_users_id"=>$uid,"love_posts_id"=>$pid))->find();
if($love){
echo 1;
}
else{
echo 0;
}
}
// 文章点赞
public function do_like()
{
$this->check_login();
$id = I('get.pid', 0, 'intval');//posts表中pid
$posts_model = M("Posts");
$can_like = sp_check_user_action("posts$id", 1);
if ($can_like) {
$posts_model->save(array("id" => $id, "post_like" => array("exp", "post_like+1")));
$this->success("赞好啦!");
} else {
$this->error("您已赞过啦!");
}
}
//点赞数显示
public function likeView(){
$posts_model = M("Posts");
$id = I('get.pid', 0, 'intval');
$likeCount = $posts_model->where(array("id"=>$id))->field("post_like")->find();
echo json_encode($likeCount);
}
// 前台用户添加文章
public function add()
{
$this->check_login();
$this->_getTermTree();
$this->display();
}
// 前台用户添加文章提交
public function add_post()
{
if (IS_POST) {
$this->check_login();
if (empty($_POST['term'])) {
$this->error("请至少选择一个分类!");
}
$posts_model = M('Posts');
$term_relationships_model = M('TermRelationships');
$_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
$_POST['post']['post_date'] = date("Y-m-d H:i:s", time());
$_POST['post']['post_modified'] = date("Y-m-d H:i:s", time());
$_POST['post']['post_author'] = sp_get_current_userid();
$article = I("post.post");
$article['smeta'] = json_encode($_POST['smeta']);
$article['post_content'] = safe_html(htmlspecialchars_decode($article['post_content']));
if ($posts_model->field('post_date,post_author,post_content,post_title,post_modified,smeta')->create($article) !== false) {
$result = $posts_model->add();
if ($result) {
$result = $term_relationships_model->add(array("term_id" => intval($_POST['term']), "object_id" => $result));
if ($result) {
$this->success("文章添加成功!");
} else {
$posts_model->delete($result);
$this->error("文章添加失败!");
}
} else {
$this->error("文章添加失败!");
}
} else {
$this->error($posts_model->getError());
}
}
}
// 前台用户文章编辑
public function edit()
{
$this->check_login();
$id = I("get.id", 0, 'intval');
$terms_model = M('Terms');
$posts_model = M('Posts');
$term_relationship = M('TermRelationships')->where(array("object_id" => $id, "status" => 1))->getField("term_id", true);
$this->_getTermTree();
$post = $posts_model->where(array('id' => $id, 'post_author' => sp_get_current_userid()))->find();
if (!empty($post)) {
$this->assign("post", $post);
$this->assign("smeta", json_decode($post['smeta'], true));
$this->display();
} else {
$this->error('您编辑的文章不存在!');
}
}
// 前台用户文章编辑提交
public function edit_post()
{
if (IS_POST) {
$this->check_login();
$posts_model = M('Posts');
$term_relationships_model = M('TermRelationships');
$_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
$_POST['post']['post_modified'] = date("Y-m-d H:i:s", time());
$article = I("post.post");
$article['smeta'] = json_encode($_POST['smeta']);
$article['post_content'] = safe_html(htmlspecialchars_decode($article['post_content']));
if ($posts_model->field('id,post_author,post_content,post_title,post_modified,smeta')->create($article) !== false) {
$result = $posts_model->where(array('id' => $article['id'], 'post_author' => sp_get_current_userid()))->save($article);
if ($result !== false) {
$this->success("文章编辑成功!");
} else {
$this->error("文章编辑失败!");
}
} else {
$this->error($posts_model->getError());
}
}
}
// 获取文章分类树结构
private function _getTermTree($term = array())
{
$result = M('Terms')->order(array("listorder" => "asc"))->select();
$tree = new \Tree();
$tree->icon = array(' │ ', ' ├─ ', ' └─ ');
$tree->nbsp = ' ';
foreach ($result as $r) {
$r['str_manage'] = '<a href="' . U("AdminTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("AdminTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a class="js-ajax-delete" href="' . U("AdminTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
$r['visit'] = "<a href='#'>访问</a>";
$r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
$r['id'] = $r['term_id'];
$r['parentid'] = $r['parent'];
$r['selected'] = in_array($r['term_id'], $term) ? "selected" : "";
$r['checked'] = in_array($r['term_id'], $term) ? "checked" : "";
$array[] = $r;
}
$tree->init($array);
$str = "<option value='\$id' \$selected>\$spacer\$name</option>";
$terms = $tree->get_tree(0, $str);
$this->assign('terms', $terms);
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: Admin
* Date: 2018/1/7
* Time: 17:07
*/
namespace Portal\Controller;
use Common\Controller\HomebaseController;
use Portal\Model\XingquModel;
/**
* 发现
*/
class FindController extends HomebaseController
{
//发现页
public function index(){
$activity_model = M("Activity");
$activity = $activity_model->order('hd_time')->where("hd_recommend=1")->limit(5)->select();
if($this->user){
$this->assign("isLogin",1);
}
else{
$this->assign("isLogin",0);
}
$this->assign("activity",$activity);
$this->display(":find");
}
//发现页活动
public function active(){
}
//发现页画板和采集
public function getHuabanList(){
$uid = sp_get_current_userid();
$huaban_model = M("Huaban");
$count = $huaban_model->count();
$page = new \Think\Page($count,6);
$Model = M();
$huabancaiji = $Model ->query("Select a.hb_id ,a.hb_name,a.hb_descp,GROUP_CONCAT(id) as pidList, c.hbgz_hbid from tb_huaban a left join tb_posts b on a.hb_id = b.post_hb_id left join (select * from tb_hbgz WHERE hbgz_uid ='$uid')c on c.hbgz_hbid = a.hb_id GROUP BY hb_id limit $page->firstRow,$page->listRows");
echo json_encode($huabancaiji);
}
//发现页兴趣和采集
public function getInterestList(){
$uid = sp_get_current_userid();
$xingqu_model = M("xingqu");
$count = $xingqu_model->count();
$page = new \Think\Page($count,6);
$Model = M();
$xingqucaiji = $Model ->query("Select a.xq_id ,a.xq_name,a.xq_intro,GROUP_CONCAT(id) as pidList,c.xqdgz_xqid from tb_xingqu a left join tb_posts b on a.xq_id = b.post_xq_id left join (select * from tb_xqd_guanzhu where xqdgz_uid = '$uid' )c on c.xqdgz_xqid = a.xq_id GROUP BY xq_id limit $page->firstRow,$page->listRows" );
echo json_encode($xingqucaiji);
}
//获取画板图片地址
public function imgHuaban(){
$huaban_model = M("Huaban");
$id=I("get.id",0,"intval");
$huaban_img = $huaban_model->field("hb_img")->where(array("hb_id" =>$id))->find();
$img = $huaban_img['hb_img'];
$should_show_default=false;
if(empty($img)){
$should_show_default=true;
}else {
if (strpos($img, "http") === 0) {
header("Location: $img");
exit();
} else {
$img_dir = C("UPLOADPATH") . "huaban/";
$img = $img_dir . $img;
if (file_exists($img)) {
$imageInfo = getimagesize($img);
if ($imageInfo !== false) {
$fp = fopen($img, "r");
$file_size = filesize($img);
$mime = $imageInfo['mime'];
header("Content-type: $mime");
header("Accept-Length:" . $file_size);
$buffer = 259 * 313;
$file_count = 0;
//向浏览器返回数据
while (!feof($fp) && $file_count < $file_size) {
$file_content = fread($fp, $buffer);
$file_count += $buffer;
echo $file_content;
flush();
ob_flush();
}
fclose($fp);
} else {
$should_show_default = true;
}
} else {
$should_show_default = true;
}
}
}
if($should_show_default){
$imageInfo = getimagesize("public/images/haibao.png");
if ($imageInfo !== false) {
$mime=$imageInfo['mime'];
header("Content-type: $mime");
echo file_get_contents("public/images/haibao.png");
}
}
exit();
}
}<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo ($user[0]["user_nicename"]); ?>欧澜芝的个人主页</title>
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/new.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/collect.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/palette.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/header.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/lable.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
</head>
<body>
<!--头部-->
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/collect/index');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/love/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<!--他人用户中心头部-->
<div class="yesterday">
<div class="yesterday_1">
<div class="yesterday_1_1">
<a href="#"><img src="<?php echo U('User/public/avatar',array('id'=>$user[0][id]));?>"></a>
</div>
<div class="yesterday_1_2">
<div class="yesterday_1_2_1"><span id="fcount"></span></div>
<div class="yesterday_1_2_2"><span id="gcount"></span></div>
</div>
<div class="yesterday_1_3">
<a href="<?php echo U('Portal/user/fans',array('id'=>$user[0][id]));?>"> <div class="yesterday_1_3_1">粉丝</div></a>
<div class="yesterday_1_3_2"></div>
<a href="<?php echo U('Portal/user/hisUser',array('id'=>$user[0][id]));?>"> <div class="yesterday_1_3_3">关注</div></a>
</div>
</div>
<div class="yesterday_2">
<div class="yesterday_2_1"><?php echo ($user[0]["user_nicename"]); ?></div>
<div class="yesterday_2_2"><?php echo ($user[0]["signature"]); ?></div>
</div>
<div class="yesterday_3" id="guanzhu">
</div>
</div>
<!--红色部分-->
<div class="hongse">
<input type="hidden" name="id" id="id" value="<?php echo ($user[0]["id"]); ?>" />
<a href="<?php echo U('portal/user/index',array('id'=>$user[0][id]));?>">
<div class="hongse_1">
<div class="hongse_1_1" ><span id="hcount"></span></div>
<div class="hongse_1_2" >画板</div>
</div>
</a>
<a href="<?php echo U('Portal/user/caiji',array('id'=>$user[0][id]));?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1" style="color: white;"><span id="ccount"></span></div>
<div class="hongse_1_2" style="color: white">采集</div>
<div class="heng" style="width: 50px;height: 3px;background: white;margin: 0 auto;margin-top: -0.5rem"></div>
</div></a>
<a href="<?php echo U('Portal/user/love',array('id'=>$user[0][id]));?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1"><span id="lcount"></span></div>
<div class="hongse_1_2">喜欢</div>
</div></a>
<a href="<?php echo U('Portal/user/tag',array('id'=>$user[0][id]));?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1"><span id="tcount"></span></div>
<div class="hongse_1_2">标签</div>
</div></a>
</div>
<!--中间部分-->
<div class="lable-detail-box">
<div class="middle-box" id="collect">
</div>
</div>
<div style="clear: both"></div>
</div>
<div class="nomore" id="load">
<div class="nomore_1" style="font-family: 微软雅黑;font-size:1rem">查看更多</div>
<i class="iconfont icon-daosanjiao" style="color: black"></i>
</div>
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/swiper.min.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/assets/js/slippry.min.js"></script>
<script src="/themes/simplebootx/Public/assets/js/classie.js"></script>
<script src="/themes/simplebootx/Public/assets/js/modalEffects.js"></script>
<script>
var id = $("#id").val();
//关注按钮状态
$.ajax({
type: "GET",
url: "/index.php?g=portal&m=user&a=userFollowStatus",
dataType: "json",
data:{
id:id
},
success:function(data){
console.log(data);
if(data==0){
$("#guanzhu").append(
'<div class="yesterday_3_1 " ><button class="userclick">关注+</button></div>'
)
}else{
$("#guanzhu").append(
'<div class="yesterday_3_1 "><button class="userclick">已关注</button></div>'
)
}
}
});
$("body").on("click",".userclick",function()
{
if($(this).text()=="关注+")
{
$.ajax({
type: "GET",
url: "/index.php?g=User&m=follow&a=clickUserFollow",
dataType: "json",
data:{
id:id
},
success:function(data){
if(data.status == 0){
alert(data.info);
$(location).attr('href', data.url);
}
if(data ==1){
alert("亲,自己不能关注自己哦!")
}
}
})
$(this).text("已关注")
}
else{
$.ajax({
type: "GET",
url: "/index.php?g=User&m=follow&a=clickCancelUser",
dataType: "json",
data:{
id:id
},
success:function(data){
}
})
$(this).text("关注+")
}
});
$.ajax({
type: "GET",
url: "/index.php?g=portal&m=user&a=userCount",
dataType: "json",
data:{
id:id
},
success:function(data){
console.log(data);
document.getElementById('hcount').innerHTML=data.hcount;
document.getElementById('ccount').innerHTML=data.ccount;
document.getElementById('lcount').innerHTML=data.lcount;
document.getElementById('tcount').innerHTML=data.tcount;
document.getElementById('fcount').innerHTML=data.fcount;
document.getElementById('gcount').innerHTML=data.gcount;
}
});
var pageIndex=1;
function getPostList(page) {
$.ajax({
type: "GET",
url: "/index.php?g=Portal&m=user&a=collectDetail&p="+page,
dataType: "json",
data:{
id:id
},
success: function (data) {
for (var i = 0; i < data.length; i++) {
var pid = data[i].pid;
var uid = data[i].uid;
$("#collect").append(
'<div class="lable-box">' +
'<div class="img-detail-box">' +
'<a href="index.php?g=&m=Article&a=posts&pid='+pid+'"><img src="index.php?g=&m=Index&a=imgCollect&id=' + pid + '"></a>' +
'</div>' +
'<div class="user-box">' +
'<div class="user-touxiang">' +
'<img src="index.php?g=user&m=public&a=avatar&id=' + uid + '">' +
'</div>' +
'<div class="title-box-right">' +
'<div class="title-left">' +
data[i].post_title +
'</div>' +
'<div class="title-right">' +
'<a href="#">' +
'<i class="iconfont icon-guanzhu" style="color: red"></i>' +
'<font id="num-like" style="color: #989998">'+data[i].post_love+'</font>' +
'</a>' +
/* '<a href="#">' +
'<font style="float: right">' +
'<i class="iconfont icon-fenxiang"></i>' +
'</font>' +*/
'</a>' +
'</div>' +
'</div>' +
'<div class="user-name">'+data[i].user_nicename+'</div>' +
'</div>' +
'</div>'
)
}
if(data.length<16)
{
$("#load").text("╮(・o・)╭没有更多了.....");
}
pageIndex++;
}
});
}
getPostList(pageIndex);
$("#load").click(function()
{
getPostList(pageIndex);
});
</script>
</body>
</html><file_sep><?php
/**
* Created by PhpStorm.
* User: 周前
* Date: 2018/1/14
* Time: 17:34
*/
/**
* Created by PhpStorm.
* User: 周前
* Date: 2018/1/7
* Time: 12:15
*/
namespace User\Controller;
use Common\Controller\MemberbaseController;
/*
* 用户喜欢
*/
class LoveController extends MemberbaseController
{
public function index(){
$uid = sp_get_current_userid();
$huabanUser_model = M("Huaban");
$caijiUser_model = M("Posts");
$loveUser_model = M("Love");
$tagUser_model = M("Tag");
$huabanCount = $huabanUser_model->where(array("hb_u_id"=>$uid))->count();
$caijiCount = $caijiUser_model->where(array("post_author"=>$uid))->count();
$loveCount = $loveUser_model->where(array("love_users_id"=>$uid))->count();
$tagCount = $tagUser_model->where(array("tag_users_id"=>$uid))->count();
$this->assign("huabanCount",$huabanCount);
$this->assign("caijiCount",$caijiCount);
$this->assign("loveCount",$loveCount);
$this->assign("tagCount",$tagCount);
$this->assign($this->user);
$this->display(':love');
}
//用户中心显示用户的喜欢
public function loveView(){
$uid = sp_get_current_userid();
$love_model = M("Love");
$count = $love_model->count();
$page = new \Think\Page($count,16);
$love = $love_model->where(array("love_users_id"=>$uid))
->alias("a")
->join("tb_posts b on a.love_posts_id = b.id")
->join("tb_users c on b.post_author = c.id")
->field("b.id as pid,c.id as uid,b.post_title,b.post_love,c.user_nicename")
->limit($page->firstRow . ',' . $page->listRows)
->select();
echo json_encode($love);
}
}<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>注册</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/login.css">
<link rel="stylesheet" media="screen and (max-width: 600px)" href="/themes/simplebootx/Public/new/css/small.css" />
</head>
<body>
<div class="border">
<div class="shuzhe">
<img src="/themes/simplebootx/Public/new/image/shuzhe.jpg">
</div>
<div class="shuzhe1">
<div class="shuzhe2">
<li class="text">WELCOM TO JOIN US</li>
<li class="text-1">we will give you the best service</li>
</div>
<div class="shuzhe3"></div>
<div class="shuzhe4"style="width: 100%;text-align: center;height: 20px;margin-top: 20px">
<!-- <div class="border1">
<div class="border1-1"></div>
</div>-->
<div class="border2" style="width:100%"><div class="border2-1" style="font-size: 1.1rem;width:100%;text-align: center">---使用第三方账号注册---</div></div>
<!--<div class="border3"><div class="border3-1"></div></div>-->
</div>
<div class="login" style="margin-top: 40px;width:180px;height: 50px;">
<div class="login-1" style="width: 45px;height: 45px;margin-right: 20px;"><a href="<?php echo U('api/oauth/login',array('type'=>'qq'));?>"><img src="/themes/simplebootx/Public/new/image/qq.png" style="width: 100%;height: 100%"></a></div>
<div class="login-1" style="width: 45px;height: 45px;margin-right: 20px;"><a href="<?php echo U('api/oauth/login',array('type'=>'sina'));?>"><img src="/themes/simplebootx/Public/new/image/weibo.png" style="width: 100%;height: 100%"></a></div>
<div class="login-1" style="width: 45px;height: 45px;"><a href="<?php echo U('api/oauth/login',array('type'=>'weixin'));?>"><img src="/themes/simplebootx/Public/new/image/weixin.png" style="width: 100%;height: 100%"></a></div>
</div>
<div style="width:100%;height:auto;text-align:center;margin-top:7rem"><a href="https://hb.pro.youzewang.com/index.php?g=user&m=login&a=reg " style="color:#FE4C7E;text-decoration: none">使用手机号注册 ></a></div>
<div class="bottom" style="margin-top: 100px">
<a href="<?php echo U('user/login/forgot_password');?>"> <li class="text-2">忘记密码 ></li></a>
<div class="bottom-1"> <li class="text-3">已经注册为会员!</li></div>
<div class="bottom-2"><a href="<?php echo leuu('user/login/index');?>"><li class="text-4">点击登录 ></li></a></div>
</div>
</div>
</div>
<div class="last">
<div class="last-1"><li class="text-5">Copyright 2006-2016 Built by Asis. All rights reserved.</li></div>
<div class="last-1"><li class="text-5">Read the boring legal stuff</li></div>
</div>
</body>
</html>
<script type="text/javascript">
//全局变量
var GV = {
ROOT: "/",
WEB_ROOT: "/",
JS_ROOT: "public/js/"
};
</script>
<!-- Placed at the end of the document so the pages load faster -->
<script src="/public/js/jquery.js"></script>
<script src="/public/js/wind.js"></script>
<script src="/themes/simplebootx/Public/assets/simpleboot/bootstrap/js/bootstrap.min.js"></script>
<script src="/public/js/frontend.js"></script>
<script>
$(function(){
$('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });
$("#main-menu li.dropdown").hover(function(){
$(this).addClass("open");
},function(){
$(this).removeClass("open");
});
$.post("<?php echo U('user/index/is_login');?>",{},function(data){
if(data.status==1){
if(data.user.avatar){
$("#main-menu-user .headicon").attr("src",data.user.avatar.indexOf("http")==0?data.user.avatar:"<?php echo sp_get_image_url('[AVATAR]','!avatar');?>".replace('[AVATAR]',data.user.avatar));
}
$("#main-menu-user .user-nicename").text(data.user.user_nicename!=""?data.user.user_nicename:data.user.user_login);
$("#main-menu-user li.login").show();
}
if(data.status==0){
$("#main-menu-user li.offline").show();
}
/* $.post("<?php echo U('user/notification/getLastNotifications');?>",{},function(data){
$(".nav .notifactions .count").text(data.list.length);
}); */
});
;(function($){
$.fn.totop=function(opt){
var scrolling=false;
return this.each(function(){
var $this=$(this);
$(window).scroll(function(){
if(!scrolling){
var sd=$(window).scrollTop();
if(sd>100){
$this.fadeIn();
}else{
$this.fadeOut();
}
}
});
$this.click(function(){
scrolling=true;
$('html, body').animate({
scrollTop : 0
}, 500,function(){
scrolling=false;
$this.fadeOut();
});
});
});
};
})(jQuery);
$("#backtotop").totop();
});
</script><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo ($user[0]["user_nicename"]); ?>欧澜芝的个人主页</title>
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/palette.css">
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/header.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/lable.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link href="/themes/simplebootx/Public/new/css/share.css" rel="stylesheet" type="text/css"><!--分享-->
</head>
<body>
<!--头部-->
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/collect/index');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/love/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<!--他人用户中心头部-->
<div class="yesterday">
<div class="yesterday_1">
<div class="yesterday_1_1">
<a href="#"><img src="<?php echo U('User/public/avatar',array('id'=>$user[0][id]));?>"></a>
</div>
<div class="yesterday_1_2">
<div class="yesterday_1_2_1"><span id="fcount"></span></div>
<div class="yesterday_1_2_2"><span id="gcount"></span></div>
</div>
<div class="yesterday_1_3">
<a href="<?php echo U('Portal/user/fans',array('id'=>$user[0][id]));?>"> <div class="yesterday_1_3_1">粉丝</div></a>
<div class="yesterday_1_3_2"></div>
<a href="<?php echo U('Portal/user/hisUser',array('id'=>$user[0][id]));?>"> <div class="yesterday_1_3_3">关注</div></a>
</div>
</div>
<div class="yesterday_2">
<div class="yesterday_2_1"><?php echo ($user[0]["user_nicename"]); ?></div>
<div class="yesterday_2_2"><?php echo ($user[0]["signature"]); ?></div>
</div>
<div class="yesterday_3" id="guanzhu">
</div>
</div>
<!--红色部分-->
<div class="hongse">
<input type="hidden" name="tid" id="tid" value="<?php echo ($tid); ?>">
<input type="hidden" name="id" id="id" value="<?php echo ($user[0]["id"]); ?>" />
<a href="<?php echo U('portal/user/index',array('id'=>$user[0][id]));?>">
<div class="hongse_1">
<div class="hongse_1_1" ><span id="hcount"></span></div>
<div class="hongse_1_2" >画板</div>
</div>
</a>
<a href="<?php echo U('portal/user/caiji',array('id'=>$user[0][id]));?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1"><span id="ccount"></span></div>
<div class="hongse_1_2">采集</div>
</div></a>
<a href="<?php echo U('portal/user/love',array('id'=>$user[0][id]));?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1"><span id="lcount"></span></div>
<div class="hongse_1_2">喜欢</div>
</div></a>
<a href="<?php echo U('portal/user/tag',array('id'=>$user[0][id]));?>">
<div class="hongse_2"></div>
<div class="hongse_1">
<div class="hongse_1_1" style="color: white;"><span id="tcount"></span></div>
<div class="hongse_1_2" style="color: white">标签</div>
<div class="heng" style="width: 50px;height: 3px;background: white;margin: 0 auto;margin-top: -0.5rem"></div>
</div></a>
</div>
<!--标签类型-->
<div class="title-detail">
<a href="<?php echo U('Portal/user/tag',array('id'=>$user[0][id]));?>">所有标签</a> <font class="address-lable" style="color: #777777"> » <?php echo ($tagname); ?></font>
<div style="float: right"><?php echo ($pcount); ?> 个包含:“<?php echo ($tagname); ?>”标签的采集</div>
</div>
<!--标签内容-->
<div class="lable-detail-box">
<div class="middle-box" id="tag-box">
</div>
</div>
<!--没有更多-->
<div class="nomore" id="load">
<div class="nomore_1" style="font-family: 微软雅黑;font-size:1.4rem">╮(╯﹏╰)╭ 查看更多</div>
<i class="iconfont icon-daosanjiao" style="color: black"></i>
</div>
<!--底部-->
<!--
<div class="footer">
<div class="footer_1">
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div style="clear: both"></div>
</div>
<div class="footer_2">
<div class="footer_2_1"><a href="#">关注我们</a></div>
<div class="footer_2_2"><a href="#">信息博客</a><br><a href="#">新浪博客</a><br><a href="#">官方微信</a></div>
<div class="footer_2_2"><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a></div>
</div>
<div style="clear: both"></div>
<div class="footer_3">Copyright2016-2017 Heifeiku Leijan Technology Co.Ltd All Rights Reserved<br>
皖ICP备17010401号-2皖公网安备3301080233301号
</div>
</div>
-->
<!--script-->
<!-- Initialize Swiper -->
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/themes/simplebootx/Public/new/js/share.js"></script><!--分享-->
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/new/js/classie.js"></script>
<script src="/themes/simplebootx/Public/new/js/modalEffects.js"></script>
<script type="text/javascript">
var tid = $("#tid").val();
var id = $("#id").val();
//关注按钮状态
$.ajax({
type: "GET",
url: "/index.php?g=portal&m=user&a=userFollowStatus",
dataType: "json",
data:{
id:id
},
success:function(data){
// console.log(data);
if(data==0){
$("#guanzhu").append(
'<div class="yesterday_3_1 " ><button class="userclick">关注+</button></div>'
)
}else{
$("#guanzhu").append(
'<div class="yesterday_3_1 "><button class="userclick">已关注</button></div>'
)
}
}
});
$("body").on("click",".userclick",function()
{
if($(this).text()=="关注+")
{
$.ajax({
type: "GET",
url: "/index.php?g=User&m=follow&a=clickUserFollow",
dataType: "json",
data:{
id:id
},
success:function(data){
if(data.status == 0){
alert(data.info);
$(location).attr('href', data.url);
}
if(data ==1){
alert("亲,自己不能关注自己哦!")
}
}
})
$(this).text("已关注")
}
else{
$.ajax({
type: "GET",
url: "/index.php?g=User&m=follow&a=clickCancelUser",
dataType: "json",
data:{
id:id
},
success:function(data){
}
})
$(this).text("关注+")
}
});
var pageIndex=1;
function getPostList(page) {
$.ajax({
type: "GET",
url: "/index.php?g=Portal&m=user&a=tagDetailView&p="+page,
dataType: "json",
data: {
id:tid
},
success: function (data) {
// console.log(data);
for(var i=0;i<data.length;i++) {
var pid = data[i].pid;
var uid = data[i].uid;
$("#tag-box").append(
'<div class="lable-box">' +
'<div class="img-detail-box">' +
'<a href="index.php?g=&m=Article&a=posts&pid='+pid+'"><img src="index.php?g=&m=Index&a=imgCollect&id=' + pid + '"></a>' +
'</div>' +
'<div class="user-box">' +
'<div class="user-touxiang">' +
'<img src="index.php?g=user&m=public&a=avatar&id=' + uid + '">' +
'</div>' +
'<div class="title-box-right">' +
'<div class="title-left">' +
data[i].post_title +
'</div>' +
'<div class="title-right">' +
'<a href="#">' +
'<i class="iconfont icon-guanzhu" style="color: red"></i>' +
'<font id="num-like" style="color: #989998">12'+data[i].post_love+'</font>' +
'</a>' +
/* '<a href="#">' +
'<font style="float: right">' +
'<i class="iconfont icon-fenxiang"></i>' +
'</font>' +*/
'</a>' +
'</div>' +
'</div>' +
'<div class="user-name">'+data[i].user_nicename+'</div>' +
'</div>' +
'</div>'
)
}
if(data.length<16)
{
$("#load").text("╮(・o・)╭没有更多了.....");
}
pageIndex++;
}
});
}
getPostList(pageIndex);
$("#load").click(function()
{
getPostList(pageIndex);
});
$.ajax({
type: "GET",
url: "/index.php?g=portal&m=user&a=userCount",
dataType: "json",
data:{
id:id
},
success:function(data){
document.getElementById('hcount').innerHTML=data.hcount;
document.getElementById('ccount').innerHTML=data.ccount;
document.getElementById('lcount').innerHTML=data.lcount;
document.getElementById('tcount').innerHTML=data.tcount;
document.getElementById('fcount').innerHTML=data.fcount;
document.getElementById('gcount').innerHTML=data.gcount;
}
});
$('#share').shareConfig({
Shade : true, //是否显示遮罩层
Event:'click', //触发事件
Content : 'Share', //内容DIV ID
Title : '分享给朋友' //显示标题
});
</script>
<script type="text/javascript">
var login = document.getElementById('login');
var over = document.getElementById('over');
function show()
{
login.style.display = "block";
over.style.display = "block";
}
function hide()
{
login.style.display = "none";
over.style.display = "none";
}
$(".nav-box .right-menu .close-menu").click(function(){
$(".login-ul").slideUp();
$(".nav-box-ul").slideUp();
$(this).parent().removeClass("active");
});
$(".nav-box .right-menu .open-menu").click(function(){
$(".login-ul").slideDown();
$(".nav-box-ul").slideDown();
$(this).parent().addClass("active");
});
</script>
</body>
</html><file_sep><?php
/**
* Created by PhpStorm.
* User: 周前
* Date: 2018/1/17
* Time: 14:09
*/
namespace User\Controller;
use Common\Controller\MemberbaseController;
/*
* 用户画板行为
*/
class FollowController extends MemberbaseController
{
//用户关注的兴趣点
public function interestFollow()
{
$this->assign($this->user);
$this->display(":Follow/interest");
}
//用户关注的兴趣点详情
public function interestDetail()
{
$uid = sp_get_current_userid();
$Model = M(); // 实例化一个model对象 没有对应任何数据表
$xingqu = $Model->query("select b.xq_id,b.xq_name,GROUP_CONCAT(c.id) as pidList from (select * from tb_xqd_guanzhu where xqdgz_uid='$uid') a left join tb_xingqu b on a.xqdgz_xqid = b.xq_id left join tb_posts c on b.xq_id = c.post_xq_id group by xq_id ");
echo json_encode($xingqu);
}
//用户关注的用户
public function userFollow()
{
$this->assign($this->user);
$this->display(":Follow/user");
}
//用户关注的用户详情
public function userDetail()
{
$uid = sp_get_current_userid();
$Model = M(); // 实例化一个model对象 没有对应任何数据表
$yonghu = $Model->query("select usergz_uid_childid,user_nicename,caiji_count,count(usergz_uid_childid) as huaban_count,pidList FROM
(
select usergz_uid_childid,user_nicename,count(usergz_uid_childid) as caiji_count,pidList from
(
select usergz_uid_childid,b.user_nicename ,GROUP_CONCAT(c.id) as pidList from (select usergz_uid_childid from tb_yonghu_gz where usergz_uid_pid='$uid') a
left join tb_users b on a.usergz_uid_childid = b.id
left join tb_posts c on a.usergz_uid_childid = c.post_author
) a GROUP BY usergz_uid_childid
) a
left join tb_huaban d on a.usergz_uid_childid = d.hb_u_id ");
echo json_encode($yonghu);
}
public function fansDetail(){
$uid = sp_get_current_userid();
$Model = M(); // 实例化一个model对象 没有对应任何数据表
$yonghu = $Model->query("select usergz_uid_pid,user_nicename,caiji_count,count(usergz_uid_pid) as huaban_count FROM
(
select usergz_uid_pid,user_nicename,count(usergz_uid_pid) as caiji_count from
(
select usergz_uid_pid,b.user_nicename from (select usergz_uid_pid from tb_yonghu_gz where usergz_uid_childid='$uid') a
left join tb_users b on a.usergz_uid_pid = b.id
left join tb_posts c on a.usergz_uid_pid = c.post_author
) a GROUP BY usergz_uid_pid
) a
left join tb_huaban d on a.usergz_uid_pid = d.hb_u_id GROUP BY usergz_uid_pid ");
echo json_encode($yonghu);
}
//用户关注的画板
public function drawFollow()
{
$this->assign($this->user);
$this->display(":Follow/draw");
}
//用户关注的画板详情
public function drawDetail()
{
$uid = sp_get_current_userid();
$Model = M(); // 实例化一个model对象 没有对应任何数据表
$huaban = $Model->query("select b.hb_id,b.hb_name,GROUP_CONCAT(c.id) as pidList from (select * from tb_hbgz where hbgz_uid='$uid') a left join tb_huaban b on a.hbgz_hbid = b.hb_id left join tb_posts c on b.hb_id = c.post_hb_id group by hb_id ");
echo json_encode($huaban);
}
//点击关注画板
public function clickDrawFollow()
{
$uid = sp_get_current_userid();
$hid = I('get.id', 0, 'intval');
$data["hbgz_uid"] = $uid;
$data["hbgz_hbid"] = $hid;
$data["hbgz_create_time"] = date("Y-m-d H:i:s");
$hbgz_model = M("Hbgz");
$huaban_model = M("Huaban");
$hbgz = $hbgz_model->where($data)->select();
if (!$hbgz) {
$huaban["hb_love_count"] = array("exp","hb_love_count+1");
$huaban_model->where(array("hb_id"=>$hid))->save($huaban);
$hbgz_model->add($data);
}
}
//点击取消关注画板
public function clickCancelDraw(){
$uid = sp_get_current_userid();
$hid = I('get.id', 0, 'intval');
$data["hbgz_uid"] = $uid;
$data["hbgz_hbid"] = $hid;
$hbgz_model = M("Hbgz");
$huaban_model = M("Huaban");
$hbgz = $hbgz_model->where($data)->select();
if($hbgz_model){
$huaban["hb_love_count"] = array("exp","hb_love_count-1");
$huaban_model->where(array("hb_id"=>$hid))->save($huaban);
$hbgz_model->where($data)->delete();
}
}
//点击关注兴趣点
public function clickInterestFollow(){
$uid = sp_get_current_userid();
$xid = I('get.id', 0, 'intval');
$data["xqdgz_uid"] = $uid;
$data["xqdgz_xqid"] = $xid;
$data["xqdgz_create_time"] = date("Y-m-d H:i:s");
$xqdgz_model = M("Xqd_guanzhu");
$xqd_model = M("Xingqu");
$xqdgz = $xqdgz_model->where($data)->select();
$xqd["xq_love_count"] = array("exp","xq_love_count+1");
if(!$xqdgz){
$xqdgz_model->add($data);
$xqd_model->where(array("xq_id"=>$xid))->save($xqd);
}
}
//点击取消关注兴趣点
public function clickCancelInterest(){
$uid = sp_get_current_userid();
$xid = I('get.id', 0, 'intval');
$data["xqdgz_uid"] = $uid;
$data["xqdgz_xqid"] = $xid;
$xqd_model = M("Xingqu");
$xqdgz_model = M("Xqd_guanzhu");
$xqd["xq_love_count"] = array("exp","xq_love_count-1");
$xqdgz = $xqdgz_model->where($data)->select();
if($xqdgz){
$xqdgz_model->where($data)->delete();
$xqd_model->where(array("xq_id"=>$xid))->save($xqd);
}
}
//用户点击关注用户
public function clickUserFollow(){
$this->check_login();
$uid = sp_get_current_userid();
$upid = I('get.id', 0, 'intval');
$data["usergz_uid_pid"] = $uid;
$data["usergz_uid_childid"] = $upid;
$data["usergz_create_time"] = date("Y-m-d H:i:s");
$yonghu_model = M("Yonghu_gz");
$yonghu = $yonghu_model->where($data)->select();
if(!$yonghu){
if($uid!=$upid){
$yonghu_model->add($data);
}else{
echo 1;
}
}
}
//用户点击取消关注用户
public function clickCancelUser(){
$uid = sp_get_current_userid();
$upid = I('get.id', 0, 'intval');
$yonghu_model = M("Yonghu_gz");
$data["usergz_uid_pid"] = $uid;
$data["usergz_uid_childid"] = $upid;
$yonghu = $yonghu_model->where($data)->select();
if($yonghu){
$yonghu_model->where($data)->delete();
}
}
}<file_sep>!
function() {
"undefined" == typeof window.HUABAN_GLOBAL && (window.HUABAN_GLOBAL = {},
function(e, t, n) {
{
var i = "1.1.2",
o = t.documentElement,
r = /(^\n+)|(\n+$)/g,
a = /^(?:\{.*\}|\[.*\])$/,
l = /-([a-z])/gi,
s = /\r\n/g,
c = /[\-\+0-9\.]/gi,
u = /\s+/,
p = /\?/,
d = /opacity=([^)]*)/,
h = /^[\],:{}\s]*$/,
g = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
f = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
m = /(?:^|:|,)(?:\s*\[)+/g,
v = "height margin-top margin-bottom padding-top padding-bottom".split(" "),
b = {},
x = {},
$ = [],
y = function() {
z($,
function(e) {
e()
}),
t.removeEventListener("DOMContentLoaded", y, !1)
},
w = function(e, n) {
var i = typeof n;
if ("string" === i) {
var o = e && e.ownerDocument || t,
r = o.createDocumentFragment(),
a = H("div");
for (a.innerHTML = n; null != a.childNodes[0];) r.appendChild(a.childNodes[0]);
n = r,
a = null
}
return "number" === i && (n += ""),
n
},
U = function(e, t) {
if (null !== e) {
if (t === n) return e;
var i = 0,
o = e.length;
if (o !== n && o > 0) {
for (; o > i && t.call(e[i], e[i], e[i++]) !== !1;);
return e
}
return t.call(e, e)
}
},
N = function(e, n, i, o) {
return U(e,
function(e) {
var r, a, l = {},
s = "show" === n,
c = e.style,
u = e._display;
u || (u = j.get(e, "display"), ("none" === u || "inherit" === u) && (r = P(t.body, H(e.nodeName)), u = j.get(r, "display"), W(r)), e._display = u),
s ? c.display = u: u = "none",
i ? (a = j.get(e, "overflow"), c.overflow = "hidden", l.opacity = s ? {
from: 0,
to: 1
}: {
from: 1,
to: 0
},
z(v,
function(t) {
l[t] = s ? {
from: 0,
to: j.get(e, t)
}: 0
}), J(e, l, i,
function() {
z(v,
function(t) {
O.set(e, t, "")
}),
c.filter = c.opacity = c.overflow = "",
c.display = u,
o && o.call(e)
})) : c.display = u
})
},
A = function(e, t) {
if ("object" == typeof t) {
var n = [];
return z(t,
function(t, i) {
n.push("object" == typeof t ? A(e + "[" + i + "]", t) : e + "[" + K(i) + "]=" + K(t))
}),
n.join("&")
}
return K(e) + "=" + K(t)
},
k = t.removeEventListener ?
function(e, t, n) {
e.removeEventListener(t, n, !1)
}: function(e, t, n) {
e.detachEvent("on" + t, n)
},
B = function() {
try {
return localStorage.setItem("test", "test"),
localStorage.removeItem("test"),
!0
} catch(e) {
return ! 1
}
} (),
S = {},
E = S.$ = function(e) {
return t.getElementById(e)
},
z = S.$each = function(e, t) {
var n, i = 0,
o = e.length,
r = typeof e,
a = "object" === r;
if (a && o - 1 in e) for (; o > i && t.call(e[i], e[i++], i) !== !1;);
else if (a) for (n in e) t.call(e[n], e[n], n);
else t.call(e, e, 0);
return e
},
_ = (S.$id = function(e, t) {
var n, i = [];
return z(e instanceof Array ? e: e.split(" "),
function(e) {
n = E(e),
null !== n && i.push(n)
}),
t ? U(i, t) : i
},
S.$dom = function(e, t) {
return t && (e.length ? U(e, t) : t(e)),
e
},
S.$tag = function(e, t, n) {
var i = [],
o = e.getElementsByTagName(t),
r = o.length,
a = 0;
if (r > 0) {
for (; r > a; a++) i.push(o[a]);
return U(i, n)
}
return i
}),
H = (S.$class = t.getElementsByClassName ?
function(e, t, n) {
var i = [],
o = e.getElementsByClassName(t),
r = o.length,
a = 0;
if (r > 0) {
for (; r > a; a++) i.push(o[a]);
return U(i, n)
}
return i
}: function(e, t, n) {
var i = [],
o = new RegExp("(^|\\s)" + t + "(\\s|$)");
return _(e, "*",
function(e) {
o.test(e.className) && i.push(e)
}),
U(i, n)
},
S.$select = t.querySelectorAll ?
function(e, n) {
return U(t.querySelectorAll(e), n)
}: function(e, n) {
var i = S.Qselector.styleSheet,
o = [];
return i.addRule(e, "q:a"),
_(t, "*",
function(e) {
"a" === e.currentStyle.q && o.push(e)
}),
i.cssText = "",
U(o, n)
},
S.$new = function(e, n) {
var i = t.createElement(e);
if (n) try {
return z(n,
function(e, t) {
switch (t) {
case "innerHTML":
case "html":
F(i, e);
break;
case "className":
case "class":
q.set(i, e);
break;
case "text":
D(i, e);
break;
default:
T.set(i, t, e)
}
}),
i
} catch(o) {} finally {
i = null
}
return i
}),
C = S.$string = {
camelCase: function(e) {
return e.replace("-ms-", "ms-").replace(l,
function(e, t) {
return (t + "").toUpperCase()
})
},
replace: function(e, t) {
for (var n in t) e = e.replace(new RegExp(n, "ig"), t[n]);
return e
},
slashes: function(e) {
return C.replace(e, {
"\\\\": "\\\\",
"\b": "\\b",
" ": "\\t",
"\n": "\\n",
"\r": "\\r",
'"': '\\"'
})
},
trim: "".trim && "tes ts" === " tes ts ".trim() ?
function(e) {
return e.trim()
}: function(e) {
return (e + "").replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "")
}
},
T = S.$attr = {
get: function(e, t) {
return e.getAttribute(t)
},
set: function(e, t, n) {
return U(e,
function(e) {
e.setAttribute(t, n)
})
},
remove: function(e, t) {
return U(e,
function(e) {
e.removeAttribute(t)
})
}
},
L = S.$data = {
get: function(e, t) {
var n = T.get(e, "data-" + t);
return "true" === n ? !0 : "false" === n ? !1 : "null" === n ? "": null === n ? "": "" === n ? "": !isNaN(parseFloat(n)) && isFinite(n) ? +n: a.test(n) ? X.decode(n) : n
},
set: function(e, t, n) {
return U(e,
function(e) {
return n = "object" == typeof n ? X.encode(n) : n,
"object" == typeof t ? z(t,
function(t, n) {
T.set(e, "data-" + n, t)
}) : T.set(e, "data-" + t, n),
e
})
},
remove: function(e, t) {
return U(e,
function(e) {
T.remove(e, "data-" + t)
})
}
},
M = (S.$storage = B ? {
set: function(e, t) {
localStorage[e] = "object" == typeof t ? X.encode(t) : t
},
get: function(e) {
var t = localStorage[e];
return X.isJSON(t) ? X.decode(t) : t || ""
},
remove: function(e) {
return localStorage.removeItem(e),
!0
}
}: {
set: function(e, t) {
t = "object" == typeof t ? X.encode(t) : t,
L.set(S.storage, e, t),
S.storage.save("Qstorage")
},
get: function(e) {
return S.storage.load("Qstorage"),
L.get(S.storage, e) || ""
},
remove: function(e) {
return S.storage.load("Qstorage"),
L.remove(S.storage, e),
!0
}
},
S.$event = {
guid: 0,
global: {},
handler: {
call: function(e, t, n, i) {
var o = M.handler;
return n.currentTarget = t,
(i === !1 || i.call(t, n) === !1) && (o.stopPropagation.call(n), o.preventDefault.call(n), e.isStopPropagation = !0),
e
},
preventDefault: function() {
var e = this.originalEvent;
e.preventDefault && e.preventDefault()
},
stopPropagation: function() {
var e = this.originalEvent;
e.stopPropagation && e.stopPropagation()
},
stopImmediatePropagation: function() {
this.stopPropagation()
},
mouseenter: function(e) {
return function(t) {
var n = t.relatedTarget;
if (this !== n) {
for (; n && n !== this;) n = n.parentNode;
n !== this && e.call(this, t)
}
}
}
},
on: function(e, i, o, r, a) {
return U(e,
function(e) {
if (3 === e.nodeType || 8 === e.nodeType) return ! 1;
if ("object" == typeof i) {
"string" != typeof o && (r = r || o, o = n);
for (type in i) M.on(e, type, o, r, i[type]);
return this
}
null == r && null == a ? (a = o, r = o = n) : null == a && ("string" == typeof o ? (a = r, r = n) : (a = r, r = o, o = n)),
e.guid === n && (M.guid++, e.guid = M.guid, M.global[M.guid] = {});
var l = e.guid,
s = (o || "") + i,
c = M.global[l][s];
return c || (M.global[l][s] = {}),
delegate_fn = function(i) {
var l, s, c = {},
u = "altKey bubbles button buttons cancelable relatedTarget clientX clientY ctrlKey fromElement offsetX offsetY pageX pageY screenX screenY shiftKey toElement timeStamp".split(" ");
if (z(u,
function(e, t) {
i[e] !== n && (c[e] = i[e])
}), c.originalEvent = i, c.preventDefault = M.handler.preventDefault, c.stopPropagation = M.handler.stopPropagation, c.stopImmediatePropagation = M.handler.stopImmediatePropagation, c.delegateTarget = e, c.isStopPropagation = !1, c.data = r, s = c.target = o ? i.target || i.srcElement || t: e, c.which = i.which || i.charCode || i.keyCode, c.metaKey = i.metaKey || i.ctrlKey, o) for (l = o ? o.replace(".", "") : ""; s !== e; s = s.parentNode) {
if (i.isStopPropagation === !0) return ! 1;
if (null === s || s === t.body) return ! 1; (s.tagName.toLowerCase() === o || q.has(s, l)) && (i = M.handler.call(i, s, c, a))
} else M.handler.call(i, s, c, a)
},
e.addEventListener ? (("mouseenter" === i || "mouseleave" === i) && (i = "mouseenter" === i ? "mouseover": "mouseout", delegate_fn = M.handler.mouseenter(delegate_fn)), e.addEventListener(i, delegate_fn, "blur" === i || "focus" === i)) : e.attachEvent("on" + i, delegate_fn),
M.global[l][s][a + ""] = delegate_fn,
e
})
},
off: function(e, t, n, i) {
if ("object" == typeof t) {
for (type in t) M.off(e, type, t[type]);
return this
}
null == i && (i = n, n = null);
var o = e.guid,
r = (n || "") + t;
fn_key = i + "",
i ? (k(e, t, M.global[o][r][fn_key]), delete M.global[o][r][fn_key]) : (z(M.global[o][r],
function(n) {
k(e, t, n)
}), delete M.global[o][r])
}
}),
I = (S.$clear = function(e) {
return e && (clearTimeout(e), clearInterval(e)),
null
},
S.$ready = function(e) {
if ("complete" === t.readyState) return setTimeout(e, 1);
if (t.addEventListener) return $.push(e),
void t.addEventListener("DOMContentLoaded", y, !1);
var n = function() {
try {
o.doScroll("left")
} catch(t) {
return void setTimeout(n, 1)
}
e()
};
n()
}),
O = S.$css = {
get: function(e, t) {
if ("object" == typeof t) {
var n = {};
return z(t,
function(t) {
n[t] = j.get(e, t)
}),
n
}
return j.get(e, t)
},
set: function(e, t, n) {
return U(e,
function(e) {
return "object" == typeof t ? z(t,
function(t, n) {
j.set(e, C.camelCase(n), O.fix(n, t))
}) : j.set(e, C.camelCase(t), O.fix(t, n)),
e
})
},
number: {
fontWeight: !0,
lineHeight: !0,
opacity: !0,
zIndex: !0
},
unit: function(e, t) {
if (O.number[e]) return "";
var n = (t + "").replace(c, "");
return "" === n ? "px": n
},
fix: function(e, t) {
return "number" != typeof t || O.number[e] || (t += "px"),
null === t && isNaN(t) ? !1 : t
}
},
j = S.$style = {
get: e.getComputedStyle ?
function(e, n) {
if (null !== e) {
var i = t.defaultView.getComputedStyle(e, null).getPropertyValue(n);
return "auto" === i || "" === i ? 0 : i
}
return ! 1
}: function(e, t) {
if (null !== e) {
var n = "opacity" === t ? d.test(e.currentStyle.filter) ? .01 * parseFloat(RegExp.$1) + "": 1 : e.currentStyle[C.camelCase(t)];
return "auto" === n ? 0 : n
}
return ! 1
},
set: o.style.opacity !== n ?
function(e, t, n) {
return U(e,
function(e) {
return e.style[t] = n,
!0
})
}: function(e, t, n) {
return U(e,
function(e) {
return e.currentStyle && e.currentStyle.hasLayout || (e.style.zoom = 1),
"opacity" === t ? (e.style.filter = "alpha(opacity=" + 100 * n + ")", e.style.zoom = 1) : e.style[t] = n,
!0
})
}
},
P = (S.$pos = function(e, t, n) {
return U(e,
function(e) {
return j.set(e, "left", t + "px"),
j.set(e, "top", n + "px"),
e
})
},
S.$offset = function(n) {
var i = t.body,
r = n.getBoundingClientRect();
return {
top: r.top + (e.scrollY || i.parentNode.scrollTop || n.scrollTop) - (o.clientTop || i.clientTop || 0),
left: r.left + (e.scrollX || i.parentNode.scrollLeft || n.scrollLeft) - (o.clientLeft || i.clientLeft || 0),
width: n.offsetWidth,
height: n.offsetHeight
}
},
S.$append = function(e, t) {
return U(e,
function(e) {
return e.appendChild(w(e, t))
})
}),
W = (S.$prepend = function(e, t) {
return U(e,
function(e) {
return e.firstChild ? e.insertBefore(w(e, t), e.firstChild) : e.appendChild(w(e, t))
})
},
S.$before = function(e, t) {
return U(e,
function(e) {
return e.parentNode.insertBefore(w(e, t), e)
})
},
S.$after = function(e, t) {
return U(e,
function(e) {
return e.nextSibling ? e.parentNode.insertBefore(w(e, t), e.nextSibling) : e.parentNode.appendChild(w(e, t))
})
},
S.$remove = function(e) {
return U(e,
function(e) {
return R(e),
e.guid !== n && delete M.global[e.guid],
null !== e && e.parentNode ? e.parentNode.removeChild(e) : e
})
}),
R = S.$empty = function(e) {
return U(e,
function(e) {
for (; e.firstChild;) 1 === e.nodeType && e.guid !== n && delete M.global[e.guid],
e.removeChild(e.firstChild);
return e
})
},
F = S.$html = function(e, t) {
return U(e,
function(e) {
if (t) {
try {
e.innerHTML = t
} catch(n) {
P(R(e), t)
}
return e
}
return 1 === e.nodeType ? e.innerHTML: null
})
},
D = S.$text = function(e, n) {
return U(e,
function(e) {
if (n) return R(e),
e.appendChild(t.createTextNode(n)),
e;
var i, o = "",
a = e.textContent;
if ((a || e.innerText) === e.innerHTML) o = a ? C.trim(e.textContent.replace(r, "")) : e.innerText.replace(s, "");
else for (e = e.firstChild; e; e = e.nextSibling) i = e.nodeType,
3 === i && "" !== C.trim(e.nodeValue) && (o += e.nodeValue.replace(r, "") + (e.nextSibling && e.nextSibling.tagName && "br" !== e.nextSibling.tagName.toLowerCase() ? "\n": "")),
(1 === i || 2 === i) && (o += D(e) + ("block" === j.get(e, "display") || "br" === e.tagName.toLowerCase() ? "\n": ""));
return o
})
},
q = S.$className = {
add: function(e, t) {
return U(e,
function(e) {
if ("" === e.className) e.className = t;
else {
var n = e.className,
i = [];
z(t.split(u),
function(e) {
new RegExp("\\b(" + e + ")\\b").test(n) || i.push(" " + e)
}),
e.className += i.join("")
}
return e
})
},
set: function(e, t) {
return U(e,
function(e) {
return e.className = t,
e
})
},
has: function(e, t) {
return new RegExp("\\b(" + t.split(u).join("|") + ")\\b").test(e.className)
},
remove: function(e, t) {
return U(e,
function(e) {
return e.className = t ? C.trim(e.className.replace(new RegExp("\\b(" + t.split(u).join("|") + ")\\b"), "").split(u).join(" ")) : "",
e
})
}
},
G = S.$hide = function(e, t, n) {
N(e, "hide", t, n)
},
Q = S.$show = function(e, t, n) {
N(e, "show", t, n)
},
J = (S.$toggle = function(e, t, n) {
return U(e,
function(e) {
"none" === j.get(e, "display") ? Q(e, t, n) : G(e, t, n)
})
},
S.$animate = function() {
var e = o.style;
return e.webkitTransition !== n || e.MozTransition !== n || e.OTransition !== n || e.msTransition !== n || e.transition !== n
} () ?
function() {
var e = o.style,
t = e.webkitTransition !== n ? "Webkit": e.MozTransition !== n ? "Moz": e.OTransition !== n ? "O": e.msTransition !== n ? "ms": "",
i = t + "Transition";
return function(e, t, o, r) {
return U(e,
function(e) {
var a, l = [],
s = [],
c = [],
u = [],
p = e.style;
o = o || 300;
for (a in t) s[a] = C.camelCase(a),
t[a].from !== n ? (t[a].to = t[a].to || 0, l[a] = O.number[a] ? t[a].to: parseInt(t[a].to, 10), c[a] = O.unit(a, t[a].to), j.set(e, s[a], parseInt(t[a].from, 10) + c[a])) : (l[a] = O.number[a] ? t[a] : parseInt(t[a], 10), c[a] = O.unit(a, t[a]), j.set(e, s[a], j.get(e, s[a]))),
u.push(a);
return setTimeout(function() {
p[i] = "all " + o + "ms",
z(u,
function(e) {
p[s[e]] = l[e] + c[e]
})
},
15),
setTimeout(function() {
p[i] = "",
r && r.call(e)
},
o),
e
})
}
} () : function(e, t, i, o) {
return U(e,
function(e) {
var r, a, l, s = 0,
c = 0,
u = 0,
p = 0,
d = 30,
h = [],
g = [],
f = [],
m = [],
v = [];
i = i || 300;
for (a in t) f.push(C.camelCase(a)),
t[a].from !== n ? (r = t[a].to, g.push(O.number[a] ? t[a].from: parseInt(t[a].from, 10)), j.set(e, f[c], g[c] + O.unit(a, r))) : (r = t[a], g.push(parseInt(j.get(e, C.camelCase(a)), 10))),
h.push(O.number[a] ? r: parseInt(r, 10)),
m.push(O.unit(a, r)),
c++,
p++;
for (u = 0; d > u; u++) for (v[u] = [], c = 0; p > c; c++) v[u][f[c]] = g[c] + (h[c] - g[c]) / d * u + ("opacity" === f[c] ? "": m[c]);
for (; d > c; c++) l = setTimeout(function() {
for (c = 0; p > c; c++) j.set(e, f[c], v[s][f[c]]);
s++
},
i / d * c);
return setTimeout(function() {
for (c = 0; p > c; c++) j.set(e, f[c], h[c] + m[c]);
o && o.call(e)
},
i),
e
})
}),
V = (S.$fadeout = function(e, t, n) {
return U(e,
function(e) {
J(e, {
opacity: {
from: 1,
to: 0
}
},
t || 500, n)
})
},
S.$fadein = function(e, t, n) {
return U(e,
function(e) {
J(e, {
opacity: {
from: 0,
to: 1
}
},
t || 500, n)
})
},
S.$cookie = {
get: function(e) {
for (var n, i, o = t.cookie.split("; "), r = 0, a = o.length; a > r; r++) if (n = o[r].split("="), n[0] === e) return i = decodeURIComponent(n[1]),
X.isJSON(i) ? X.decode(i) : i + "";
return null
},
set: function(e, n, i) {
if ("object" == typeof e) return i = n,
z(e,
function(e, t) {
V.set(t, e, i)
});
var o = new Date;
return o.setTime(o.getTime()),
i = i ? ";expires=" + new Date(o.getTime() + 864e5 * i).toGMTString() : "",
n = "object" == typeof n ? X.encode(n) : n,
t.cookie = e + "=" + K(n) + i + ";path=/"
},
remove: function() {
return z(arguments,
function(e) {
V.set(e, "", -1)
}),
!0
}
}),
X = S.$json = {
decode: e.JSON ?
function(e) {
return X.isJSON(e) ? JSON.parse(C.trim(e)) : !1
}: function(e) {
return X.isJSON(e) ? new Function("return " + C.trim(e))() : !1
},
encode: e.JSON ?
function(e) {
return JSON.stringify(e)
}: function(e) {
function t(e) {
var t, n, i, o, r = [];
for (t in e) {
if (i = e[t], n = typeof i, "undefined" === n) return;
if ("function" !== n) {
switch (n) {
case "object":
o = null === i ? i: i.getDay ? '"' + (1e3 - 10 * ~i.getUTCMonth() + i.toUTCString() + 1e3 + i / 1).replace(/1(..).*?(\d\d)\D+(\d+).(\S+).*(...)/, "$3-$1-$2T$4.$5Z") + '"': i.length ? "[" +
function() {
var e = [];
return z(i,
function(t) {
e.push("string" == typeof t ? '"' + C.slashes(t) + '"': t)
}),
e.join(",")
} () + "]": X.encode(i);
break;
case "number":
o = isFinite(i) ? i: null;
break;
case "boolean":
case "null":
o = i;
break;
case "string":
o = '"' + C.slashes(i) + '"'
}
r.push('"' + t + '":' + o)
}
}
return r.join(",")
}
return "{" + t(e) + "}"
},
isJSON: function(e) {
return "string" == typeof e && "" !== C.trim(e) ? h.test(e.replace(g, "@").replace(f, "]").replace(m, "")) : !1
}
},
K = (S.$ajax = function(t, i) {
"object" == typeof t && (i = t, t = n),
i = i || {};
var o, r = e.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest,
t = t || i.url,
a = [];
i.data && z(i.data,
function(e, t) {
a.push(A(t, e))
}),
o = a.join("&").replace(/%20/g, "+"),
"GET" === i.type ? (r.open("GET", t + (p.test(t) ? "&": "?") + o, !0), o = null) : r.open(i.type || "POST", t, !0),
r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"),
i.header && z(i.header,
function(e, t) {
r.setRequestHeader(t, e)
}),
r.send(o),
r.onreadystatechange = function() {
4 === r.readyState && (200 === r.status && i.success ? (o = r.responseText, i.success("" !== o && X.isJSON(o) ? X.decode(o) : o)) : i.error && i.error(r.status))
}
},
S.$require = function(e, n) {
var i, r = [];
z(e,
function(e) {
b[e] || (b[e] = !0, r.push(e), i = /\.css[^\.]*$/gi.test(e) ? H("link", {
type: "text/css",
rel: "stylesheet",
href: e
}) : H("script", {
type: "text/javascript",
async: !0,
src: e
}), i.onload = i.onreadystatechange = function(t) { ("load" === t.type || /loaded|complete/.test(i.readyState)) && (i.onload = i.onreadystatechange = null, r.splice(r.indexOf(e), 1), 0 === r.length && n && n())
},
P(t.head || _(t, "head")[0] || o, i))
})
},
S.$template = function(e, t) {
var n = x[e];
return n || (n = "var s='';s+='" + e.replace(/[\r\t\n]/g, " ").split("'").join("\\'").replace(/\{\{#([\w]*)\}\}(.*)\{\{\/(\1)\}\}/gi,
function(e, t, n) {
return "';var i=0,l=data." + t + ".length,d=data." + t + ";for(;i<l;i++){s+='" + n.replace(/\{\{(\.|this)\}\}/g, "'+d[i]+'").replace(/\{\{([\w]*)\}\}/g, "'+d[i].$1+'") + "'}s+='"
}).replace(/\{\{(.+?)\}\}/g, "'+data.$1+'") + "';return s;", x[e] = n),
t ? new Function("data", n)(t) : new Function("data", n)
},
S.$url = function(e) {
return encodeURIComponent(e)
}),
Y = (S.$rand = function(e, t) {
return Math.floor(Math.random() * (t - e + 1) + e)
},
S.$browser = function() {
for (var e = navigator.userAgent.toLowerCase(), t = {},
n = "msie|firefox|opera|webkit|iPad|iPhone|android".split("|"), i = n.length, o = 6; i--;) t[n[i]] = e.indexOf(n[i].toLowerCase()) > -1;
for (; 12 > o; o++) t["msie" + o] = e.indexOf("msie " + o) > -1;
return t.is = function(t) {
return new RegExp(t, "ig").test(e)
},
t
} (), S.$isArray = Array.isArray ||
function(e) {
return "[object Array]" == Object.prototype.toString.call(e)
}),
Z = S.$merge = function(e) {
for (var t = 1,
n = arguments.length; n > t; t++) {
var i = arguments[t];
if ("object" != typeof e || "object" != typeof i || Y(e) || Y(i)) e = i;
else for (var o in i) e[o] = Z(e[o], i[o])
}
return e
},
ee = S.$clone = function(e) {
var t = function(e) {
return "object" == typeof e ? ee(e) : e
};
if (Y(e)) {
for (var n = e.length,
i = new Array(n); n--;) i[n] = t(e[n]);
return i
}
var i = {};
for (var o in e) i[o] = t(e[o]);
return i
},
te = (S.$filter = function(e, t, n) {
for (var i = [], o = 0, r = e.length >>> 0; r > o; o++) o in e && t.call(n, e[o], o, e) && i.push(e[o]);
return i
},
S.$findParent = function(e, t) {
for (var n = e.parentNode; n && 11 !== n.nodeType;) {
if (t(n)) return n;
n = n.parentNode
}
return null
},
S.$parent = function(e, t) {
var n = e && e.parentNode;
return n && 11 !== n.nodeType && (!t || t(n)) ? n: null
},
S.$keys = function(e) {
var t = [];
for (var n in e) e.hasOwnProperty(n) && t.push(n);
return t
});
S.$parallel = function(e, t) {
function n(e, n) {
i[e] = n,
a++,
a == r && t(i)
}
var i = {},
o = [],
r = 0,
a = 0;
o = te(e),
r = o.length,
z(o,
function(t) {
e[t](function(e) {
n(t, e)
})
})
},
S.$parallelEach = function(e, t, n) {
function i() {
o -= 1,
0 >= o && n()
}
n = n ||
function() {};
var o = e.length;
return o ? void z(e,
function(e) {
t(e, i)
}) : n()
},
S.$getQueryParams = function(e) {
return e = e && e.split("?")[1] || t.location.search.slice(1),
e.split("&").map(function(e) {
return e = e.split("="),
this[e[0]] = e[1],
this
}.bind({}))[0]
}
}
S.version = i,
"undefined" != typeof HUABAN_GLOBAL && (HUABAN_GLOBAL.Qatrix = S),
I(function() {
t.querySelectorAll || (S.Qselector = P(t.body, H("style"))),
B || (S.storage = P(t.body, H("link", {
style: {
behavior: "url(#default#userData)"
}
})))
})
} (window, document),
function(e, t) {
var n = t.Qatrix,
i = "https://hb.pro.youzewang.com";
e.__huaban_dev && "hb.pro.youzewang.com" !== e.__huaban_dev && (i = "http://" + __huaban_dev);
var o = t.settings = {
autoInitialize: !0,
autoAttachFloatingButton: !1,
imageMinWidth: 200,
imageMinHeight: 150,
elemMinWidth: 150,
elemMinHeight: 150,
getSizeTimeout: 1e3,
orderBy: "recommend",
prefix: "HUABAN-",
id: "HUABAN_WIDGETS",
priority: {
video: 2,
og: 1,
img: 0,
bg: -1
},
huabanUrl: i,
popupUrl: i + "/index.php/Portal/Gather/index/",
multiPopupUrl: i + "/index.php/Portal/Gather/caijiAll/",
imgBase: i.replace("http:", "") + "/img/widgets",
analyticsUrl: i.replace("http:", "") + "/share_analytics.html?v=3",
waterfallLimit: 600,
md: "",
via: 2,
isMobileClient: !1,
floatingButton: {
inner: "采集",
style: "inside",
color: "red",
size: "normal",
position: "top left",
withIcon: !1
},
maximumSelect: 10,
showCallback: null,
hideCallback: null
},
r = n.$("huaban_share_script"),
a = ["style", "color", "size", "position"],
l = o.floatingButton;
if (r) {
o.autoInitialize = !1,
o.autoAttachFloatingButton = !0,
l.withIcon = !0,
n.$each(a,
function(e) {
var t = n.$data.get(r, e);
t && (l[e] = t)
});
var s = n.$data.get(r, "image-min-size");
s && (s = s.split(" "), o.imageMinWidth = Number(s[0]) || 0, o.imageMinHeight = Number(s[1]) || Number(s[0]) || 0),
o.via = 3;
var c = location && location.host && location.host.split(".") || [];
"www" === c[0] && c.shift(),
c.length && (o.md = c.join(".")),
l.suspended && (l.style = {
"in": "inside",
out: "outside"
} [l.suspended], delete l.suspended),
l.size = {
16 : "small",
66 : "normal",
108 : "large"
} [l.size] || l.size || "normal",
e.huaban_minWidth && (o.imageMinWidth = huaban_minWidth),
e.huaban_minHeight && (o.imageMinHeight = huaban_minHeight),
o.md = e.huaban_md || o.md || "",
l.inner = "收藏",
"large" === l.size && (l.inner = "收藏到花瓣");
var u = n.$new("iframe", {
src: o.analyticsUrl
});
n.$style.set(u, "display", "none"),
n.$append(document.body, u)
}
e.HUABAN_PRESETTINGS && n.$merge(o, HUABAN_PRESETTINGS)
} (window, HUABAN_GLOBAL),
function(e) {
var t = e.Qatrix,
n = {
"": 'font-family: "helvetica neue",arial,sans-serif; color: #444; font-size: 14px;',
"*": "box-sizing: content-box;",
".main": "position: fixed; left: 0; top: 0; width: 100%; height: 100%; background: #e5e5e5; background: rgba(229,229,229,.95); max-height: 100%; overflow: hidden; z-index: 9999999999999;",
"a img": "border: 0;",
".header": "height: 50px; background: white; box-shadow: 0 0 4px rgba(0,0,0,.2); width: 100%; left: 0; top: 0; position: absolute;",
".header .inner": "margin: 0 auto; position: relative;",
".header .close": "width: 60px; height: 50px; border-left: 1px solid #ddd; position: absolute; right: 0; top: 0; background: url({{imgBase}}/btn_close.png) 20px 14px no-repeat; cursor: pointer;",
".header .close:hover": "background-position: 20px -26px;",
".header .close:active": "background-position: 20px -66px;",
".header .logo": "display: block; position: absolute; top: 12px;",
".waterfall-holder": "position: relative; overflow-y: auto; height: 100%;",
".waterfall": "position: relative; margin-top: 50px;",
".waterfall .empty": "position: absolute; left: 50%; top: 30px; height: 36px; line-height: 36px; width: 216px; text-align: left; margin-left: -128px; color: #777; background: url({{imgBase}}/icon_notice.png) 12px 8px no-repeat white; padding-left: 40px; font-size: 15px;",
".btn": "display: inline-block; border-radius: 2px; font-size: 14px; padding: 0 12px; height: 30px; line-height: 30px; cursor: pointer; text-decoration: none; white-space: nowrap; -moz-user-select: none; -webkit-user-select: none; user-select: none; text-align: center; background: #D53939; color: white;",
".btn:hover": "background: #E54646;",
".btn:active": "background: #C52424;",
".wbtn": "background: #EDEDED; color: #444;",
".wbtn:hover": "background: #F2F2F2;",
".wbtn:active": "background: #DDD;",
".f-button": "position: absolute; display: none; z-index: 9999999999998; box-shadow: 0 0 0 2px rgba(255,255,255,.2); background: #aaa; background: rgba(0,0,0,.3); color: white; cursor: pointer; padding: 0 12px; height: 30px; line-height: 30px; border-radius: 2px; font-size: 14px",
".f-button:hover": "background-color: #999; background-color: rgba(0,0,0,.5);",
".f-button:active": "background-color: rgba(0,0,0,.6);",
".red-normal-icon-button": "width: 36px; height: 24px; border: 0px; line-height: 24px; padding-left: 24px; padding-right: 0px; text-align: left; background: url({{imgBase}}/widget_icons.png) 0 -200px no-repeat; box-shadow: none !important; font-size: 14px; background-color: transparent !important;",
".red-normal-icon-button:hover": "background-position: -130px -200px;",
".red-normal-icon-button:active": "background-position: -260px -200px;",
".red-large-icon-button": "width: 80px; height: 24px; border: 0px; line-height: 24px; padding-left: 24px; padding-right: 0px; text-align: left; background: url({{imgBase}}/widget_icons.png) 0 -150px no-repeat; box-shadow: none !important; font-size: 14px; background-color: transparent !important;",
".red-large-icon-button:hover": "background-position: -130px -150px;",
".red-large-icon-button:active": "background-position: -260px -150px;",
".red-small-icon-button": "width: 30px; height: 21px; border: 0px; line-height: 21px; padding-left: 20px; padding-right: 0px; text-align: left; background: url({{imgBase}}/widget_icons.png) 0 -250px no-repeat; box-shadow: none !important; font-size: 12px; background-color: transparent !important;",
".red-small-icon-button:hover": "background-position: -130px -250px;",
".red-small-icon-button:active": "background-position: -260px -250px;",
".white-normal-icon-button": "width: 36px; height: 24px; border: 0px; line-height: 24px; padding-left: 24px; padding-right: 0px; text-align: left; background: url({{imgBase}}/widget_icons.png) 0 -500px no-repeat; box-shadow: none !important; color: #444; font-size: 14px; background-color: transparent !important;",
".white-normal-icon-button:hover": "background-position: -130px -500px;",
".white-normal-icon-button:active": "background-position: -260px -500px;",
".white-large-icon-button": "width: 80px; height: 24px; border: 0px; line-height: 24px; padding-left: 24px; padding-right: 0px; text-align: left; background: url({{imgBase}}/widget_icons.png) 0 -450px no-repeat; box-shadow: none !important; color: #444; font-size: 14px; background-color: transparent !important;",
".white-large-icon-button:hover": "background-position: -130px -450px;",
".white-large-icon-button:active": "background-position: -260px -450px;",
".white-small-icon-button": "width: 30px; height: 21px; border: 0px; line-height: 21px; padding-left: 20px; padding-right: 0px; text-align: left; background: url({{imgBase}}/widget_icons.png) 0 -550px no-repeat; box-shadow: none !important; color: #444; font-size: 12px; background-color: transparent !important;",
".white-small-icon-button:hover": "background-position: -130px -550px;",
".white-small-icon-button:active": "background-position: -260px -550px;",
".cell": "width: 236px; position: absolute; background: white; box-shadow: 0 1px 3px rgba(0,0,0,.3); transition: left .3s ease-in-out, top .3s linear;",
".cell .img-holder": "overflow: hidden; position: relative;",
".cell .img-holder:hover img.cell-img": "opacity: .8",
".cell .video-icon": "width: 72px; height: 62px; position: absolute; left: 50%; top: 50%; margin: -31px auto auto -36px; background: url({{imgBase}}/media_video.png) 0 0 no-repeat; display: none;",
".cell.video .video-icon": "display: block;",
".cell .over": "display: none;",
".cell:hover .over": "display: block;",
".cell .over .btn": "width: 60px; height: 34px; padding: 0; position: absolute; left: 50%; top: 50%; margin: -18px 0 0 -31px; line-height: 34px; box-shadow: 0 0 0 2px rgba(255,255,255,.2); font-size: 16px;",
".cell.long .img-holder": "height: 600px;",
".cell.long .img-holder:after": 'content: ""; display: block; position: absolute; width: 236px; height: 12px; left: 0; bottom: 0; background: url({{imgBase}}/long_image_shadow_2.png) repeat-x 4px top;',
".cell img": "width: 236px; display: block;",
".cell .size": "margin: 8px 16px; font-size: 12px; color: #999",
".cell .description": "display: block; width: 202px; margin: 0 6px 6px; padding: 6px 10px; border: 0; resize: none; outline: 0; border: 1px solid transparent; line-height: 18px; font-size: 13px; overflow: hidden; word-wrap: break-word; background: url({{imgBase}}/icon_edit.png) 500px center no-repeat;",
".cell:hover .description": "background-color: #fff9e0; background-position: right top;",
".cell .description:focus": "background-color: #F9F9F9; background-position: 500px center;",
".cell .select-btn": "width: 34px; height:34px; background: url({{imgBase}}/checkbox.png) 0 0 no-repeat; position: absolute; right: 5px; top: 5px; cursor: pointer;",
".cell .pinned-label": "position: absolute; left: 0; top: 10px; height: 24px; line-height: 24px; padding: 0 10px; background: #CE0000; background: rgba(200, 0, 0, 0.9); color: white; font-size: 12px; display: none;",
".cell.pinned .pinned-label": "display: block;",
".selected .select-btn": "background-position: 0 -40px;",
".multi .cell .img-holder": "cursor: pointer;",
".multi .cell .cell-pin-btn": "display: none;",
".multi .cell .over": "display: block;",
".header .multi-buttons": "position: absolute; top: 10px; left: 0; display: none;",
".header .multi-buttons .btn": "margin-right: 10px;",
".header .multi-noti": "display: none; height: 50px; line-height: 50px; text-align: center; font-size: 16px; color: #999; font-weight: bold;",
".header .multi-noti span": "font-weight: normal;",
".header .multi-noti i": "font-style: normal;",
".header .notice": "padding: 0 10px; height:30px; line-height: 30px; position: absolute; left: 50%; top: 10px; margin-left: -83px; background: #fff9e2; text-align: center;",
".header .notice i": "display: inline-block; width: 18px; height: 18px; background: url({{imgBase}}/icon_notice.png) 0 0 no-repeat; vertical-align: top; margin: 6px 6px 0 0;",
".switcher": "height: 50px; width: 100px; position: relative;",
".switcher .title": "position: absolute; right: 75px; top: 13px; color: #999; white-space: nowrap; line-height: 24px; opacity: 0; visibility: hidden;",
".switcher:hover .title": "visibility: visible; opacity: 1; -webkit-transition: opacity .2s linear; -webkit-transition-delay: .2s; transition: opacity .2s linear; transition-delay: .2s;",
".switcher .bar": "width: 40px; height: 24px; background: #EB595F; border-radius: 12px; color: white; position: absolute; right: 0; top: 13px; cursor: pointer; font-size: 14px; -webkit-transition: all .2s linear; transition: all .2s linear;",
".switcher:hover .bar": "width: 64px;",
".switcher.on .bar": "background: #7DD100;",
".switcher .bar .round": "width: 20px; height: 20px; background: white; border-radius: 50%; position: absolute; left: 2px; top: 2px; -webkit-transition: left .2s linear; box-shadow: 0px 0px 3px rgba(0,0,0,0.15); transition: left .2s linear; box-shadow: 0px 0px 3px rgba(0,0,0,0.15);",
".switcher.on .bar .round": "left: 17px;",
".switcher.on:hover .bar .round": "left: 41px;",
".switcher .bar .text-1": "height: 24px; line-height: 24px; position: absolute; right:17px; top: 0; opacity: 0; visibility: hidden; -webkit-transition: all .2s linear; transition: all .2s linear;",
".switcher:hover .bar .text-1": "right: 9px; opacity: 1; visibility: visible;",
".switcher.on:hover .bar .text-1": "right: 17px; opacity: 0; visibility: hidden;",
".switcher .bar .text-2": "height: 24px; line-height: 24px; position: absolute; left:17px; top: 0; opacity: 0; visibility: hidden; -webkit-transition: all .2s linear; transition: all .2s linear;",
".switcher:hover .bar .text-2": "left: 17px; opacity: 0; visibility: hidden;",
".switcher.on:hover .bar .text-2": "left: 9px; opacity: 1; visibility: visible;",
".header .switcher": "position: absolute; right: 0; top: 0;"
},
i = {
".red-normal-icon-button, .red-large-icon-button, .red-small-icon-button, .white-normal-icon-button, .white-large-icon-button, .white-small-icon-button": "{ background-image: url({{imgBase}}/widget_icons_ie6.png)"
};
e.styles = "";
var o = e.settings.imgBase; (t.$browser.msie6 || t.$browser.msie7 || t.$browser.msie8) && (o = window.location.protocol + o),
t.$each(t.$keys(n),
function(i) {
n[i] = t.$string.replace(n[i], {
"{{imgBase}}": o
}),
e.styles += "#" + e.settings.id + " " + i.replace(/\./g, "." + e.settings.prefix) + " {" + n[i] + "} "
}),
e.styles += "<!--[if IE 6]>",
t.$each(t.$keys(i),
function(t) {
e.styles += "#" + e.settings.id + " " + t.replace(/\./g, "." + e.settings.prefix) + " " + i[t] + " "
}),
e.styles += "<![endif]-->"
} (HUABAN_GLOBAL),
function(e) {
{
var t = e.Qatrix;
e.settings.huabanUrl
}
e.templates = {
main: ['<div class="main">', '<div class="waterfall-holder">', '<div class="waterfall">', "</div>", "</div>", '<div class="header">', '<div class="inner sync">', '<a class="logo" href="{{huabanUrl}}" target="_blank">', '<img src="{{imgBase}}/logo.png?v=1">', "</a>", '<div class="multi-noti">已选择 <b>1</b> 张<span>(最多 <i>10</i> 张)</span></div>', '<div class="multi-buttons">', '<div class="btn confirm">批量采集</div>', '<div class="btn wbtn cancel">取消</div>', "</div>", '<div class="notice" style="display: none"><i></i><span></span></div>', '<div class="switcher switch-order">', '<div class="title">图片排序</div>', '<div class="bar">', '<div class="text-1">推荐</div>', '<div class="text-2">自然</div>', '<div class="round"></div>', "</div>", "</div>", "</div>", '<div class="close", title="或按 ESC 键关闭">', "</div>", "</div>", "</div>"].join(""),
"message-box": '<div id="HUABAN_MESSAGE" style="display: none"></div>',
"waterfall-cell": ['<div class="cell">', '<div class="img-holder">', '<img src="{{imgUrl}}" class="cell-img" height="{{imgHeight}}"/>', '<div class="pinned-label">已采集</div>', '<div class="video-icon"></div>', '<div class="over">', '<div class="btn cell-pin-btn">采集</div>', '<div class="select-btn"></div>', "</div>", "</div>", '<div class="size">{{size.x}} x {{size.y}}</div>', '<textarea class="description">{{description}}</textarea>', "</div>"].join(""),
"empty-alert": ['<div class="empty">没有找到足够大的图片/视频</div>'].join(""),
"floating-button": ['<div class="f-button {{extraClass}}">', "{{inner}}", "</div>"].join("")
},
t.$each(t.$keys(e.templates),
function(n) {
e.templates[n] = t.$string.replace(e.templates[n], {
"{{imgBase}}": e.settings.imgBase,
"{{huabanUrl}}": e.settings.huabanUrl
})
}),
e.render = function(n, i) {
i = i || {};
var o = t.$template(e.templates[n], i),
r = t.$new("div", {
html: o
}),
a = r.childNodes[0];
return t.$tag(r, "*",
function(n) {
n.className && (n.className = (e.settings.prefix + t.$string.trim(n.className)).replace(/\ /g, " " + e.settings.prefix))
}),
r.removeChild(a),
a
}
} (HUABAN_GLOBAL),
function(e) {
var t = e.Qatrix,
n = function(e) {
return e.length ? (t.$each(e,
function(e) {
e.url = window.location.href
}), e) : void 0
};
e.rules = {
"^https?://image\\.baidu\\.com\\/channel": function(e) {
return e.length ? (t.$each(e,
function(e) {
var n, i;
n = t.$findParent(e.elem,
function(e) {
return t.$className.has(e, "inner_wrapper")
}),
n && (i = t.$class(n, "abs")[0], e.url = t.$attr.get(i, "href"), e.description = t.$text(i))
}), e) : void 0
},
"^https?://image\\.baidu\\.com\\/i\\?": function(e) {
if (e.length) {
var n = t.$id("picInfoPnl")[0];
return n ? t.$each(e,
function(e) {
var i = t.$parent(e.elem,
function(e) {
return t.$className.has(e, "img-container")
});
i && (e.description = t.$class(n, "pictitle")[0].innerText)
}) : t.$each(e,
function(e) {
var n, i = t.$findParent(e.elem,
function(e) {
return t.$className.has(e, "pullImgli")
});
if (i) try {
n = t.$class(i, "imgShow")[0],
e.url = t.$tag(n, "a")[0].href,
e.description = t.$class(i, "fromURL")[0].innerText
} catch(o) {}
}),
e
}
},
"^https?://(.*\\.)?weibo\\.com": function(e) {
if (e.length) {
var n = [];
return t.$each(e,
function(e) {
if (!e.imgUrl.match(/img.t.sinajs.cn/)) {
var i = t.$findParent(e.elem,
function(e) {
return t.$className.has(e, "feed_list_new") || t.$className.has(e, "WB_feed_expand") || t.$className.has(e, "WB_media_expand") || t.$className.has(e, "WB_feed_detail")
});
if (i) {
var o = t.$class(i, "WB_from")[0];
o || (o = t.$class(i, "feed_from")[0]),
o && (e.url = t.$tag(o, "a")[0].href);
var r = t.$class(i, "WB_text")[0];
r || (r = t.$class(i, "comment_txt")[0]),
r || (i = t.$findParent(e.elem,
function(e) {
return t.$className.has(e, "WB_feed_datail")
}), r = t.$class(i, "WB_text")[0]),
r && (e.description = r.innerText)
}
n.push(e)
}
}),
n
}
},
"^https?://(.*\\.)?zcool\\.com\\.cn\\/gfx\\/.+": n,
"^http://(.*\\.)?kmeitu\\.com": n,
"^http://(.*\\.)?bcy\\.net": n,
"^https?://(.*\\.)?zcool\\.com\\.cn": function(e) {
if (e.length) {
var n = t.$select(".camWholeBox")[0];
if (n) t.$each(e,
function(e) {
var n = t.$parent(e.elem);
n && (e.url = t.$attr.get(n, "href"))
});
else try {
var i = t.$select(".workTitle")[0].innerText;
t.$each(e,
function(e) {
e.description = i
})
} catch(o) {}
return e
}
},
"^https?://(www\\.)?500px\\.com": function(e) {
return e.length ? (t.$each(e,
function(e) {
var n = t.$data.get(e.elem, "bind");
if (n && "photo_img" === n) {
var i = t.$parent(e.elem);
i && (e.url = t.$attr.get(i, "href"));
try {
var o = t.$parent(i),
r = t.$string.trim(t.$class(o, "title")[0].innerText) || "",
a = t.$string.trim(t.$class(o, "info")[0].innerText) || ""; (r || a) && (e.description = r + " - " + a)
} catch(l) {}
}
}), e) : void 0
},
"^https?://(www\\.)?pinterest\\.com": function(e) {
return e.length ? (t.$each(e,
function(e) {
var n = t.$findParent(e.elem,
function(e) {
return t.$className.has(e, "pinImageWrapper")
});
n && (e.url = "http://www.pinterest.com/" + t.$attr.get(n, "href"))
}), e) : void 0
},
"^https?://(www\\.)?behance\\.net": function(e) {
return e.length ? (t.$each(e,
function(e) {
var n = t.$parent(t.$parent(e.elem));
n && (e.url = t.$attr.get(n, "href"))
}), e) : void 0
},
"^https?://movie\\.douban\\.com": function(e) {
try {
var n = t.$select("#mainpic .nbgnbg img")[0],
i = n.src.replace("movie_poster_cover/spst", "photo/photo"),
o = n.alt + " (来自豆瓣电影)";
e.push({
size: {
x: 428,
y: 600
},
imgUrl: i,
description: o
})
} catch(r) {}
return e
},
"^https?://ypy\\.douban\\.com/": n,
"^https?://(www\\.)?jianjuke\\.com": function(e) {
return e.length ? (t.$each(e,
function(e) {
var n = t.$findParent(e.elem,
function(e) {
return t.$className.has(e, "post")
});
if (n) try {
var i = t.$class(n, "entry-title")[0],
o = t.$tag(i, "a")[0];
e.url = t.$attr.get(o, "href"),
e.description = t.$text(o)
} catch(r) {}
}), e) : void 0
},
"^https?://(www\\.)?duitang\\.com": function(e) {
return e.length ? (t.$each(e,
function(e) {
if (window.location.href.match(/.*duitang\.com\/people\/mblog\/\d+\/detail/) && e.url && e.url.match(/http:\/\/www\.duitang\.com\/redirect\//)) {
var n = t.$getQueryParams(e.url).to;
n && (e.url = decodeURIComponent(n))
} else try {
var i = t.$parent(t.$parent(e.elem)),
o = t.$tag(t.$class(i, "dt-woo-title")[0], "a")[0];
e.description = t.$text(o)
} catch(r) {}
}), e) : void 0
},
"^http://www\\.58pic\\.com/": function(e) {
return e.length ? (t.$each(e,
function(e) {
var n = t.$parent(e.elem);
t.$className.has(n, "thumb-box") && (e.url = n.href)
}), e) : void 0
},
"^http://(www\\.)?tobosu\\.com/pic": function(e) {
return e.length ? (t.$each(e,
function(e) {
e.imgUrl = e.imgUrl.replace("/small/", "//")
}), e) : void 0
},
"^https?://(www\\.)?houzz\\.com/photos(/[^0-9]+)*": function(e) {
return e.length ? (t.$class(document.body, "browseListBody") && t.$each(e,
function(e) {
var n = t.$parent(t.$parent(e.elem));
t.$className.has(n, "noHoverLink") && (e.url = t.$attr.get(n, "href"))
}), e) : void 0
},
"^https?://(.*\\.)?lofter\\.com": function(e) {
return e.length ? (t.$each(e,
function(e) {
var n = t.$parent(e.elem),
i = t.$parent(n);
n && n.tagName && "a" === n.tagName.toLowerCase() && n.href ? e.url = t.$attr.get(n, "href") : i && i.tagName && "a" === i.tagName.toLowerCase() && i.href && (e.url = t.$attr.get(i, "href"))
}), e) : void 0
},
"^https?://zhan\\.renren\\.com": function(e) {
return e.length ? (t.$each(e,
function(e) {
e.url && "javascript:;" !== e.url || (e.url = window.location.href)
}), e) : void 0
},
"^http://(\\w+\\.)?rayli\\.com\\.cn/": function(e) {
return e.length ? (t.$each(e,
function(e) {
e.imgUrl = e.imgUrl.replace("/thumb_(d+_)+/", "/")
}), e) : void 0
},
"^http://fanjian8\\.com": function(e) {
return e.length ? (t.$each(e,
function(e) {
var n = t.$parent(e.elem);
t.$className.has(n, "single-content") && (e.url = "http://" + window.location.host + t.$attr.get(n, "rel") || "")
}), e) : void 0
},
"^http://pic\\.gamespot\\.com\\.cn": function(e) {
return e.length ? (t.$each(e,
function(e) {
e.imgUrl = e.imgUrl.replace(/_\d+\./, ".")
}), e) : void 0
},
"^https?://(www\\.)diandian\\.com": function(e) {
return e.length ? (t.$each(e,
function(e) {
var n = t.$findParent(e.elem,
function(e) {
return t.$className.has(e, "feed-content-holder")
});
if (n) try {
var i = t.$class(n, "link-to-post")[0];
e.url = t.$attr.get(i, "href")
} catch(o) {}
}), e) : void 0
},
"^https?://tuchong\\.com": function(e) {
return e.length ? (t.$each(e,
function(e) {
e.imgUrl = e.imgUrl.replace(/\/(\d+)\/g\/(\d+)/, "/$1/f/$2")
}), e) : void 0
},
"^http://(www\\.)zhuqu\\.com/": function(e) {
return e.length ? (t.$each(e,
function(e) {
var n = t.$parent(e.elem),
i = t.$class(n, "zq_mask")[0];
i && (e.url = t.$attr.get(i, "href")),
e.imgUrl = e.imgUrl.replace(/\/thb2\/\d+x\d+\//, "/water/")
}), e) : void 0
},
"^http://(\\w+\\.)cnsc8\\.com/": function(e) {
return e.length ? (t.$each(e,
function(e) {
e.imgUrl = e.imgUrl.replace(/\/Small_Pic\//, "/Big_Pic/")
}), e) : void 0
},
"^http://(www\\.)35pic\\.com/": function(e) {
return e.length ? (t.$each(e,
function(e) {
e.imgUrl = e.imgUrl.replace(/img\./, "pic.").replace(/_\d+\./, ".")
}), e) : void 0
},
"^https?://(w+\\.)mogujie\\.com/": function(e) {
return e.length ? (t.$each(e,
function(e) {
e.imgUrl = e.imgUrl.replace(/(_\d+x\d+\.(jpg|jpeg|png))(?:_\d+x\d+\.(jpg|jpeg|png))*/, "$1")
}), e) : void 0
},
"^https?://(www\\.)youku\\.com/": function(e) {
return e.length ? (t.$each(e,
function(e) {
try {
var n = t.$parent(t.$parent(e.elem)),
i = t.$tag(t.$class(n, "v-link")[0], "a")[0];
e.url = t.$attr.get(i, "href")
} catch(o) {}
}), e) : void 0
},
"^https?://(www\\.)uehtml\\.com/": function(e) {
return e.length ? (t.$each(e,
function(e) {
try {
var n = t.$parent(t.$parent(e.elem));
e.description = t.$text(t.$class(n, "citemtitle"))
} catch(i) {}
}), e) : void 0
},
"^http://(\\w+\\.)aili\\.com/": function(e) {
return e.length ? (t.$each(e,
function(e) {
e.imgUrl = e.imgUrl.replace(/_\d+\.(jpg|jpeg|png)$/, ".$1")
}), e) : void 0
},
"^http://pic\\.gamersky\\.com/": function(e) {
return e.length ? (t.$each(e,
function(e) {
e.description = document.title
}), e) : void 0
},
"^http://(www\\.)kujiale\\.com/": function(e) {
return e.length ? (t.$each(e,
function(e) {
e.imgUrl = e.imgUrl.replace(/@!?\d+x\d+$/, "")
}), e) : void 0
},
"^http://tupian\\.zol\\.com\\.cn/": function(e) {
return e.length ? (t.$each(e,
function(e) {
try {
var n = t.$parent(t.$parent(e.elem));
e.description = t.$text(t.$class(n, "pic-infor"))
} catch(i) {}
}), e) : void 0
},
"^http://drawcrowd\\.com/": function(e) {
return e.length ? (t.$each(e,
function(e) {
try {
var n = t.$class(t.$parent(e.elem), "project-page")[0];
e.url = "http://" + window.location.host + t.$attr.get(n, "href")
} catch(i) {}
}), e) : void 0
},
"^http://(www\\.)gtn9\\.com/": function(e) {
return e.length ? (t.$each(e,
function(e) {
try {
var n = t.$parent(t.$parent(t.$parent(e.elem))),
i = t.$class(n, "comment_box")[0];
e.description = t.$text(t.$tag(i, "li")[1])
} catch(o) {}
}), e) : void 0
},
"^http://topys\\.cn/": function(e) {
return e.length ? (t.$each(e,
function(e) {
try {
var n = t.$parent(t.$parent(t.$parent(e.elem)));
e.description = t.$text(t.$class(n, "cont-text"))
} catch(i) {}
}), e) : void 0
},
"^http://dp\\.pconline\\.com\\.cn/": function(e) {
return e.length ? (t.$each(e,
function(e) {
try {
var n = t.$parent(t.$parent(t.$parent(e.elem)));
e.description = t.$class(n, "cont-text")[0].innerText
} catch(i) {}
}), e) : void 0
},
"^http://(www\\.)gameui\\.cn/": function(e) {
return e.length ? (t.$each(e,
function(e) {
var n = t.$parent(e.elem);
e.description = t.$attr.get(n, "title")
}), e) : void 0
}
},
e.videoSiteRules = {
"^https?://v.youku.com": function() {
if (window.videoId2) {
var n = t.$id("movie_player")[0];
if (n) {
var i = t.$new("param", {
name: "wmode",
value: "transparent"
});
t.$prepend(n, i),
e.settings.hideCallback = function() {
t.$remove(i)
}
}
var o = "http://player.youku.com/player.php/sid/" + videoId2 + "/v.swf";
return {
imgUrl: e.settings.huabanUrl + "/pins/create/video/swf?url=" + encodeURIComponent(o),
size: {
x: 448,
y: 252
},
video: o,
elem: null,
elemSize: null,
type: "video"
}
}
},
"^https?://www.tudou.com": function() {
if (window.itemData) {
var e = "";
try {
t.$select("#shareWrap .iconfont")[0].click(),
e = t.$("flashInput").value,
t.$select("#shareWrap .iconfont")[0].click()
} catch(n) {}
if (e) return {
imgUrl: itemData.pic,
size: {
x: 320,
y: 240
},
video: e,
elem: null,
elemSize: null,
description: itemData.kw || "",
type: "video"
}
}
},
"^https?://www.bilibili.tv": function() {
var e = t.$select("meta"),
n = "",
i = "";
return t.$each(e,
function(e) {
"thumbnailUrl" == t.$attr.get(e, "itemprop") ? n = t.$attr.get(e, "content") : "embedURL" == t.$attr.get(e, "itemprop") && (i = t.$attr.get(e, "content"))
}),
{
imgUrl: n,
size: {
x: 120,
y: 90
},
video: i,
elem: null,
elemSize: null,
type: "video"
}
},
"^https?://www.acfun.com/v/": function() {
if (window.system) {
var e = system.preview,
t = "http://static.acfun.com/player/ACFlashPlayer.out.swf?type=page&url=" + system.url;
if (t && e) return {
imgUrl: e,
size: {
x: 120,
y: 90
},
video: t,
elem: null,
elemSize: null,
type: "video"
}
}
},
"^https?://v.yinyuetai.com": function() {
var t = e.collector.og;
if (t) {
var n = t.image,
i = t.videosrc;
if (i && n) return {
imgUrl: n,
size: {
x: 640,
y: 360
},
video: i,
elem: null,
elemSize: null,
type: "video"
}
}
},
"^https?://(www|yule).iqiyi.com": function() {
var n = "",
i = "",
o = "";
try {
t.$select('a[data-widget="pshareicon"]')[0].click(),
t.$select(".show-more")[0].click(),
n = t.$select('input[data-sharecopy-ele="flashurl"]')[0].value;
var r = /player\.video\.qiyi\.com\/([\w\d]+)\//,
a = /\-tvId\=(\d+)\-/;
i = r.exec(n)[1],
o = a.exec(n)[1],
t.$select('a[data-widget="pshareicon"]')[0].click()
} catch(l) {
return
}
return {
imgUrl: e.settings.huabanUrl + "/pins/create/video/qiyi/?id=" + i + "&tvid=" + o,
size: {
x: 115,
y: 77
},
video: n,
elem: null,
elemSize: null,
type: "video"
}
},
"^https?://www.56.com/u": function() {
var t = /v_(.+?)\.html/,
n = t.exec(location.href);
return n = n[1],
{
imgUrl: e.settings.huabanUrl + "/pins/create/video/56/?id=" + n,
size: {
x: 480,
y: 405
},
video: "http://player.56.com/v_" + n + ".swf",
elem: null,
elemSize: null,
type: "video"
}
},
"^https?://v.ku6.com": function() {
var e = "",
t = "";
try {
e = App.VideoInfo.data.data.bigpicpath,
t = App.VideoInfo.id
} catch(n) {}
if (e && t) return {
imgUrl: e,
size: {
x: 480,
y: 405
},
video: "http://player.ku6.com/refer/" + t + "/v.swf",
elem: null,
elemSize: null,
type: "video"
}
},
"^https?://v.pptv.com/show": function() {
return {
imgUrl: e.settings.huabanUrl + "/pins/create/video/pptv/?id=" + webcfg.id,
size: {
x: 120,
y: 60
},
video: webcfg.player.playList[0].swf,
elem: null,
elemSize: null,
type: "video"
}
},
"^https?://v.qq.com/": function() {
var e = "",
n = "";
try {
var i = /vid=(.+)&/;
e = t.$("textfield2").value,
n = i.exec(e)[1]
} catch(o) {}
if (n && e) return {
imgUrl: "http://vpic.video.qq.com/76082551/" + n + "_160_90_3.jpg",
size: {
x: 160,
y: 90
},
video: e,
elem: null,
elemSize: null,
type: "video"
}
}
},
e.embedVideoRules = {
"(player.youku.com/player|www.tudou.com|player.ku6.com/refer|player.56.com|player.pptv.com/v)": function(t) {
return {
imgUrl: e.settings.huabanUrl + "/pins/create/video/swf?url=" + encodeURIComponent(t.url),
size: {
x: 448,
y: 336
},
video: t.url,
elem: t.elem,
elemSize: e.collector.getElemSize(t.elem),
type: "video"
}
},
"share.vrs.sohu.com/my/v.swf.+?&id=(.+?)&autoplay=": function(t) {
var n = /share.vrs.sohu.com\/my\/v.swf.+?&id=(.+?)&autoplay=/.exec(t.url)[1];
return {
imgUrl: e.settings.huabanUrl + "/pins/create/video/mysohu/?id=" + n,
size: {
x: 480,
y: 360
},
video: t.url,
elem: t.elem,
elemSize: e.collector.getElemSize(t.elem),
type: "video"
}
},
"share.vrs.sohu.com/(.+?)/v.swf": function(t) {
var n = /share\.vrs\.sohu\.com\/(.+?)\/v\.swf/.exec(t.url)[1];
return {
imgUrl: e.settings.huabanUrl + "/pins/create/video/sohu/?id=" + n,
size: {
x: 480,
y: 360
},
video: t.url,
elem: t.elem,
elemSize: e.collector.getElemSize(t.elem),
type: "video"
}
},
"v.ifeng.com/include/exterior.swf": function(t) {
var n = /guid=(.+?)&/,
i = n.exec(t.url);
return i ? (i = i[1], {
imgUrl: e.settings.huabanUrl + "/pins/create/video/ifeng/?id=" + i,
size: {
x: 480,
y: 360
},
video: t.url,
elem: t.elem,
elemSize: e.collector.getElemSize(t.elem),
type: "video"
}) : !1
},
"swf.ws.126.net/movieplayer": function(t) {
var n = /-(vimg.+)-.swf?/,
i = n.exec(t.url);
return i ? (i = i[1].replace(/_/g, "."), {
imgUrl: "http://" + i + ".jpg",
size: {
x: 480,
y: 360
},
video: t.url,
elem: t.elem,
elemSize: e.collector.getElemSize(t.elem),
type: "video"
}) : !1
},
"swf.ws.126.net/v": function(t) {
var n = /coverpic=\"(.+?)&/,
i = n.exec(t.url);
return i ? (i = i[1], {
imgUrl: i,
size: {
x: 480,
y: 360
},
video: t.url,
elem: t.elem,
elemSize: e.collector.getElemSize(t.elem),
type: "video"
}) : !1
},
"player.yinyuetai.com": function(t) {
var n = /video\/swf\/(.+?)\//,
i = n.exec(t.url);
if (!i) return ! 1;
i = i[1];
var o = t.url.indexOf("video") > 0 ? e.settings.huabanUrl + "/pins/create/video/yinyuetai/?id=" + i: e.settings.huabanUrl + "/pins/create/video/yytList/?id=" + i;
return {
imgUrl: o,
size: {
x: 480,
y: 360
},
video: t.url,
elem: t.elem,
elemSize: e.collector.getElemSize(t.elem),
type: "video"
}
},
"player.video.qiyi.com": function(t) {
var n = /com\/(.+?)\//,
i = n.exec(t.url);
return i ? (i = i[1], {
imgUrl: e.settings.huabanUrl + "/pins/create/video/qiyi/?id=" + i,
size: {
x: 115,
y: 77
},
video: t.url,
elem: t.elem,
elemSize: e.collector.getElemSize(t.elem),
type: "video"
}) : !1
},
"www.jifenzhong.com/external": function(t) {
var n = /v1.0\/(.+?)\/player/,
i = n.exec(t.url);
return i ? (i = i[1], {
imgUrl: e.settings.huabanUrl + "/pins/create/video/jfz/?id=" + i,
size: {
x: 480,
y: 305
},
video: t.url,
elem: t.elem,
elemSize: e.collector.getElemSize(t.elem),
type: "video"
}) : !1
},
"static.video.qq.com": function(t) {
var n = /vid=(.+)(&|$)/,
i = n.exec(t.url);
return i ? {
imgUrl: "http://vpic.video.qq.com/76082551/" + i[1] + "_160_90_3.jpg",
size: {
x: 160,
y: 90
},
video: t.url,
elem: t.elem,
elemSize: e.collector.getElemSize(t.elem),
type: "video"
}: !1
}
}
} (HUABAN_GLOBAL),
function(e, t) {
{
var n = e.Qatrix;
e.collector = {
getImgUnits: function(e) {
var i = [],
o = t.images || [],
r = this;
return o.length ? (n.$each(o,
function(e) {
var t = r.buildImgUnit(e);
t && i.push(t)
}), void e(i)) : e([])
},
buildImgUnit: function(t) {
if (n.$findParent(t,
function(t) {
return t.id == e.settings.id
})) return null;
if (!t.src && !t.srcset) return null;
var i = this.getImgNaturalSize(t);
if (!i) return null;
var o, r = "figure" == n.$parent(t).tagName.toLowerCase() ? n.$parent(t) : null,
a = r && n.$tag(r, "figcaption").length ? n.$tag(r, "figcaption")[0].innerHTML: null,
l = n.$parent(t),
s = n.$attr.get(t, "alt") || a || n.$attr.get(t, "title") || "";
return "a" === l.tagName.toLowerCase() && l.href && (s = s || n.$attr.get(l, "title") || "", l.href.match(/(^(#|javascript:))|((\.jpg|\.jpeg|\.png|\.gif)$)/) || (o = l.href)),
{
elem: t,
url: o,
imgUrl: t.src || t.srcset.split(/[,|\s]/)[2],
size: i,
elemSize: this.getElemSize(t),
description: s,
type: "img",
nopin: "nopin" === (n.$attr.get(t, "huaban") || "").trim()
}
},
getBgUnits: function(i) {
var o = [],
r = t.getElementsByTagName("*"),
a = (r.length, this);
n.$parallelEach(r,
function(t, i) {
var r = n.$style.get(t, "background-image"),
l = a.getElemSize(t);
return ! r || "none" == r || !~r.indexOf("http") || l.x < e.settings.elemMinWidth || l.y < e.settings.elemMinHeight ? i() : (r = a.getAbsoluteUrl(r.replace(/^url\(["']?/, "").replace(/["']?\)$/, "")), void a.getImgSize(r,
function(e) {
o.push({
elem: t,
imgUrl: r,
size: e,
elemSize: l,
description: n.$attr.get(t, "title") || "",
type: "bg",
nopin: "nopin" === (n.$attr.get(t, "huaban") || "").trim()
}),
i()
}))
},
function() {
i(o)
})
},
getOpenGraph: function() {
for (var e = {},
i = n.$tag(t, "meta"), o = 0; o < i.length; o++) {
var r = n.$attr.get(i[o], "property");
r && ~r.toLowerCase().indexOf("og:") && (e[n.$string.trim(r.toLowerCase().replace("og:", ""))] = n.$attr.get(i[o], "content"))
}
return e
},
getVideos: function(o) {
var r = t.getElementsByTagName("object"),
a = t.embeds,
l = this,
s = [],
c = function(t, n) {
var o = {
url: t,
elem: n
};
for (i in e.embedVideoRules) {
var r = new RegExp(i);
if (r.test(o.url)) {
var a = e.embedVideoRules[i](o);
a && s.push(a);
break
}
}
};
a.length && n.$each(a,
function(e) {
c(e.src, e)
}),
r.length && n.$each(r,
function(e) {
var t = n.$attr.get(e, "data");
t || n.$tag(e, "param",
function(e) {
var i = n.$attr.get(e, "name"); ("movie" == i || "src" == i) && (t = n.$attr.get(e, "value"))
}),
t && c(t, e)
});
for (i in e.videoSiteRules) {
var u = new RegExp(i);
if (u.test(location.href)) {
var p = e.videoSiteRules[i]();
p && s.push(p);
break
}
}
n.$parallelEach(s,
function(e, t) {
l.getImgSize(e.imgUrl,
function(n) {
n && (e.size = n),
t()
})
},
function() {
o(s)
})
},
getElemSize: function(e) {
return {
x: e.offsetWidth,
y: e.offsetHeight
}
},
getImgSize: function(t, n) {
function i() {
return a.complete || a.width ? {
x: a.width,
y: a.height
}: null
}
function o() {
if (new Date - r >= e.settings.getSizeTimeout) return n(null);
var t = i();
t ? n(t) : setTimeout(o, 100)
}
var r = new Date,
a = new Image;
a.src = t,
setTimeout(o, 0)
},
getImgNaturalSize: function(e) {
var t = {};
if (e.naturalWidth) t = {
x: e.naturalWidth,
y: e.naturalHeight
};
else {
var n = new Image;
n.src = e.src,
t = {
x: n.width,
y: n.height
}
}
if (0 == t.x && 0 == t.y) {
if (0 == e.width && 0 == e.height) return null;
t = {
x: e.width,
y: e.height
}
}
return t
},
getAbsoluteUrl: function(e) {
var n = t.createElement("A");
return n.href = e,
e = n.href
},
buildUnits: function(t) {
var i = this;
n.$parallel({
imgs: function(e) {
i.getImgUnits(e)
},
bgs: function(e) {
i.getBgUnits(e)
},
og: function(e) {
var t = i.og = i.getOpenGraph();
t.image && t.videosrc && t["video:type"] && ~t["video:type"].indexOf("flash") ? i.getImgSize(t.image,
function(n) {
e({
imgUrl: t.image,
size: n || {
x: 640,
y: 360
},
video: t.videosrc,
elem: null,
elemSize: null,
type: "video",
nopin: "nopin" === (t.huaban || "").trim()
})
}) : t.image ? i.getImgSize(t.image,
function(n) {
e({
elem: null,
imgUrl: t.image,
size: n,
elemSize: n,
description: "",
type: "og",
nopin: "nopin" === (t.huaban || "").trim()
})
}) : e()
},
videos: function(e) {
i.getVideos(e)
}
},
function(n) {
var o = n.imgs.concat(n.bgs);
n.og && o.push(n.og),
o = o.concat(n.videos),
o = i.filter(o),
o = i.handleUnitsByRule(o),
o = i.sorting(o, e.settings.orderBy),
o = i.fillDescriptions(o),
i.units = o,
t(o)
})
},
fillDescriptions: function(n) {
var i = t.title,
o = e.ui && e.ui.getSelectedText();
this.og || (this.og = this.getOpenGraph()),
this.og.title && (i = this.og.title),
this.og.description && (i ? i += " : " + this.og.description: i = this.og.description);
for (var r = n.length - 1; r >= 0; r--) n[r].description = o || n[r].description || i;
return n
},
handleUnitsByRule: function(t) {
if (!e.rules) return t;
for (i in e.rules) {
var n = new RegExp(i);
if (n.test(window.location.href)) {
t = e.rules[i](t) || t;
break
}
}
return t
},
filter: function(t) {
for (var i = [], o = function(t) {
var o = !0,
r = [t.size && t.size.x >= e.settings.imageMinWidth, t.size && t.size.y >= e.settings.imageMinHeight, !t.nopin,
function() {
var e = !0;
return n.$each(i,
function(n) {
t.imgUrl == n.imgUrl && (e = !1)
}),
e
} ()];
return "video" == t.type && (r[0] = !0, r[1] = !0),
n.$each(r,
function(e) {
e || (o = !1)
}),
o
},
r = 0; r < t.length; r++) o(t[r]) && i.push(t[r]);
return i
},
sorting: function(t, n) {
for (var i = 0; i < t.length; i++) t[i].documentOrder = i;
var o = e.settings.priority;
t.sort(function(e, t) {
var n = o[t.type] - o[e.type];
return n ? n: t.size.x * t.size.y - e.size.x * e.size.y
});
for (var i = 0; i < t.length; i++) t[i].recommendOrder = i;
return "document" == n && t.sort(function(e, t) {
return e.documentOrder - t.documentOrder
}),
t
},
attachFloatingButton: function() {
if (!this.floatingButton) {
var i = this,
o = e.settings.floatingButton,
r = [o.color, o.size, "icon-button"].join("-"),
a = this.floatingButton = e.render("floating-button", {
inner: o.inner,
extraClass: o.withIcon ? r: ""
});
e.ui.mainEl || e.ui.buildElements(),
n.$prepend(e.ui.holderEl, a),
n.$show(a);
var l = this.getElemSize(a);
n.$hide(a),
this.mouseMoveEvent = function(t) {
var o = t.target || t.srcElement;
if (!n.$className.has(o, "HUABAN-f-button")) if ("img" == o.tagName.toLowerCase()) {
var r = i.getImgNaturalSize(o),
s = i.getElemSize(o);
if (r.x < e.settings.imageMinWidth || r.y < e.settings.imageMinHeight || s.x < e.settings.elemMinWidth || s.y < e.settings.elemMinHeight) return n.$hide(a);
var c = i.getElPosition(o);
n.$css.set(a, i.calButtonPos(c, l)),
n.$show(a),
a.imgElem = o
} else {
if (n.$className.has(o, "bdimgshare-bg")) return;
n.$hide(a)
}
},
window.addEventListener ? t.body.addEventListener("mousemove", this.mouseMoveEvent) : t.body.attachEvent("onmousemove", this.mouseMoveEvent),
n.$event.on(a, "click",
function() {
if (!e.ui.checkPermission()) {
var t = i.buildImgUnit(this.imgElem);
return t ? (t = i.handleUnitsByRule([t])[0], t = i.fillDescriptions([t])[0], t.nopin ? alert("该网站禁止花瓣采集该图片,您可以联系网站管理员了解更多。谢谢您的理解") : void e.popup.single(t)) : alert("对不起,未找到合适图片")
}
})
}
},
calButtonPos: function(t, n) {
var i = 0,
o = 0,
r = e.settings.floatingButton;
return "outside" == r.style ? (i = ~r.position.indexOf("bottom") ? t.bottom: t.top - n.y, o = ~r.position.indexOf("right") ? t.right - n.x: t.left) : (i = ~r.position.indexOf("bottom") ? t.bottom - n.y - 5 : t.top + 5, o = ~r.position.indexOf("right") ? t.right - n.x - 5 : t.left + 5),
{
left: o > 0 ? o + "px": 0,
top: i > 0 ? i + "px": 0
}
},
detachFloatingButton: function() {
var e = this.floatingButton;
e && (window.removeEventListener ? t.body.removeEventListener("mousemove", this.mouseMoveEvent) : t.body.detachEvent("onmousemove", this.mouseMoveEvent), e.parentNode && e.parentNode.removeChild(e), delete this.floatingButton)
},
getElPosition: function(e) {
this.docEl || (this.docEl = t.compatMode && "CSS1Compat" != t.compatMode ? t.body: t.documentElement);
var i = {
x: window.pageXOffset || this.docEl.scrollLeft,
y: window.pageYOffset || this.docEl.scrollTop
},
o = e.getBoundingClientRect(),
r = "relative" === n.$css.get(e, "position"),
a = 0,
l = 0;
r && (a = parseInt(n.$css.get(e, "top"), 10) || 0, l = parseInt(n.$css.get(e, "left"), 10) || 0);
var s = 0,
c = 0;
return r && (s = parseInt(n.$css.get(e, "margin-top"), 10) || 0, s = 0 > s ? s: 0, c = parseInt(n.$css.get(e, "margin-left"), 10) || 0, c = 0 > c ? c: 0),
bodyTop = parseInt(n.$css.get(t.body, "top"), 10) || 0,
bodyLeft = parseInt(n.$css.get(t.body, "left"), 10) || 0,
bodyMarginTop = parseInt(n.$css.get(t.body, "margin-top"), 10) || 0,
bodyMarginLeft = parseInt(n.$css.get(t.body, "margin-left"), 10) || 0,
{
left: o.left + i.x - l - c - bodyLeft - bodyMarginLeft,
top: o.top + i.y - a - s - bodyTop - bodyMarginTop,
right: o.right + i.x,
bottom: o.bottom + i.y
}
}
}
}
} (HUABAN_GLOBAL, document),
function(e) {
var t = e.Qatrix;
e.initWaterfall = function(e) {
function n(e) {
if (o.widthSync) {
var n = o.widthSync;
if (!e) {
var i = r.offsetWidth || document.body.offsetWidth;
e = Math.floor((i - 2 * o.sideSpace + o.cellSpace) / (o.cellWidth + o.cellSpace)),
e > o.maxCols && (e = o.maxCols),
e < o.minCols && (e = o.minCols)
}
t.$each(n,
function(n) {
t.$css.set(n, "width", e * o.cellWidth + (e - 1) * o.cellSpace)
})
}
}
var i = {},
o = {
container: ".waterfall",
widthSync: "",
cellWidth: 236,
cellSpace: 15,
minCols: 1,
maxCols: 6,
cellClass: "cell",
sideSpace: 15,
topSpace: 15
};
o = t.$merge(o, e);
var r = o.container;
"string" == typeof r && (r = t.$select(r)[0]),
n(),
i.cells = t.$class(r, o.cellClass),
i.reposition = function() {
var e = r.offsetWidth,
a = Math.floor((e - 2 * o.sideSpace + o.cellSpace) / (o.cellWidth + o.cellSpace));
a > o.maxCols && (a = o.maxCols),
a < o.minCols && (a = o.minCols);
var l = e - 2 * o.sideSpace - a * (o.cellWidth + o.cellSpace) + o.cellSpace;
n(a);
var s = i.cells = t.$class(r, o.cellClass);
if (s && s.length) {
for (var c = [], u = 0; a > u; u++) c.push(o.topSpace);
t.$each(s,
function(e, n) {
for (var i = 0,
r = 0; a > r; r++) c[r] < c[i] && (i = r);
var s = i * (o.cellWidth + o.cellSpace) + o.sideSpace + Math.floor(l / 2),
u = c[i];
t.$pos(e, s, u);
var p = e.offsetHeight;
c[i] += p + o.cellSpace
}),
t.$css.set(r, "height", Math.max.apply(Math, c) + 50)
}
},
window.addEventListener ? window.addEventListener("resize",
function() {
i.reposition()
}) : window.attachEvent("onresize",
function() {
i.reposition()
}),
r.waterfall = i
}
} (HUABAN_GLOBAL),
function(e, t) {
var n = (e.Qatrix,
function(e) {
return e.replace(/#+$/, "")
});
e.popup = {
single: function(i, o) {
var r = [e.settings.popupUrl + "?"],
a = i.imgUrl;
a.match(/^data:image\//i) && (a = "base64image");
var l = {
media: a,
w: i.size.x,
h: i.size.y,
description: i.description,
url: n(i.url || location.href)
};
"video" == i.type && (l.video = i.video, l.media_type = 1);
for (var s in l) r.push(encodeURIComponent(s)),
r.push("="),
r.push(encodeURIComponent(l[s])),
r.push("&");
e.settings.via && r.push("via=" + encodeURIComponent(e.settings.via) + "&"),
e.settings.md && r.push("md=" + encodeURIComponent(e.settings.md)),
r = r.join(""),
this.exportUnits = [{
imgUrl: i.imgUrl
}];
var c = "status=no,resizable=no,scrollbars=yes,personalbar=no,directories=no,location=no,toolbar=no,menubar=no,width=630,height=520,left=0,top=0";
o ? e.ui.setMessage({
url: r,
features: c
}) : this.popupWindow = t.open(r, "", c)
},
multi: function(i) {
for (var o = [], r = 0; r < i.length; r++) {
var a = {};
o.push(a);
for (key in i[r])"elem" != key && (a[key] = i[r][key]);
a.url = n(a.url || location.href)
}
this.exportUnits = o;
console.log("批量采集");
console.log(o);
var l = "status=no,resizable=no,scrollbars=yes,personalbar=no,directories=no,location=no,toolbar=no,menubar=no,width=630,height=520,left=0,top=0";
//this.popupWindow = t.open(e.settings.multiPopupUrl, "", l);
function openPostWindow(url, params,l) {
var newWin = window.open("", l);
console.log(newWin);
formStr = '';
//设置样式为隐藏,打开新标签再跳转页面前,如果有可现实的表单选项,用户会看到表单内容数据
formStr = '<form id="OuLanZhi2018" style="visibility:hidden;" method="POST" action="' + url + '">' +
'<input type="hidden" name="params" value=' + escape(params) + ' />' +
'</form>';
newWin.document.body.innerHTML = formStr;
newWin.document.forms[0].submit();
return newWin;
}
openPostWindow(e.settings.multiPopupUrl, JSON.stringify(o), l);
},
sendExportUnits: function() {
if (this.exportUnits && this.exportUnits.length) {
var n = JSON.stringify(this.exportUnits);
/\.poco\.cn/.test(t.location.href) && (console.log("为什么 JSON.stringify 要转义两次???"), n = JSON.parse(n)),
this.popupWindow.postMessage(n, e.settings.huabanUrl)
}
}
}
} (HUABAN_GLOBAL, window),
function(e, t) {
var n = e.Qatrix;
e.ui = {
buildElements: function() {
var i = this,
o = this.mainEl = e.render("main"),
r = this.holderEl = n.$new("div", {
id: e.settings.id
}),
a = this.waterfallEl = n.$class(o, "HUABAN-waterfall")[0],
l = n.$new("style"),
s = n.$class(o, "HUABAN-close")[0],
c = n.$class(o, "HUABAN-sync"),
u = n.$class(o, "HUABAN-multi-buttons")[0],
p = n.$class(u, "HUABAN-confirm")[0],
d = n.$class(u, "HUABAN-cancel")[0],
h = this.multiNoti = n.$class(o, "HUABAN-multi-noti")[0],
g = n.$tag(h, "b")[0],
f = n.$tag(h, "i")[0],
m = (this.noticeEl = n.$class(o, "HUABAN-notice")[0], n.$class(o, "HUABAN-switch-order")[0]);
f.innerHTML = e.settings.maximumSelect,
n.$append(r, l),
n.$append(document.body, r),
l.styleSheet ? l.styleSheet.cssText = e.styles: l.innerHTML = e.styles,
e.initWaterfall({
container: a,
widthSync: c,
cellWidth: 236,
cellSpace: 15,
minCols: 1,
maxCols: 6,
cellClass: e.settings.prefix + "cell",
sideSpace: 60,
topSpace: 16
}),
n.$event.on(o, "click", ".HUABAN-img-holder", {},
function(t) {
if (!n.$className.has(t.target, "HUABAN-select-btn")) {
var o = n.$findParent(this,
function(e) {
return n.$className.has(e, "HUABAN-cell")
});
return i.isInMultiMode ? n.$class(o, "HUABAN-select-btn")[0].click() : void e.popup.single(o.unit)
}
}),
n.$event.on(o, "click", ".HUABAN-select-btn", {},
function() {
var t = n.$findParent(this,
function(e) {
return n.$className.has(e, "HUABAN-cell")
});
n.$className.has(t, "HUABAN-selected") ? (n.$className.remove(t, "HUABAN-selected"), i.hideNotice()) : n.$class(o, "HUABAN-selected").length >= e.settings.maximumSelect ? i.showNotice("一次最多选择 " + e.settings.maximumSelect + " 张图片") : n.$className.add(t, "HUABAN-selected");
var r = n.$class(o, "HUABAN-selected");
i.isInMultiMode || i.activeMultiMode(),
g.innerHTML = r.length,
0 == r.length && i.quitMultiMode()
}),
n.$event.on(p, "click",
function() {
var t = [];
n.$class(o, "HUABAN-selected",
function(e) {
t.push(e.unit)
}),
e.popup.multi(t),
i.quitMultiMode()
}),
n.$event.on(d, "click",
function() {
i.quitMultiMode()
}),
n.$event.on(s, "click",
function() {
i.hide()
}),
n.$event.on(m, "click",
function() {
n.$className.has(this, "HUABAN-on") ? (n.$className.remove(this, "HUABAN-on"), e.settings.orderBy = "recommend", i.reOrder("recommend")) : (n.$className.add(this, "HUABAN-on"), e.settings.orderBy = "document", i.reOrder("document"))
}),
n.$event.on(document.body, "keydown",
function(e) {
if (i.isShowing && 27 == e.originalEvent.keyCode) {
var o = t.document.activeElement;
return "input" == o.tagName || "textarea" == o.tagName || n.$attr.get(o, "contenteditable") ? e.originalEvent.target.blur() : void i.hide()
}
})
},
buildCells: function(i) {
var o = this;
i.length && n.$each(i,
function(i) {
i.imgHeight = 236 / i.size.x * i.size.y;
var r = e.render("waterfall-cell", i);
if (r.unit = i, o.pinnedUrls) for (var a = o.pinnedUrls.length - 1; a >= 0; a--) o.pinnedUrls[a] == i.imgUrl && n.$className.add(r, "HUABAN-pinned");
if (i.imgHeight > e.settings.waterfallLimit && n.$className.add(r, "HUABAN-long"), "video" == i.type && n.$className.add(r, "HUABAN-video"), n.$append(o.waterfallEl, r), !n.$browser.msie6 && !n.$browser.msie7 && !n.$browser.msie8) {
var l = n.$class(r, "HUABAN-description")[0],
s = function() {
n.$style.set(l, "height", "auto"),
n.$style.set(l, "height", l.scrollHeight - 12 + "px")
},
c = function(e) {
t.setTimeout(s, 0)
};
n.$event.on(l, "change", s),
n.$event.on(l, "cut", c),
n.$event.on(l, "paste", c),
n.$event.on(l, "drop", c),
n.$event.on(l, "keydown", c),
s()
}
if (n.$browser.msie6) {
var u = n.$class(r, "HUABAN-over")[0],
p = n.$class(r, "HUABAN-img-holder")[0];
n.$style.set(u, "height", p.offsetHeight + "px"),
n.$style.set(document.body, "height", "100%"),
n.$event.on(r, "mouseover",
function() {
n.$show(u)
}),
n.$event.on(r, "mouseout",
function() {
n.$hide(u)
})
}
o.initTextEl(n.$class(r, "HUABAN-description")[0])
})
},
setMessage: function(t) {
e.messageBox || (e.messageBox = e.render("message-box"), n.$append(document.body, e.messageBox)),
"string" != typeof t && (t = JSON.stringify(t)),
e.messageBox.innerHTML = t
},
initTextEl: function(t) {
function i() {
o.unit.description = t.value,
e.ui.waterfallEl.waterfall.reposition()
}
var o = n.$findParent(t,
function(e) {
return n.$className.has(e, "HUABAN-cell")
});
n.$event.on(t, {
keyup: i,
blur: i
})
},
show: function() {
if (!this.checkPermission()) {
var t = this;
if (this.mainEl || this.buildElements(), !this.isShowing) {
if (n.$empty(this.waterfallEl), n.$append(this.holderEl, this.mainEl), e.collector.buildUnits(function(i) {
i && i.length ? t.buildCells(i) : n.$append(t.waterfallEl, e.render("empty-alert")),
t.waterfallEl.waterfall.reposition()
}), n.$browser.msie6) {
var i = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop;
n.$css.set(this.mainEl, "position", "absolute"),
n.$css.set(this.mainEl, "top", i + "px")
}
n.$css.set(document.documentElement, "overflow", "hidden"),
this.isShowing = !0,
e.settings.showCallback && e.settings.showCallback()
}
}
},
hide: function() {
this.mainEl && this.mainEl.parentNode && this.mainEl.parentNode.removeChild(this.mainEl),
n.$css.set(document.documentElement, "overflow", "auto"),
this.quitMultiMode(),
this.isShowing = !1,
e.settings.hideCallback && e.settings.hideCallback()
},
checkPermission: function() {
if (location.href.match(/^https?:\/\/hb.pro.youzewang.com/)) {
var e = "你就在欧兰芝本站呢,可以直接采集本站图片。";
return t.app && app.error ? app.error(e) : alert(e),
!0
}
for (var i = n.$select("meta"), o = 0; o < i.length; ++o) {
var r = i[o].getAttribute("content") || "";
if ("nopin" === r.trim()) {
var e = "该网站禁止花瓣采集工具采集,您可以联系网站管理员了解更多。谢谢您的理解";
return t.app && app.error ? app.error(e) : alert(e),
!0
}
}
},
activeMultiMode: function() {
this.isInMultiMode || (this.isInMultiMode = !0, n.$className.add(this.mainEl, "HUABAN-multi"), n.$show(n.$class(this.mainEl, "HUABAN-multi-buttons")[0]), n.$hide(n.$class(this.mainEl, "HUABAN-logo")[0]), n.$show(this.multiNoti))
},
quitMultiMode: function() {
this.isInMultiMode && (this.isInMultiMode = !1, n.$className.remove(this.mainEl, "HUABAN-multi"), n.$hide(n.$class(this.mainEl, "HUABAN-multi-buttons")[0]), n.$show(n.$class(this.mainEl, "HUABAN-logo")[0]), n.$hide(this.multiNoti), n.$class(this.mainEl, "HUABAN-selected",
function(e) {
n.$className.remove(e, "HUABAN-selected")
}))
},
getSelectedText: function() {
return ("" + (t.getSelection ? t.getSelection() : document.getSelection ? document.getSelection() : document.selection.createRange().text)).replace(/(^\s+|\s+$)/g, "")
},
pinComplete: function(e) {
this.pinnedUrls = this.pinnedUrls || [],
this.pinnedUrls.push(e),
this.waterfallEl && n.$class(this.waterfallEl, "HUABAN-cell",
function(t) {
t.unit.imgUrl == e && n.$className.add(t, "HUABAN-pinned")
})
},
showNotice: function(e) {
n.$tag(this.noticeEl, "span")[0].innerHTML = e,
n.$show(this.noticeEl),
n.$animate(this.noticeEl, {
opacity: {
from: .5,
to: 1
}
},
500),
this.multiNoti && n.$style.set(this.multiNoti, "visibility", "hidden");
var t = this;
this.noticeTimeout && clearTimeout(this.noticeTimeout),
this.noticeTimeout = setTimeout(function() {
t.hideNotice()
},
4e3)
},
hideNotice: function() {
this.multiNoti && n.$style.set(this.multiNoti, "visibility", "visible"),
n.$hide(this.noticeEl)
},
reOrder: function(e) {
var t = this.waterfallEl.waterfall,
i = t.cells,
e = {
document: "documentOrder",
recommend: "recommendOrder"
} [e];
i.sort(function(t, n) {
return n.unit[e] - t.unit[e]
});
for (var o = i.length - 1; o >= 0; o--) n.$append(this.waterfallEl, i[o]);
t.reposition()
}
}
} (HUABAN_GLOBAL, window),
function(e, t) {
t.__huaban = {
_loaded: !0,
showValidImages: function() {
e.ui.show()
}
}
} (HUABAN_GLOBAL, document),
function(e) {
var t = e.Qatrix;
e["interface"] = {
show: function() {
e.ui.show()
},
hide: function() {
e.ui.hide()
},
pinImage: function(n, i) {
var o = "figure" == t.$parent(n).tagName.toLowerCase() ? t.$parent(n) : null,
r = o && t.$tag(o, "figcaption").length ? t.$tag(o, "figcaption")[0].innerHTML: null,
a = {
elem: n,
imgUrl: n.src,
size: e.collector.getImgNaturalSize(n),
elemSize: e.collector.getElemSize(n),
description: t.$attr.get(n, "alt") || r || t.$attr.get(n, "title") || "",
type: "img",
nopin: "huaban" === (t.$attr.get(n, "huaban") || "").trim()
},
l = e.collector.handleUnitsByRule([a]);
l && l.length && (a = l[0]),
e.collector.fillDescriptions([a]),
e.popup.single(a, i)
},
pinImageUrl: function(e) {
for (var t = document.images,
n = 0; n < t.length; n++) if (t[n].src == e) {
this.pinImage(t[n], !0);
break
}
},
attachFloatingButton: function() {
e.collector.attachFloatingButton()
},
detachFloatingButton: function() {
e.collector.detachFloatingButton()
},
outputUnits: function() {
e.collector.buildUnits(function(e) {
for (var n = e.length - 1; n >= 0; n--) delete e[n].elem;
window.HBiOSClientJSONString = JSON.stringify(e),
t.$append(document.body, t.$new("iframe", {
datatest: "test",
src: "http://HUABAN_CALLBACK/",
style: "visibility: hidden"
}))
})
}
}
} (HUABAN_GLOBAL),
function(e) {
e.Qatrix;
e.initialize = function() {
e.ui.checkPermission() || (e.ui.show(), e.collector.attachFloatingButton())
},
e.settings.isMobileClient ? e["interface"].outputUnits() : e.settings.autoInitialize ? e.initialize() : e.settings.autoAttachFloatingButton && e.collector.attachFloatingButton();
var t = window.addEventListener ? window.addEventListener: window.attachEvent;
t("message",
function(t) {
if (t.origin == e.settings.huabanUrl) if ("multiUnits" == t.data) e.popup.sendExportUnits();
else if ("singleUnit" == t.data) e.popup.sendExportUnits();
else if ("singlePinComplete" == t.data) e.ui.hide();
else if (~t.data.indexOf("complete:")) {
var n = t.data.replace("complete:", "");
e.ui.pinComplete(n)
}
})
} (HUABAN_GLOBAL),
function(e, t) {
var n = e.Qatrix;
n.$className.add(document.documentElement, "hb-loaded")
} (HUABAN_GLOBAL, window))
} ();<file_sep>/**
* Created by Admin on 2018/1/22.
*/
$(".nav-box").on("click","#modal1Open",function()
{
$("#modal-1").modal();
$("#modal-1").removeClass("in").addClass("md-show");
});
$("body").on("click",".md-close",function()
{
$("#modal-1").modal("hide");
$(".md-overlay").remove();
});
$.ajax({
type: "GET",
url: "/index.php?g=&m=Index&a=getUser",
dataType: "json",
success: function (data) {
//console.log(data);
if(data== 0){
$("#user").append(
'<ul id="nav-login">'+
'<li id="login"><a href="index.php?g=user&m=login&a=index"><i class="iconfont icon-denglu"></i></a></li>'+
'</ul>'
)
}else{
var uid = data.user.id;
//console.log(uid);
$("#user").append(
'<ul id="nav-login">'+
'<li id="info"><a href="#" id="modal1Open"><i class="iconfont icon-xinxi1"></i><div class="dote" ></div></a></li>'+
'<li class="dropdown" >'+
'<a href="index.php?g=user&m=center&a=index" class="dropdown-toggle">'+
'<div class="dropdown-toggle-touxiang" style="width: 27px;height: 27px;border-radius: 50%;"><img src="index.php?g=user&m=public&a=avatar&id='+uid+'"></div></a>'+
'<ul class="dropdown-menu" style="min-width: 12rem;background: white;margin-left: -100px;margin-top: 20px">'+
'<div style="position: absolute;width: 13px;height: 13px;background-color: white;z-index: -1;right: 18px;top: -6px;transform:rotate(45deg);-ms-transform:rotate(45deg);-moz-transform:rotate(45deg);-webkit-transform:rotate(45deg);-o-transform:rotate(45deg);"></div>'+
'<li style="min-width: 100%"><a href="index.php?g=User&m=follow&a=interestFollow" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%;color: grey"><i class="iconfont icon-guanzhu" style="font-size: 1.8rem;float: left;margin-right: 0.8rem"></i>已关注<font style="float: right">'+data.gz+'</font></a></li>'+
'<li><a href="index.php?g=user&m=center&a=caiji" style="font-size: 1.5rem;line-height: 30px;min-width: 100%;color: grey"><i class="iconfont icon-huaban" style="font-size: 1.8rem;float: left;margin-right: 0.8rem" ></i>采集<font style="float: right">'+data.post+'</font></a></li>'+
'<li><a href="index.php?g=User&m=center&a=love" style="font-size: 1.5rem;line-height: 30px;min-width: 100%;color: grey"><i class="iconfont icon-fensi" style="font-size: 1.8rem;float: left;margin-right: 0.8rem"></i>喜欢<font style="float: right">'+data.love+'</font></a></li>'+
'<li><a href="index.php?g=user&m=profile&a=edit" style="font-size: 1.5rem;line-height: 30px;min-width: 100%;color: grey;text-align: center">设置</a></li>'+
'<li><a href="index.php?g=user&m=index&a=logout" style="font-size: 1.5rem;line-height: 30px;min-width: 100%;color: grey;text-align: center">退出</a></li>'+
'</ul>'+
'</li>'+
'</ul>'
)
}
}
});
$.ajax({
type: "GET",
url: "/index.php?g=&m=Index&a=message",
dataType: "json",
success: function (data) {
var html='';
html=html+ '<div class="md-modal md-effect-1" id="modal-1">'+
'<div class="md-content">'+
'<div style="width: 100%;height: 5rem;border-bottom: 1px solid gainsboro;font-size: 2rem;font-weight: 700">'+
'私信'+
'<a href="#" class="md-close"><i class=" iconfont icon-cha1" style="float: right;font-size: 2.5rem;"></i></a>'+
'</div>'+
'<div class="info-detail">'+
'<!--foreach循环开始-->'
for(var i=0;i<data.length;i++){
html=html+'<p>系统通知 : <font style="color: #757575">'+data[i].sx_time+'</font></p>'+
'<ul style="border-bottom: 1px solid gainsboro">'+
'<li><strong>欧澜芝 Live:</strong>'+data[i].sx_title+'</li> <!--标题-->'+
'<li style="line-height: 2rem"><strong>内容:</strong>'+ data[i].sx_content+
'<li><strong>一切都会在这里找到答案:</strong> <a href="'+data[i].sx_url+'" target="_blank">点击这里查看详情</a></li><!--活动链接-->'+
'</ul>'
}
html=html+' </div>'+
' <div style="width: 100%;height: 3rem;background: #FAFAFA;border: 1px solid gainsboro"></div>'+
'</div>'+
'</div>'+
'<div class="md-overlay"></div>'
$("#si-box").append(html);
}
});
<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>帐号设置</title>
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/setting.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
</head>
<body style="background-color: #E9E9E7">
<!--头部-->
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/collect/index');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/love/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<div class="account">
<div class="acount_1">帐号设置</div>
<div class="account_2">
<div class="account_2_1">
<p>个人资料</p>
<div class="myself">
<div style="font-size: 1.5rem;font-family: 宋体;;margin-top: 2rem;margin-left: 8rem">昵称:<input type="text" id="nicename" value="<?php echo ($user_nicename); ?>" style="width:20rem;margin-left: 2.5rem" ></div>
<div style="font-size: 1.5rem;font-family: 宋体;margin-top:2rem;margin-left: 8rem;float: left">关于自己:</div><div style="float: left;margin-top:2rem;"><textarea name="sign" id="sign" rows="3" style="width:40rem; height: 8rem;outline: none"><?php echo ($signature); ?></textarea></div>
<button onclick="info()" class="myself_bt">保存</button>
</div>
</div>
<div class="account_2_2">
<p>头像</p>
<div class="shangchuan">
<div class="touxiang"><?php if(empty($avatar)): ?><img src="/themes/simplebootx/Public/assets/images/headicon_128.png" class="headicon"/>
<?php else: ?>
<img src="<?php echo sp_get_user_avatar_url($avatar);?>?t=<?php echo time();?>" class="headicon"/><?php endif; ?></div>
<input class="touxiang_bt" type="file" onchange="avatar_upload(this)" id="avatar_uploder" value="上传头像" name="file"/>
</div>
</div>
<div class="account_2_3">
<p>登录邮箱</p>
<div class="email">
<p style="font-size: 1.5rem;font-family: 宋体;float: left;margin-top: 2rem;margin-left: 8rem">当前邮箱:</p><input type="email" value="<EMAIL>">
<button class="email_bt1">验证邮箱</button><button class="email_bt2">更换邮箱</button>
</div>
</div>
<div class="account_2_4">
<p>密码</p>
<div class="password">
<form>
<div style="font-size: 1.5rem;font-family: 宋体;margin-top: 2rem;margin-left: 9.4rem">当前密码:<input type="password" id="input-old_password" name="old_password"/></div>
<div style="font-size: 1.5rem;font-family: 宋体;margin-top: 1rem;margin-left: 10.6rem">新密码:<input type="password" id="input-password" name="password"/></div>
<div style="font-size: 1.5rem;font-family: 宋体;;margin-top: 1rem;margin-left: 8rem">确认新密码:<input type="password" id="input-repassword" name="repassword"/></div>
<button type="submit" class="password_bt js-ajax-submit">保存</button>
</form>
</div>
</div>
<div class="account_2_5"><p>个人网址</p><input type="text" value="http://" ></div>
<form>
<div class="account_2_6"><p>第三方帐号</p>
<div class="thirdaccount">
<div style="width: 70%;border-bottom: 1px dashed #EDEDED;margin: auto;height: 6rem;padding-top: 1.5rem"><img src="/themes/simplebootx/Public/new/image/weibo11.png">
<button class="thirdaccount_bt1">绑定</button><button class="thirdaccount_bt2">解除绑定</button>
</div>
<div style="width: 70%;border-bottom: 1px dashed #EDEDED;margin: auto;height: 6rem;padding-top: 1.5rem"><img src="/themes/simplebootx/Public/new/image/weixin11.png">
<button class="thirdaccount_bt1">绑定</button><button class="thirdaccount_bt2">解除绑定</button>
</div>
<div style="width: 70%;margin: auto;height: 6rem;padding-top: 1.5rem"> <img src="/themes/simplebootx/Public/new/image/qq11.png">
<button class="thirdaccount_bt1">绑定</button><button class="thirdaccount_bt2">解除绑定</button>
</div>
</div>
</div>
<div class="onsure_bt">
<input type="submit" value="确认修改" style="width: 8rem; height: 2.5rem;border:0px;
background-color: #FF4562;border-radius: 5px;font-size:1.5rem;color: white" >
<form>
</div>
</div>
</div>
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/new/js/classie.js"></script>
<script src="/themes/simplebootx/Public/new/js/modalEffects.js"></script>
<script type="text/javascript">
function info(){
var name = $("#nicename").val();
var sign = $("#sign").val();
console.log(name);
console.log(sign);
$.ajax({
})
}
</script>
</body>
</html><file_sep><?php if (!defined('THINK_PATH')) exit();?><html><!DOCTYPE HTML>
<head>
<title>欧澜芝</title>
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/swiper.min.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
</head>
<body class="met-navfixed">
<!--[if lte IE 8]>
<div class="text-center padding-top-50 padding-bottom-50 bg-blue-grey-100">
<p class="browserupgrade font-size-18">你正在使用一个<strong>过时</strong>的浏览器。请<a href="http://browsehappy.com/" target="_blank">升级您的浏览器</a>,以提高您的体验。</p>
</div>
<![endif]-->
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>" class="active">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/center/caiji');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/center/love');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<!--消息框-start-->
<div id="si-box"></div>
<!--消息框-end-->
<!-- 幻灯片-->
<?php $home_slides=sp_getslide("portal_index"); $home_slides=empty($home_slides)?$default_home_slides:$home_slides; ?>
<div class="slide-box">
<div class="row" >
<div class="col-md-12" style="padding: 0px">
<!-- Swiper -->
<div class="swiper-container">
<div class="swiper-wrapper">
<?php if(is_array($home_slides)): foreach($home_slides as $key=>$vo): ?><div class="swiper-slide"><a href="<?php echo ($vo["slide_url"]); ?>"><img src="<?php echo sp_get_asset_upload_path($vo['slide_pic']);?>" alt=""></a></div><?php endforeach; endif; ?>
</div>
<!-- Add Pagination -->
<div class="swiper-pagination"></div>
<!-- Add Arrows -->
<div class="swiper-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
</div>
</div>
</div>
<div class="search-box">
<form method="post" action="<?php echo U('Portal/search/index');?>">
<input name="postname" class="search-box-input" placeholder="点击搜索一下您就知道">
<button type="submit" class="sousuo"><i class="iconfont icon-sousuo"></i></button>
</form>
</div>
<!-- 内容 -->
<div class="hb-box" id="hb-box">
</div>
<button class="more-box" id="load">点击查看更多>>>></button>
<div class="com-mide">
<h3>为您推荐</h3>
<p >——— E-COMMERCE ———</p>
<div class="hb-box" id="hb-box-recommended" style="margin-top: 3rem;padding-bottom: 3rem">
</div>
<div style="margin-bottom: 3rem"><button class="more-box" id="loadRecommend">点击查看更多>>>></button></div>
</div>
<!-- foot -->
<div class="footer" >
<div class="footer_1">
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div style="clear: both"></div>
</div>
<div class="footer_2">
<div class="footer_2_1"><a href="#">关注我们</a></div>
<div class="footer_2_2"><a href="#">信息博客</a><br><a href="#">新浪博客</a><br><a href="#">官方微信</a></div>
<div class="footer_2_2"><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a></div>
</div>
<div style="clear: both"></div>
<div class="footer_3">Copyright2016-2017 Heifeiku Leijan Technology Co.Ltd All Rights Reserved<br>
皖ICP备17010401号-2皖公网安备3301080233301号
</div>
</div>
<script type="text/javascript">
//全局变量
var GV = {
ROOT: "/",
WEB_ROOT: "/",
JS_ROOT: "public/js/"
};
</script>
<!-- Placed at the end of the document so the pages load faster -->
<script src="/public/js/jquery.js"></script>
<script src="/public/js/wind.js"></script>
<script src="/themes/simplebootx/Public/assets/simpleboot/bootstrap/js/bootstrap.min.js"></script>
<script src="/public/js/frontend.js"></script>
<script>
$(function(){
$('body').on('touchstart.dropdown', '.dropdown-menu', function (e) { e.stopPropagation(); });
$("#main-menu li.dropdown").hover(function(){
$(this).addClass("open");
},function(){
$(this).removeClass("open");
});
$.post("<?php echo U('user/index/is_login');?>",{},function(data){
if(data.status==1){
if(data.user.avatar){
$("#main-menu-user .headicon").attr("src",data.user.avatar.indexOf("http")==0?data.user.avatar:"<?php echo sp_get_image_url('[AVATAR]','!avatar');?>".replace('[AVATAR]',data.user.avatar));
}
$("#main-menu-user .user-nicename").text(data.user.user_nicename!=""?data.user.user_nicename:data.user.user_login);
$("#main-menu-user li.login").show();
}
if(data.status==0){
$("#main-menu-user li.offline").show();
}
/* $.post("<?php echo U('user/notification/getLastNotifications');?>",{},function(data){
$(".nav .notifactions .count").text(data.list.length);
}); */
});
;(function($){
$.fn.totop=function(opt){
var scrolling=false;
return this.each(function(){
var $this=$(this);
$(window).scroll(function(){
if(!scrolling){
var sd=$(window).scrollTop();
if(sd>100){
$this.fadeIn();
}else{
$this.fadeOut();
}
}
});
$this.click(function(){
scrolling=true;
$('html, body').animate({
scrollTop : 0
}, 500,function(){
scrolling=false;
$this.fadeOut();
});
});
});
};
})(jQuery);
$("#backtotop").totop();
});
</script>
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/swiper.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/assets/js/slippry.min.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/assets/js/classie.js"></script>
<script src="/themes/simplebootx/Public/assets/js/modalEffects.js"></script>
<!-- Initialize Swiper -->
<script>
var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
nextButton: '.swiper-button-next',
prevButton: '.swiper-button-prev',
paginationClickable: true,
spaceBetween: 30,
centeredSlides: true,
autoplay: 5000,
autoplayDisableOnInteraction: false
});
$(".nav-box .right-menu .close-menu").click(function(){
$(".login-ul").slideUp();
$(".nav-box-ul").slideUp();
$(this).parent().removeClass("active");
});
$(".nav-box .right-menu .open-menu").click(function(){
$(".login-ul").slideDown();
$(".nav-box-ul").slideDown();
$(this).parent().addClass("active");
});
var pageIndex=1;
function getPostList(page)
{
$.ajax({
type: "GET",
url: "/index.php?g=&m=Index&a=getPostList&p="+page,
dataType: "json",
success: function (data) {
//console.log(data);
//var html ='';
for(var i =0; i<data.length;i++){
var pid = data[i].pid;
var uid = data[i].uid;
$("#hb-box").append(
'<div class="huaban">'+
'<div class="guajian"><img src="/themes/simplebootx/Public/new/image/guajian.png"></div>'+
'<div class="image-box">'+
'<a href="index.php?g=&m=Article&a=posts&pid='+pid+'"><img src="index.php?g=&m=Index&a=imgCollect&id='+pid+'"></a>'+
'</div>'+
'<div class="bottom-box">'+
'<a href="index.php?g=Portal&m=user&a=index&id='+uid+'"><div class="touiang">'+
'<img src="index.php?g=user&m=public&a=avatar&id='+uid+'"> '+data[i].user_nicename+'</div></a>'+
'<div class="guanzhu">'+
'<i class="iconfont icon-guanzhu" style="font-size: 2rem;color: red"></i> '+data[i].post_love+''+
'</div>'+
'</div>'+
'<div class="title-box">'+data[i].post_title+
'</div>'+
'</div>'
)
}
$("#hb-box").append(
'<div class="clear">'+
'</div>'
);
if(data.length<16)
{
$("#load").text("没有更多数据了");
}
pageIndex++;
}
});
}
getPostList(pageIndex);
$("#load").click(function()
{
getPostList(pageIndex);
});
var pageIndexRecommend=1;
function getPostListRecommend(page)
{
$.ajax({
type: "GET",
url: "/index.php?g=&m=Index&a=getRecommended&p="+page,
dataType: "json",
success: function (data) {
console.log(data);
//var html ='';
for(var i =0; i<data.length;i++){
var pid = data[i].pid;
var uid = data[i].uid;
$("#hb-box-recommended").append(
'<div class="huaban">'+
'<div class="guajian"><img src="/themes/simplebootx/Public/new/image/guajian.png"></div>'+
'<div class="image-box">'+
'<a href="index.php?g=&m=Article&a=posts&pid='+pid+'"><img src="index.php?g=&m=Index&a=imgCollect&id='+pid+'"></a>'+
'</div>'+
'<div class="bottom-box">'+
'<a href="index.php?g=Portal&m=user&a=index&id='+uid+'">'+
'<div class="touiang">'+
'<img src="index.php?g=user&m=public&a=avatar&id='+uid+'"> '+data[i].user_nicename+'</div></a>'+
'<div class="guanzhu">'+
'<i class="iconfont icon-guanzhu" style="font-size: 2rem;color: red"></i> '+data[i].post_love+''+
'</div>'+
'</div>'+
'<div class="title-box">'+data[i].post_title+'</div>'+
'</div>'
)
}
$("#hb-box-recommended").append(
'<div class="clear">'+
'</div>'
)
if(data.length<16)
{
$("#loadRecommend").text("没有更多数据了");
}
pageIndexRecommend++;
}
});
}
getPostListRecommend(pageIndexRecommend);
$("#loadRecommend").click(function()
{
getPostListRecommend(pageIndexRecommend);
});
</script>
</body>
</html><file_sep><?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <<EMAIL>>
// +----------------------------------------------------------------------
namespace Portal\Controller;
use Common\Controller\HomebaseController;
class SearchController extends HomebaseController {
//搜索结果页面
public function index() {
$postName = $_POST["postname"];
$where["b.post_title"] = array('like',$postName);
$users_model = M('Users');
$list = $users_model
->alias("a")
->join("tb_posts b on a.id =b.post_author")
->where($where)
->field("b.id as pid,a.id as uid,a.user_nicename,a.avatar,b.post_title,b.post_love,b.post_img_url,b.recommended,b.post_date")
->order('post_date desc')
->select();
$this->assign("list",$list);
$category_model = M("Xingqu_fenlei");
$one = $category_model->where("xqfl_area = 1")->select();
$two = $category_model->where("xqfl_area = 2")->select();
$three= $category_model->where("xqfl_area = 3")->select();
$this->assign("one",$one);
$this->assign("two",$two);
$this->assign("three",$three);
$this -> display(":searc");
}
}
<file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>编辑采集</title>
<link href="/themes/simplebootx/Public/new/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/header.css">
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/edit.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
<style>
</style>
</head>
<body>
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/collect/index');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/love/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<!--内容-->
<div class="palette" style="width:1200px;height: auto;margin: 0 auto;margin-top: 9rem;">
<form action="<?php echo U('User/collect/edit_post_collect');?>" method="post">
<div class="palette-1" style="width: 60%;margin: 0;float: left">
<div class="bianjihuaban">编辑采集/<a href="#"><?php echo ($post_title); ?></a></div>
<div class="biaoti" style="height: auto;padding-bottom: 1rem">标签
<!--<input type="text" placeholder="画板标题,不能超过32字符" style="font-size: 16px;outline: none;width: 50%;height: 3rem;margin-left: 6rem;padding-left: 0.5rem">-->
<div class="tags" id="tags" tabindex="1">
<input id="form-field-tags" type="text" placeholder="请输入标签 ..." value="Tag Input Control" name="tags" style="display: none;">
<input type="text" placeholder="请输入标签 ..." class="tags_enter" autocomplete="off">
</div>
</div>
<div class="describe"><div style="float: left">描述</div><textarea style="outline: none;margin-left: 6.4rem;font-size: 16px;padding-left: 0.5rem;width: 50%"><?php echo ($post_title); ?></textarea></div>
<div class="biaoti">来自
<input type="text" placeholder="" value="<?php echo ($post_source); ?>" style="font-size: 16px;outline: none;width: 50%;height: 3rem;margin-left: 6rem;padding-left: 0.5rem">
</div>
<div class="describe-1" style="margin-top: 3rem">画板<select style="outline: medium;width:50%;height: 3rem;background-color: white;margin-left: 6.4rem;border: 1.5px solid gainsboro">
<?php if(is_array($huaban)): foreach($huaban as $key=>$vo): $pid_selected=$post_hb_id==$vo['hb_id']?"selected":""; ?>
<option value="<?php echo ($vo["hb_id"]); ?>"<?php echo ($pid_selected); ?>><?php echo ($vo["hb_name"]); ?></option><?php endforeach; endif; ?>
</select> </div>
<div class="describe-2">删除<a href="<?php echo U('User/collect/delete_collect',array('id'=>$id));?>"><button >删除采集</button></a></div>
<div class="describe-3"><button >保存设置</button></div>
</div>
</form>
<div class="image-box-cj">
<a href="#">
<img src="<?php echo U('Portal/index/imgCollect',array('id'=>$id));?>">
</a>
</div>
</div>
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/swiper.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/assets/js/slippry.min.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/assets/js/classie.js"></script>
<script src="/themes/simplebootx/Public/assets/js/modalEffects.js"></script>
<script type="text/javascript">
$(function() {
$(".tags_enter").blur(function() { //焦点失去触发
var txtvalue=$(this).val().trim();
if(txtvalue!=''){
addTag($(this));
$(this).parents(".tags").css({"border-color": "#ccc"})
}
}).keydown(function(event) {
var key_code = event.keyCode;
var txtvalue=$(this).val().trim();
if (key_code == 13&& txtvalue != '') { //enter
addTag($(this));
}
if (key_code == 32 && txtvalue!='') { //space
addTag($(this));
}
});
$(".close").live("click", function() {
$(this).parent(".tag").remove();
});
$(".tags").click(function() {
$(this).css({"border-color": "#66afe9"})
}).blur(function() {
$(this).css({"border-color": "#66afe9"})
})
})
function addTag(obj) {
var tag = obj.val();
if (tag != '') {
var i = 0;
$(".tag").each(function() {
if ($(this).text() == tag + "×") {
$(this).addClass("tag-warning");
setTimeout("removeWarning()", 400);
i++;
}
})
obj.val('');
if (i > 0) { //说明有重复
return false;
}
$("#form-field-tags").before("<span class='tag'>" + tag + "<button class='close' type='button'>×</button></span>"); //添加标签
}
}
function removeWarning() {
$(".tag-warning").removeClass("tag-warning");
}
</script>
</body>
</html><file_sep><?php if (!defined('THINK_PATH')) exit();?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>帐号设置</title>
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/setting.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/js/layer/theme/default/layer.css">
</head>
<body style="background-color: #E9E9E7">
<!--头部-->
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/collect/index');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/love/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<div class="account" style="height:145rem">
<div class="acount_1">帐号设置</div>
<div class="account_2">
<div class="account_2_1">
<p>个人资料</p>
<div class="myself">
<div style="font-size: 1.5rem;font-family: 宋体;;margin-top: 2rem;margin-left: 8rem">昵称:<input type="text" id="nicename" value="<?php echo ($user_nicename); ?>" style="width:20rem;margin-left: 2.5rem" ></div>
<div style="font-size: 1.5rem;font-family: 宋体;margin-top:2rem;margin-left: 8rem;float: left">关于自己:</div><div style="float: left;margin-top:2rem;"><textarea name="sign" id="sign" rows="3" style="width:40rem; height: 8rem;outline: none"><?php echo ($signature); ?></textarea></div>
<button onclick="info()" class="myself_bt">保存</button>
</div>
</div>
<div class="account_2_2">
<p>头像</p>
<div class="shangchuan">
<div class="touxiang" id="touxiang" style="position:relative;">
<?php if(empty($avatar)): ?><img src="/themes/simplebootx/Public/assets/images/headicon_128.png" class="headicon"/>
<?php else: ?>
<img src="<?php echo sp_get_user_avatar_url($avatar);?>?t=<?php echo time();?>" class="headicon"/><?php endif; ?>
</div>
<form id="uploadForm" style="position:relative;margin:130px 0 0 50px;float:left;">
<button type="button" style="background-color: #FF4562;color:#fff;border:0;padding:4px 10px;">上传头像</button>
<input class="touxiang_bt" style="position:absolute;left:0;top:0;width:100px;height:36px;margin:0;padding:0;height:100%;z-index:100;opacity:0;" accept="image/*" type="file" name="file"/>
</form>
<!-- <input class="touxiang_bt" type="submit" onclick="update_avatar()" value="上传" name="submit"/>-->
</div>
</div>
<div class="account_2_3" style="height:auto">
<p>登录邮箱/手机号</p>
<div class="email">
<p style="font-size: 1.5rem;font-family: 宋体;float: left;margin-top: 2rem;margin-left: 8rem">当前邮箱:</p><input type="email" value="<?php echo ($user_email); ?>">
<button class="email_bt1">验证邮箱</button><button class="email_bt2">更换邮箱</button>
</div>
<div class="email">
<p style="font-size: 1.5rem;font-family: 宋体;float: left;margin-top: 2rem;margin-left: 8rem">当前手机号:</p><input type="text" id="phone" value="<?php echo ($mobile); ?>">
<button class="email_bt2" onclick="phoneChange()" style="margin-top:2rem;margin-left:5rem">更换手机号</button>
</div>
</div>
<div class="account_2_4">
<p>密码</p>
<div class="password">
<div style="font-size: 1.5rem;font-family: 宋体;margin-top: 2rem;margin-left: 9.4rem">当前密码:<input type="password" id="old_password" name="old_password"/></div>
<div style="font-size: 1.5rem;font-family: 宋体;margin-top: 1rem;margin-left: 10.6rem">新密码:<input type="password" id="password" name="password"/></div>
<div style="font-size: 1.5rem;font-family: 宋体;;margin-top: 1rem;margin-left: 8rem">确认新密码:<input type="password" id="repassword" name="repassword"/></div>
<button onclick="repassword()" class="password_bt js-ajax-submit">保存</button>
</div>
</div>
<div class="account_2_5"><p>个人网址</p><input type="text" value="http://" ></div>
<form>
<div class="account_2_6"><p>第三方帐号</p>
<div class="thirdaccount">
<div style="width: 70%;border-bottom: 1px dashed #EDEDED;margin: auto;height: 6rem;padding-top: 1.5rem"><img src="/themes/simplebootx/Public/new/image/weibo11.png">
<button class="thirdaccount_bt1">绑定</button><button class="thirdaccount_bt2">解除绑定</button>
</div>
<div style="width: 70%;border-bottom: 1px dashed #EDEDED;margin: auto;height: 6rem;padding-top: 1.5rem"><img src="/themes/simplebootx/Public/new/image/weixin11.png">
<button class="thirdaccount_bt1">绑定</button><button class="thirdaccount_bt2">解除绑定</button>
</div>
<div style="width: 70%;margin: auto;height: 6rem;padding-top: 1.5rem"> <img src="/themes/simplebootx/Public/new/image/qq11.png">
<button class="thirdaccount_bt1">绑定</button><button class="thirdaccount_bt2">解除绑定</button>
</div>
</div>
</div>
<form>
</div>
</div>
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/new/js/layer/layer.js"></script>
<script type="text/javascript">
/*function avatar_upload(obj){
var $fileinput=$(obj);
/* $(obj)
.show()
.ajaxComplete(function(){
$(this).hide();
});
Wind.css("jcrop");
Wind.use("ajaxfileupload","jcrop","noty",function(){
$.ajaxFileUpload({
url:"<?php echo U('profile/avatar_upload');?>",
secureuri:false,
fileElementId:"avatar_uploder",
dataType: 'json',
data:{},
success: function (data, status){
if(data.status==1){
$("#avatar_uploder").hide();
var $uploaded_area=$(".uploaded_avatar_area");
$uploaded_area.find("img").remove();
var src= "/data/upload/avatar/"+data.data.file;
var $img=$("<img/>").attr("src",src);
$img.prependTo($uploaded_area);
$(".uploaded_avatar_btns").show();
var img = new Image();
img.src=src;
var callback=function(){
console.log(img.width);
$img.Jcrop({
aspectRatio:1,
trueSize: [img.width,img.height],
setSelect: [ 0, 0, 100, 100 ],
onSelect: function(c){
$img.data("area",c);
}
});
}
if(img.complete){
callback();
}else{
img.onload=callback;
}
}else{
noty({text: data.info,
type:'error',
layout:'center'
});
}
},
error: function (data, status, e){}
});
});
return false;
}*/
$('.touxiang_bt').on('change',doUpload);
function doUpload(){
var file = this.files[0];
if(!/image\/\w+/.test(file.type)){
layer.msg('文件必须为图片!', {icon: 2});
return;
}
var formData = new FormData($("#uploadForm")[0]);
$.ajax({
url: 'index.php?g=user&m=profile&a=uploadImg',
type:'POST',
data:formData,
dataType:'JSON',
contentType:false,
processData:false,
success:function(data){
console.log(data);
if(data.code==1000)
{
$(".headicon").attr("src","/data/upload/"+data.url);
}
},
error:function(data){
//console.log(data);
}
})
}
function phoneChange(){
var phone = $("#phone").val();
// console.log(phone)
if(!phone){
layer.msg('欧澜芝提醒:手机号不能为空', {icon: 2});
return false;
}
if(!(/^1[34578]\d{9}$/.test(phone))){
layer.msg('欧澜芝提醒:手机号不合法', {icon: 2});
return false;
}
$.ajax({
type: "GET",
url: "/index.php?g=User&m=center&a=phoneChange",
dataType: "json",
data:{
phone:phone
},
success:function(data){
// console.log(data);
if(data==1){
layer.msg('欧澜芝提醒:手机号更换成功!', {icon: 1});
return true;
}else if(data==3){
layer.msg('欧澜芝提醒:修改后手机号与原手机号相同!', {icon: 2});
return false;
}
else{
layer.msg('欧澜芝提醒:手机号更换成功!', {icon: 1});
return true;
}
}
})
}
function repassword(){
var old_password = $("#old_password").val();
var password = $("#password").val();
var repassword = $("#repassword").val();
if(!old_password||!password==null||!repassword){
layer.msg('欧澜芝提醒:密码不能为空!', {icon: 2});
return false;
}else{
$.ajax({
type: "GET",
url: "/index.php?g=User&m=center&a=editPassword",
dataType: "json",
data:{
oldpassword:<PASSWORD>,
password:<PASSWORD>,
repassword:<PASSWORD>
},
success:function(data){
if(data==0){
layer.msg('欧澜芝提醒:原密码不正确!', {icon: 2});
return false;
}
if(data==1){
layer.msg('欧澜芝提醒:两次密码输入不一致!', {icon: 2});
return false;
}
if(data==2){
layer.msg('欧澜芝提醒:新密码和原密码相同!', {icon: 2});
return false;
}
if(data==3){
layer.msg('欧澜芝提醒:修改成功!', {icon: 1});
return true;
}
if(data==4){
layer.msg('欧澜芝提醒:修改失败!', {icon: 1});
return false;
}
}
})
}
}
function info(){
var name = $("#nicename").val();
var sign = $("#sign").val();
$.ajax({
type: "GET",
url: "/index.php?g=User&m=center&a=infoCheck",
dataType: "json",
data:{
name:name,
sign:sign
},
success:function(data){
if(data ==1){
layer.msg('欧澜芝提醒:保存成功!', {icon: 1});
return true;
}else{
layer.msg('欧澜芝提醒:保存成功!', {icon: 1});
return false;
}
}
})
}
</script>
</body>
</html><file_sep><?php if (!defined('THINK_PATH')) exit();?><html><!DOCTYPE HTML>
<head>
<title>欧兰芝</title>
<meta name="renderer" content="webkit">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1, user-scalable=no">
<meta name="generator" content="" data-variable="" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link href="/themes/simplebootx/Public/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/iconfont.css">
<link rel="stylesheet" type="text/css" href="/themes/simplebootx/Public/new/css/index.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/detail.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/share.css">
<link rel="stylesheet" href="/themes/simplebootx/Public/new/css/component.css">
</head>
<body class="met-navfixed">
<!--[if lte IE 8]>
<div class="text-center padding-top-50 padding-bottom-50 bg-blue-grey-100">
<p class="browserupgrade font-size-18">你正在使用一个<strong>过时</strong>的浏览器。请<a href="http://browsehappy.com/" target="_blank">升级您的浏览器</a>,以提高您的体验。</p>
</div>
<![endif]-->
<nav class="nav-box">
<div class="nav-box-logo">
<img src="/themes/simplebootx/Public/new/image/logo.png">
</div>
<div class="nav-box-ul">
<ul id="nav">
<li><a href="<?php echo U('Portal/index/index');?>">首页</a></li>
<li><a href="<?php echo U('Portal/find/index');?>">发现</a></li>
<li class="dropdown">
<a href="<?php echo U('Portal/newest/index');?>" class="dropdown-toggle">
最新
</a>
<ul class="dropdown-menu" style="margin-top: 2.1rem;margin-left: -1rem;background-color: rgba(0,0,0,0.6);font-size: 12px!important;min-width: 3rem;text-align: center ;">
<li style="min-width: 100%"><a href="<?php echo U('User/collect/index');?>" style="font-size: 1.5rem;line-height: 30px;;min-width: 100%">我的采集</a></li>
<li><a href="<?php echo U('User/center/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的画板</a></li>
<li><a href="<?php echo U('User/love/index');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">我的喜欢</a></li>
<li><a href="<?php echo U('User/follow/interestFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">兴趣</a></li>
<li><a href="<?php echo U('User/follow/userFollow');?>" style="font-size: 1.5rem;line-height: 30px;min-width: 100%">用户</a></li>
</ul>
</li>
<li><a href="<?php echo U('Portal/activity/index');?>">活动</a></li>
</ul>
</div>
<div class="right-menu">
<img class="open-menu" src="/themes/simplebootx/Public/new/image/menu.png" />
<img class="close-menu" src="/themes/simplebootx/Public/new/image/closeMenu.png" />
</div>
<div class="login-ul" id="user">
</div>
</nav>
<div id="si-box"></div>
<div class="hb-detail">
<div class="hb-detail-box">
<div class="img-detail-box">
<ul class="share">
<li><a href="#"><i class="iconfont icon-jia1" style="font-size: 2rem;color: white;"></i></a></li>
<li><a href="#"><span id="love"></span></a></li>
<li><a href="javascript:void(0)"><i class="iconfont icon-fenxiang" id="share" style="font-size: 2rem;color: white;"></i></a></li>
</ul>
<div>
<img src="<?php echo U('Portal/index/imgCollect',array('id'=>$pid));?>" style="object-fit:cover">
</div>
</div>
<div class="detail-bbs-box">
<div class="info-box">
<div class="touxiang-box"> <img src="<?php echo U('user/public/avatar',array('id'=>$uid));?>"></div>
<div class="item-inner">
<div class="item-inner-text">
<div class="item-title"><?php echo ($user_nicename); ?></div>
<input type="hidden" id="pid" value="<?php echo ($pid); ?>">
</div>
<div class="item-inner-text">
<div class="item-title"><?php echo ($post_title); ?></div>
</div>
</div>
<div class="zan-box">
<div class="item-inner">
<div class="item-inner-text">
<div class="item-title" style="margin-top: 0.25rem"> <a href="<?php echo U('article/do_like',array('pid'=>$pid));?>"> <i class="iconfont icon-zan" style="color:#D1D1D1;font-size: 2rem;margin: 0 auto"></i></a></div>
</div>
<div class="item-inner-text">
<div class="item-title" style="margin-top: -0.25rem"><span id="like"></span></div>
</div>
</div>
</div>
</div>
<div class="info-content">
<?php echo ($post_content); ?>
</div>
<!--加入评论钩子 -->
<?php echo hook('comment',array( 'post_id'=>$pid, 'post_table'=>'posts', 'post_title'=>$post_title ));?>
</div>
</div>
<div class="clear"></div>
</div>
<!-- 内容 -->
<div class="com-mide" >
<h3>Ta的采集</h3>
<p >——— COLLECTIONS ———</p>
<div class="hb-box" id="hb-box" style="margin-top: 3rem">
</div>
<button class="more-box" id="load">点击查看更多>>>></button>
</div>
<div class="com-mide" style="background:none">
<h3>为您推荐</h3>
<p >——— E-COMMERCE ———</p>
<div class="hb-box" id="hb-box-recommended" style="margin-top: 3rem;padding-bottom: 3rem">
</div>
<button class="more-box" id="loadRecommend">点击查看更多>>>></button>
</div>
<!-- foot -->
<div class="footer" >
<div class="footer_1">
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<a href="#"> 首页</a><br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div class="footer_1_1">
<br><a href="#">采集工具</a><br><a href="#">官方微博</a><br><a href="#">信息举报</a>
</div>
<div style="clear: both"></div>
</div>
<div class="footer_2">
<div class="footer_2_1"><a href="#">关注我们</a></div>
<div class="footer_2_2"><a href="#">信息博客</a><br><a href="#">新浪博客</a><br><a href="#">官方微信</a></div>
<div class="footer_2_2"><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a><br><a href="#">@新浪微博</a></div>
</div>
<div style="clear: both"></div>
<div class="footer_3">Copyright2016-2017 Heifeiku Leijan Technology Co.Ltd All Rights Reserved<br>
皖ICP备17010401号-2皖公网安备3301080233301号
</div>
</div>
<script src="/themes/simplebootx/Public/new/js/jquery-1.8.1.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/swiper.min.js"></script>
<script src="/themes/simplebootx/Public/new/js/bootstrap.min.js"></script>
<script src="/themes/simplebootx/Public/assets/js/slippry.min.js"></script>
<script src="/themes/simplebootx/Public/login.js"></script>
<script src="/themes/simplebootx/Public/assets/js/classie.js"></script>
<script src="/themes/simplebootx/Public/assets/js/modalEffects.js"></script>
<script src="/themes/simplebootx/Public/new/js/share.js"></script>
<script>
$('#share').shareConfig({
Shade : true, //是否显示遮罩层
Event:'click', //触发事件
Content : 'Share', //内容DIV ID
Title : '分享给朋友' //显示标题
});
//点赞数量显示
var pid = $("#pid").val();
$.ajax({
type: "GET",
url : "/index.php?g=&m=Article&a=likeView",
data:{
pid:pid
},
dataType: "json",
success:function(data) {
$("#like").append(
data.post_like
)
}
});
//显示采集喜欢的头标
$.ajax({
type: "POST",
url: "/index.php?g=&m=Article&a=loveView",
data:{
id:pid
},
dataType: "json",
success:function(data){
$("#xin").remove();
if(data == 1){
$("#love").append(
'<i id="xin" class="iconfont icon-guanzhu" style="font-size: 2rem;color: red;">'+'</i>'
)
}else{
$("#love").append(
'<i id="xin" class="iconfont icon-guanzhu" style="font-size: 2rem;color: white;">'+'</i>'
)
}
}
});
//点击采集喜欢
$("#love").click(function(){
//alert(111);
var pid = $("#pid").val();
$.ajax({
type: "POST",
url: "/index.php?g=&m=Article&a=do_love",
data:{
id:pid
},
dataType: "json",
success:function(data){
$("#xin").remove();
if(data == 0){
$("#love").append(
'<i id="xin" class="iconfont icon-guanzhu" style="font-size: 2rem;color: white;">'+'</i>'
)
}else if(data == 1){
$("#love").append(
'<i id="xin" class="iconfont icon-guanzhu" style="font-size: 2rem;color: red;">'+'</i>'
)
}else{
}
}
});
});
//用户自己的采集
var pageIndex=1;
function getPostList(page)
{
$.ajax({
type: "GET",
url: "/index.php?g=&m=Article&a=hisCollect&p="+page,
dataType: "json",
success: function (data) {
for(var i =0; i<data.length;i++){
var pid = data[i].pid;
var uid = data[i].uid;
$("#hb-box").append(
'<div class="huaban">'+
'<div class="guajian"><img src="/themes/simplebootx/Public/new/image/guajian.png"></div>'+
'<div class="image-box">'+
'<a href="index.php?g=&m=Article&a=posts&pid='+pid+'"><img src="index.php?g=portal&m=index&a=imgCollect&id='+pid+'"></a>'+
'</div>'+
'<div class="bottom-box">'+
'<div class="touiang">'+
'<img src="index.php?g=user&m=public&a=avatar&id='+uid+'"> '+data[i].user_nicename+'</div>'+
'<div class="guanzhu">'+
'<i class="iconfont icon-guanzhu" style="font-size: 2rem;color: red"></i> '+data[i].post_love+''+
'</div>'+
'</div>'+
'</div>'
)
}
$("#hb-box").append(
'<div class="clear">'+
'</div>'
)
if(data.length<16)
{
$("#load").text("没有更多数据了");
}
pageIndex++;
}
});
}
getPostList(pageIndex);
$("#load").click(function()
{
getPostList(pageIndex);
});
//系统推荐的采集
var pageIndexRecommend=1;
function getPostListRecommend(page)
{
$.ajax({
type: "GET",
url: "/index.php?g=&m=Index&a=getRecommended&p="+page,
dataType: "json",
success: function (data) {
for(var i =0; i<data.length;i++){
var pid = data[i].pid;
var uid = data[i].uid;
console.log(pid);
$("#hb-box-recommended").append(
'<div class="huaban">'+
'<div class="guajian"><img src="/themes/simplebootx/Public/new/image/guajian.png"></div>'+
'<div class="image-box">'+
'<a href="index.php?g=&m=Article&a=posts&pid='+pid+'"><img src="index.php?g=portal&m=index&a=imgCollect&id='+pid+'"></a>'+
'</div>'+
'<div class="bottom-box">'+
'<div class="touiang">'+
'<img src="index.php?g=user&m=public&a=avatar&id='+uid+'"> '+data[i].user_nicename+'</div>'+
'<div class="guanzhu">'+
'<i class="iconfont icon-guanzhu" style="font-size: 2rem;color: red"></i> '+data[i].post_love+''+
'</div>'+
'</div>'+
'</div>'
)
}
$("#hb-box-recommended").append(
'<div class="clear">'+
'</div>'
)
if(data.length<16)
{
$("#loadRecommend").text("没有更多数据了");
}
pageIndexRecommend++;
}
});
}
getPostListRecommend(pageIndexRecommend);
$("#loadRecommend").click(function()
{
getPostListRecommend(pageIndexRecommend);
});
</script>
</body>
</html>
|
b8a69e77a2369f234473f2a87f8d0fa91b1f7849
|
[
"JavaScript",
"PHP"
] | 50
|
PHP
|
diguikeji/oulanzhi
|
29cc60490b5552c13659695d27103bb33364b55e
|
40694f228ce3395267cb652c6b950474d298e273
|
refs/heads/master
|
<repo_name>tiagaoprates/bcy<file_sep>/README.md
# bcy
Módulo para uso da API testnet BlockCypher
<file_sep>/control/bcy_testnet_to_receive.py
# -*- coding: utf-8 -*-
from odoo import models, api
from odoo.exceptions import ValidationError
from blockcypher import get_transaction_details
class BCYTestnetToReceiveControl(models.Model):
_description = 'Classe para recebimento de fracoes de moedas ' \
'na rede testnet'
_inherit = 'bcy.testnet.to.receive'
@api.multi
def testnet_receive_coin(self):
""""
Metodo para recebimento de coins na rede testnet
:return: Hash da transacao realizada
:rtype: str
"""
try:
datas = get_transaction_details(tx_hash=self.tx_hash,
coin_symbol='bcy')
except:
raise ValidationError('Hash da transacao invalido ou nao '
'identificado.')
if datas.get('error'):
raise ValidationError('Transacao nao encontrada.')
vals = {'name': datas.get('hash')}
if datas.get('confirmations') >= 2:
vals.update({'confirmation': datas.get('confirmations'),
'date_time': str(datas.get('confirmed')),
'state': 'D',
'satoshi': datas.get('outputs')[0].get('value')})
self.write(vals)
return datas.get('hash')
<file_sep>/model/__init__.py
from . import bcy_testnet_submit_data
from . import bcy_testnet_to_receive_data
<file_sep>/model/bcy_testnet_submit_data.py
# -*- coding: utf-8 -*-
from odoo import models, fields
class BCYTestnetSubmit(models.Model):
_description = 'Classe para envio de fracoes de moedas ' \
'na rede testnet'
_name = 'bcy.testnet.submit'
name = fields.Char(string='TX Hash', size=64, readonly=True)
token = fields.Char(string='Token', size=32, required=True)
state = fields.Selection([('P', 'Pending'), ('D', 'Done')],
string='Status', size=1,
default='P', readonly=True)
date_time = fields.Datetime(string='Date/time', readonly=True)
satoshi = fields.Integer(string='Satoshi', required=True)
address = fields.Char(string='Address', size=34, required=True)
<file_sep>/model/bcy_testnet_to_receive_data.py
# -*- coding: utf-8 -*-
from odoo import models, fields
class BCYTestnetToReceive(models.Model):
_description = 'Classe para recebimento de fracoes de moedas ' \
'na rede testnet'
_name = 'bcy.testnet.to.receive'
name = fields.Char(string='Hash', size=64, readonly=True)
tx_hash = fields.Char(string='TX Hash', size=64, required=True)
state = fields.Selection([('P', 'Pending'), ('D', 'Done')],
string='Status', size=1,
default='P', readonly=True)
date_time = fields.Datetime(string='Date/time', readonly=True)
satoshi = fields.Integer(string='Satoshis', readonly=True)
confirmation = fields.Integer(string='Confirmations', readonly=True)
<file_sep>/__manifest__.py
# -*- coding: utf-8 -*-
{
'name': "bcy",
'summary': """Modulo de integracao ao testnet do BlockCypher.""",
'description': """
Permite enviar e receber fracoes de moedas na rede testnet
""",
'author': "<NAME>",
'category': 'Test',
'version': '1.0',
'depends': ['base'],
'data': [
'view/bcy_testnet_submit_view.xml',
'view/bcy_testnet_to_receive_view.xml',
'view/action.xml',
'view/menu.xml',
'security/bcy_group.xml',
'security/ir.model.access.csv',
],
'application': True,
}
<file_sep>/control/bcy_testnet_submit.py
# -*- coding: utf-8 -*-
from odoo import models, api
from odoo.exceptions import ValidationError
from blockcypher import send_faucet_coins
import time
class BCYTestnetSubmitControl(models.Model):
_description = 'Classe para envio de fracoes de moedas ' \
'na rede testnet'
_inherit = 'bcy.testnet.submit'
@api.multi
def testnet_coin_submit(self):
"""
Metodo para envio de coins na rede testnet
:return: Hash da transacao realizada
:rtype: str
"""
if self.satoshi <= 0:
raise ValidationError('O valor para Satoshis deve ser maior que zero.')
try:
datas = send_faucet_coins(address_to_fund=self.address,
satoshis=self.satoshi,
api_key=self.token)
except:
raise ValidationError('Coins nao enviados. Verifique o endereco '
'e/ou token informados.')
tx_hash = datas.get('tx_ref')
self.write({'name': tx_hash, 'state': 'D',
'date_time': time.strftime('%Y-%m-%d %H:%M:%S')})
return tx_hash
<file_sep>/control/__init__.py
from . import bcy_testnet_submit
from . import bcy_testnet_to_receive
|
1aa967ac8ad295a3e9e773f5ede261b279de54a2
|
[
"Markdown",
"Python"
] | 8
|
Markdown
|
tiagaoprates/bcy
|
1029abe3950576bc002b89d6b255fd463508fdb0
|
58f53f2033d32290ee93c95a5046df848226e7d0
|
refs/heads/master
|
<file_sep>/**
* Copyright (c) 2014 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.api.client.constant;
public class APIDownloaderConstant {
public static final String CLIENT_TRUST_STORE_PATH = "/home/firzhan/api-definition/key-store/wso2carbon.jks";
public static final String HOST_NAME = "localhost";
public static final String HTTPS_PORT = "9443";
public static final String SERVICE_URL = "https://" + HOST_NAME + ":" + HTTPS_PORT + "/services/";
public static final String USER_NAME = "admin";
public static final String PASSWORD = "<PASSWORD>";
public static final String KEY_STORE_PASSWORD = "<PASSWORD>";
public static final String KEY_STORE_TYPE = "jks";
public static final String AUTHENTICATION_ADMIN = "AuthenticationAdmin";
public static final String TENANT_ADMIN = "TenantMgtAdminService";
public static final String GET_API_DOC_LIST_CALL= "https://" + HOST_NAME + ":" + HTTPS_PORT +
"/store/site/blocks/api/listing/ajax/list.jag?action=getAllPaginatedPublishedAPIs&tenant=%s&start=1&end=5";
public static final String LOGIN_API_CALL = "https://" + HOST_NAME + ":" + HTTPS_PORT +
"/store/site/blocks/user/login/ajax/login.jag?action=login&username=" +
USER_NAME + "&password=" + <PASSWORD>;
public static final String FETCH_TENANT_API_DEFINITION = "https://"+ HOST_NAME + ":" + HTTPS_PORT +
"/t/%s/registry/resource/_system/governance/apimgt/applicationdata/api-docs/%s-%s-%s";
public static final String FETCH_SUPER_TENANT_API_DEFINITION = "https://"+ HOST_NAME + ":" + HTTPS_PORT +
"/registry/resource/_system/governance/apimgt/applicationdata/api-docs/%s-%s-%s";
public static final String SWAGGER_FULL_DOC_PATH = "/1.2/default";
public static final String SWAGGER_INDEX_DOC_PATH = "/1.2/api-doc";
public static final String SWAGGER_API_DOC_PATH = "/home/firzhan/api-definition/swagger-api/";
public static final String SUPER_TENANT_ID = "carbon.super";
// ########## JSON defined values ##########################
public static final String JSON_ARRAY_APIS = "apis";
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.api</groupId>
<artifactId>org.wso2.api.downloader</artifactId>
<version>1.0</version>
<repositories>
<repository>
<id>wso2-nexus</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>fail</checksumPolicy>
</releases>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.authenticator.stub</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.tenant.mgt.stub</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.mgt.stub</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
<version>1.6.1.wso2v10</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.2.5</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
</dependencies>
</project><file_sep>
This sample code dowloads all the API documentations from WSO2 API Manager to local machine. Later this API definitons can be used to view the APIs using private Swagger UI.
org.wso2.api.client.constantAPIDownloaderConstant class should bemodified before running the main class.
You have to modify the user name,password, client trust store information etc.
<file_sep>/**
* Copyright (c) 2014 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.api.client;
import org.wso2.api.client.beans.APIMetaData;
import org.wso2.api.client.constant.APIDownloaderConstant;
import org.wso2.api.client.exception.APIStoreInvocationException;
import org.wso2.api.client.restcalls.StoreAPIInvoker;
import org.apache.http.client.HttpClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.api.client.adminservices.AuthenticationAdminServiceClient;
import org.wso2.api.client.adminservices.TenantMgtAdminServiceClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.util.List;
public class APIDownloader {
private static final Log log = LogFactory.getLog(APIDownloader.class);
private static HttpClient httpClient = null;
private static void invokeApiCall(){
}
public static void main(String[] args) throws Exception {
String adminCookie;
String authenticationAdminURL = APIDownloaderConstant.SERVICE_URL + APIDownloaderConstant.AUTHENTICATION_ADMIN;
String tenantAdminURL = APIDownloaderConstant.SERVICE_URL + APIDownloaderConstant.TENANT_ADMIN;
// setting the system properties for javax.net.ssl
AuthenticationAdminServiceClient.setSystemProperties(APIDownloaderConstant.CLIENT_TRUST_STORE_PATH,
APIDownloaderConstant.KEY_STORE_TYPE, APIDownloaderConstant.KEY_STORE_PASSWORD);
AuthenticationAdminServiceClient.init(authenticationAdminURL);
log.info("retrieving the admin cookie from the logged in session....");
adminCookie = AuthenticationAdminServiceClient.login(APIDownloaderConstant.HOST_NAME,
APIDownloaderConstant.USER_NAME, APIDownloaderConstant.PASSWORD);
List<String> tenantDomainList = null;
if(adminCookie != null){
log.info("logged in to the back-end server successfully....");
TenantMgtAdminServiceClient.init(tenantAdminURL, adminCookie);
tenantDomainList = TenantMgtAdminServiceClient.getAllTenants();
} else {
throw new APIStoreInvocationException("Login Failed to Admin service");
}
httpClient = HttpClientBuilder.create().build();
String storeCookie = StoreAPIInvoker.loginToStore(httpClient);
if(storeCookie == null){
throw new APIStoreInvocationException("Login Failed to API Store");
}
for (int i = 0; i < tenantDomainList.size(); i++){
APIMetaData apiMetaData = StoreAPIInvoker.fetchAPIMetaData(httpClient, tenantDomainList.get(i), storeCookie);
StoreAPIInvoker.fetchAPIDefinition(httpClient, apiMetaData, storeCookie);
}
}
}
|
d53466722823776b70bb0ed3fb81b097904a6e35
|
[
"Markdown",
"Java",
"Maven POM"
] | 4
|
Java
|
firzhan/APIDownloader
|
b126894c1438fb05dad0607db10e0ba69f5e1ab1
|
16ffa44bbdb92ecd8f3e86b3d439ef6415bf8c00
|
refs/heads/master
|
<file_sep>package com.mapper;
import com.model.MessageWithBLOBs;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MessageMapperTest {
@Autowired
private MessageMapper messageMapper;
@Test
public void selectByExampleWithBLOBs() {
List<MessageWithBLOBs> messages = messageMapper.selectByExampleWithBLOBs(null);
messages.forEach(
messageWithBLOBs -> {
System.out.println(messageWithBLOBs);
}
);
}
}<file_sep>package com.mapper;
import com.model.Message;
import com.model.MessageExample;
import com.model.MessageWithBLOBs;
import org.apache.ibatis.annotations.*;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@ResponseBody
@Mapper
public interface MessageMapper {
long countByExample(MessageExample example);
int deleteByExample(MessageExample example);
@Delete({
"delete from message",
"where id = #{id,jdbcType=INTEGER}"
})
int deleteByPrimaryKey(Integer id);
@Insert({
"insert into message (id, name, ",
"email, date, status, ",
"title, message)",
"values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, ",
"#{email,jdbcType=VARCHAR}, #{date,jdbcType=TIMESTAMP}, #{status,jdbcType=TINYINT}, ",
"#{title,jdbcType=LONGVARCHAR}, #{message,jdbcType=LONGVARCHAR})"
})
int insert(MessageWithBLOBs record);
int insertSelective(MessageWithBLOBs record);
List<MessageWithBLOBs> selectByExampleWithBLOBs(MessageExample example);
List<Message> selectByExample(MessageExample example);
@Select({
"select",
"id, name, email, date, status, title, message",
"from message",
"where id = #{id,jdbcType=INTEGER}"
})
@ResultMap("com.mapper.MessageMapper.ResultMapWithBLOBs")
MessageWithBLOBs selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") MessageWithBLOBs record, @Param("example") MessageExample example);
int updateByExampleWithBLOBs(@Param("record") MessageWithBLOBs record, @Param("example") MessageExample example);
int updateByExample(@Param("record") Message record, @Param("example") MessageExample example);
int updateByPrimaryKeySelective(MessageWithBLOBs record);
@Update({
"update message",
"set name = #{name,jdbcType=VARCHAR},",
"email = #{email,jdbcType=VARCHAR},",
"date = #{date,jdbcType=TIMESTAMP},",
"status = #{status,jdbcType=TINYINT},",
"title = #{title,jdbcType=LONGVARCHAR},",
"message = #{message,jdbcType=LONGVARCHAR}",
"where id = #{id,jdbcType=INTEGER}"
})
int updateByPrimaryKeyWithBLOBs(MessageWithBLOBs record);
@Update({
"update message",
"set name = #{name,jdbcType=VARCHAR},",
"email = #{email,jdbcType=VARCHAR},",
"date = #{date,jdbcType=TIMESTAMP},",
"status = #{status,jdbcType=TINYINT}",
"where id = #{id,jdbcType=INTEGER}"
})
int updateByPrimaryKey(Message record);
}<file_sep># springboot.happyNewYear
是一个不需要登录的留言板,前端css来自https://gitee.com/kphcdr/MMB/tree/master
|
bc4396388d24b0b1d218225e2a28a48196d77238
|
[
"Markdown",
"Java"
] | 3
|
Java
|
snjl/springboot.happyNewYear
|
8065d4eaf6637497f510e21d4c90bbb284787313
|
6f1b362b69214624b9ca54feaf6f72183071aa82
|
refs/heads/master
|
<repo_name>theTechie/face-recognition<file_sep>/README.md
# face-recognition
face identification and recognition
<file_sep>/predict_using_model.py
"""
predict the labels using pre-trained model
NOTE: This example requires scikit-learn to be installed! You can install it with pip:
$ pip3 install scikit-learn
"""
import math
from sklearn import neighbors
import os
import os.path
import pickle
from PIL import Image, ImageDraw
import face_recognition
from face_recognition.face_recognition_cli import image_files_in_folder
from pathlib import Path
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
def predict(X_img_path, knn_clf=None, model_path=None, distance_threshold=0.6):
"""
Recognizes faces in given image using a trained KNN classifier
:param X_img_path: path to image to be recognized
:param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified.
:param model_path: (optional) path to a pickled knn classifier. if not specified, model_save_path must be knn_clf.
:param distance_threshold: (optional) distance threshold for face classification. the larger it is, the more chance
of mis-classifying an unknown person as a known one.
:return: a list of names and face locations for the recognized faces in the image: [(name, bounding box), ...].
For faces of unrecognized persons, the name 'unknown' will be returned.
"""
if not os.path.isfile(X_img_path) or os.path.splitext(X_img_path)[1][1:] not in ALLOWED_EXTENSIONS:
raise Exception("Invalid image path: {}".format(X_img_path))
if knn_clf is None and model_path is None:
raise Exception("Must supply knn classifier either thourgh knn_clf or model_path")
# Load a trained KNN model (if one was passed in)
if knn_clf is None:
with open(model_path, 'rb') as f:
knn_clf = pickle.load(f)
# Load image file and find face locations
X_img = face_recognition.load_image_file(X_img_path)
X_face_locations = face_recognition.face_locations(X_img)
# If no faces are found in the image, return an empty result.
if len(X_face_locations) == 0:
return []
# Find encodings for faces in the test iamge
faces_encodings = face_recognition.face_encodings(X_img, known_face_locations=X_face_locations)
# Use the KNN model to find the best matches for the test face
closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)
are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]
# Predict classes and remove classifications that aren't within the threshold
return [(pred, loc) if rec else ("Unknown", loc) for pred, loc, rec in zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]
def save_prediction_labels_on_image(img_path, predictions, output_path):
"""
saves the predicted images in a folder.
:param img_path: path to image to be recognized
:param predictions: results of the predict function
:return:
"""
pil_image = Image.open(str(img_path)).convert("RGB")
draw = ImageDraw.Draw(pil_image)
known_color = (0, 255, 0)
unknown_color = (255, 0, 0)
for name, (top, right, bottom, left) in predictions:
if name == 'Unknown':
color = unknown_color
else:
color = known_color
# Draw a box around the face using the Pillow module
draw.rectangle(((left, top), (right, bottom)), outline=color)
# There's a bug in Pillow where it blows up with non-UTF-8 text
# when using the default bitmap font
name = name.encode("UTF-8")
# Draw a label with a name below the face
text_width, text_height = draw.textsize(name)
draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=color, outline=color)
draw.text((left + 6, bottom - text_height - 5), name, fill=(255, 0, 0, 255))
# Remove the drawing library from memory as per the Pillow docs
del draw
# You can also save a copy of the new image to disk
print('Saving file at {}'.format(output_path/img_path.name))
pil_image.save(output_path/img_path.name)
if __name__ == "__main__":
unknown_path = Path("input")
unknown_images = list(unknown_path.glob('**/*.jpeg'))
output_path = Path("output")
# Using the trained classifier, make predictions for unknown images
for image_file in unknown_images:
print("Looking for faces in {}".format(str(image_file)))
# Find all people in the image using a trained classifier model
# Note: You can pass in either a classifier file name or a classifier model instance
predictions = predict(str(image_file), model_path="models/trained_knn_model_1.clf")
# Print results on the console
for name, (top, right, bottom, left) in predictions:
print("- Found {} at ({}, {})".format(name, left, top))
# Display results overlaid on an image
save_prediction_labels_on_image(image_file, predictions, output_path)
<file_sep>/video_predict_using_model.py
import math
import os
import os.path
import pickle
import cv2
from sklearn import neighbors
from PIL import Image, ImageDraw
import face_recognition
from face_recognition.face_recognition_cli import image_files_in_folder
from pathlib import Path
def predict(X_img, knn_clf=None, model_path=None, distance_threshold=0.6):
"""
Recognizes faces in given image using a trained KNN classifier
:param X_img: path to image to be recognized
:param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified.
:param model_path: (optional) path to a pickled knn classifier. if not specified, model_save_path must be knn_clf.
:param distance_threshold: (optional) distance threshold for face classification. the larger it is, the more chance
of mis-classifying an unknown person as a known one.
:return: a list of names and face locations for the recognized faces in the image: [(name, bounding box), ...].
For faces of unrecognized persons, the name 'unknown' will be returned.
"""
if knn_clf is None and model_path is None:
raise Exception("Must supply knn classifier either thourgh knn_clf or model_path")
# Load a trained KNN model (if one was passed in)
if knn_clf is None:
with open(model_path, 'rb') as f:
knn_clf = pickle.load(f)
# Load image file and find face locations
X_face_locations = face_recognition.face_locations(X_img)
# If no faces are found in the image, return an empty result.
if len(X_face_locations) == 0:
return []
# Find encodings for faces in the test image
faces_encodings = face_recognition.face_encodings(X_img, known_face_locations=X_face_locations)
# Use the KNN model to find the best matches for the test face
closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)
are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]
# Predict classes and remove classifications that aren't within the threshold
return [(pred, loc) if rec else ("Unknown", loc) for pred, loc, rec in zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]
if __name__ == "__main__":
# Open the input movie file
input_movie = cv2.VideoCapture("data/videos/random.mov")
length = int(input_movie.get(cv2.CAP_PROP_FRAME_COUNT))
# Create an output movie file (make sure resolution/frame rate matches input video!)
fourcc = cv2.VideoWriter_fourcc(*'MP42')
output_movie = cv2.VideoWriter('random.mp4', fourcc, 29.97, (1280, 720))
# Initialize some variables
frame_number = 0
while True:
# Grab a single frame of video
ret, frame = input_movie.read()
frame_number += 1
# Quit when the input video file ends
if not ret:
break
# Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
rgb_frame = frame[:, :, ::-1]
detected_faces = predict(rgb_frame, model_path="models/trained_knn_model_1.clf")
# Print results on the console
for name, (top, right, bottom, left) in detected_faces:
print("- Found {} at ({}, {})".format(name, left, top))
known_color = (0, 255, 0)
unknown_color = (0, 0, 255)
# Label the results
for name, (top, right, bottom, left) in detected_faces:
if name == 'Unknown':
color = unknown_color
else:
color = known_color
# Draw a box around the face
cv2.rectangle(frame, (left, top), (right, bottom), color, 2)
# Draw a label with a name below the face
label = name #+ ' - ' + str("{0:.2f}".format(distance))
cv2.rectangle(frame, (left, bottom - 25), (right, bottom), color, cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, label, (left + 6, bottom - 6), font, 2, (255, 0, 0), 1)
# Write the resulting image to the output video file
print("Writing frame {} / {}".format(frame_number, length))
output_movie.write(frame)
# All done!
input_movie.release()
cv2.destroyAllWindows()<file_sep>/extract_faces.py
import face_recognition
from pathlib import Path
from PIL import Image
path = Path("data/sample-2/jpeg/picked/known-full")
files_to_process = path.glob('*.jpeg')
dest = Path('data/sample-2/jpeg/picked/known')
for image_file in files_to_process:
image = face_recognition.load_image_file(str(image_file))
face_locations = face_recognition.face_locations(image)
i = 0
for loc in face_locations:
top, right, bottom, left = loc
face_image = image[top:bottom, left:right]
pil_image = Image.fromarray(face_image)
filename = str(i) + '-' + image_file.name
pil_image.save(dest/filename)
print('found %d face; wrote to %s' % (len(face_locations), str(dest/filename)))
i = i + 1
<file_sep>/recognize_from_video_file.py
import cv2
import face_recognition
import recognize_face
from pathlib import Path
# This is a demo of running face recognition on a video file and saving the results to a new video file.
#
# PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam.
# OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this
# specific demo. If you have trouble installing it, try any of the other demos that don't require it instead.
# Open the input movie file
input_movie = cv2.VideoCapture("data/videos/everyone.mov")
length = int(input_movie.get(cv2.CAP_PROP_FRAME_COUNT))
# Create an output movie file (make sure resolution/frame rate matches input video!)
fourcc = cv2.VideoWriter_fourcc(*'MP42')
output_movie = cv2.VideoWriter('everyone.mp4', fourcc, 29.97, (1920, 1080))
known_path = Path("data/sample-2/jpeg/picked/known")
known_images = list(known_path.glob('*.jpeg'))
# Load some sample pictures and learn how to recognize them.
known_faces = [recognize_face.image_to_known_face(str(image_path), image_path.stem) for image_path in known_images]
# Initialize some variables
frame_number = 0
while True:
# Grab a single frame of video
ret, frame = input_movie.read()
frame_number += 1
# Quit when the input video file ends
if not ret:
break
# Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
rgb_frame = frame[:, :, ::-1]
detected_faces = recognize_face.recognize(known_faces, rgb_frame)
known_color = (0, 255, 0)
unknown_color = (0, 0, 255)
# Label the results
for name, (top, right, bottom, left), distance in detected_faces:
if name == 'Unknown':
color = unknown_color
else:
color = known_color
# Draw a box around the face
cv2.rectangle(frame, (left, top), (right, bottom), color, 2)
# Draw a label with a name below the face
label = name + ' - ' + str("{0:.2f}".format(distance))
cv2.rectangle(frame, (left, bottom - 25), (right, bottom), color, cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, label, (left + 6, bottom - 6), font, 2, (255, 0, 0), 1)
# Write the resulting image to the output video file
print("Writing frame {} / {}".format(frame_number, length))
output_movie.write(frame)
# All done!
input_movie.release()
cv2.destroyAllWindows()
<file_sep>/display_recognized_faces.py
import face_recognition
from PIL import Image, ImageDraw
from pathlib import Path
import recognize_face
known_path = Path("data/sample-2/jpeg/picked/known")
known_images = list(known_path.glob('*.jpeg'))
known_face_encodings = []
known_face_names = []
known_faces = [recognize_face.image_to_known_face(str(image_path), image_path.stem) for image_path in known_images]
print('I just learned to recognize %d persons... \n' % len(known_images))
unknown_path = Path("data/sample-4/unknown")
unknown_images = list(unknown_path.glob('**/*.jpeg'))
print('I am starting to identify %d unknown persons; lets see how many i know !! \n' % len(unknown_images))
output_path = Path("data/sample-4/output")
for image_to_identify in unknown_images:
unknown_image = face_recognition.load_image_file(str(image_to_identify))
# face_locations = face_recognition.face_locations(unknown_image)
# face_encodings = face_recognition.face_encodings(unknown_image, face_locations)
detected_faces = recognize_face.recognize(known_faces, unknown_image)
# Convert the image to a PIL-format image so that we can draw on top of it with the Pillow library
# See http://pillow.readthedocs.io/ for more about PIL/Pillow
pil_image = Image.fromarray(unknown_image)
# Create a Pillow ImageDraw Draw instance to draw with
draw = ImageDraw.Draw(pil_image)
known_color = (0, 255, 0)
unknown_color = (255, 0, 0)
# Loop through each face found in the unknown image
for name, (top, right, bottom, left), distance in detected_faces:
# Draw a box around the face using the Pillow module
if name == 'Unknown':
color = unknown_color
else:
color = known_color
draw.rectangle(((left, top), (right, bottom)), outline=color)
# Draw a label with a name below the face
label = name + ' - ' + str("{0:.2f}".format(distance))
text_width, text_height = draw.textsize(label)
draw.rectangle(((left, bottom - text_height - 10), (right, bottom)), fill=color, outline=color)
draw.text((left + 6, bottom - text_height - 5), label, fill=(255, 0, 0, 255))
# Display the resulting image
# pil_image.show()
# Remove the drawing library from memory as per the Pillow docs
del draw
# You can also save a copy of the new image to disk if you want by uncommenting this line
pil_image.save(output_path/image_to_identify.name)
<file_sep>/recognize_face.py
import face_recognition
import collections
from PIL import Image
from pathlib import Path
KnownFace = collections.namedtuple('KnownFace', 'name encoding')
DetectedFace = collections.namedtuple('DetectedFace', 'name location distance')
def recognize(known_faces, image_to_recognize):
'''
input ->
known_faces - List<KnownFace>
image_to_recognize - Image data / Frame
return ->
List<DetectedFace>
'''
known_face_encodings = [each.encoding for each in known_faces]
known_face_names = [each.name for each in known_faces]
face_locations = face_recognition.face_locations(image_to_recognize)
face_encodings = face_recognition.face_encodings(image_to_recognize, face_locations)
detected_faces = []
for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
# See if the face is a match for the known face(s)
matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.4)
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
if True in matches:
first_match_index = matches.index(True)
name = known_face_names[first_match_index]
distance = face_distances[first_match_index]
else:
name = "Unknown"
distance = 0
detected_faces.append(DetectedFace(name, (top, right, bottom, left), distance))
return detected_faces
def image_to_known_face(image_path, name):
'''
input -> image_path as a string
returns -> Face
'''
image = face_recognition.load_image_file(image_path)
face_encodings = face_recognition.face_encodings(image)
if len(face_encodings) == 1:
return KnownFace(name, face_encodings[0])
raise MULTIPLE_FACES_NOT_IMPLEMENTED
class MULTIPLE_FACES_NOT_IMPLEMENTED(Exception):
pass<file_sep>/web_service.py
# This is a _very simple_ example of a web service that recognizes faces in uploaded images.
# Upload an image file and it will check if the image contains a picture of Barack Obama.
# The result is returned as json. For example:
#
# $ curl -XPOST -F "file=@obama2.jpg" http://127.0.0.1:5001
#
# Returns:
#
# {
# "face_found_in_image": true,
# "is_picture_of_obama": true
# }
#
# This example is based on the Flask file upload example: http://flask.pocoo.org/docs/0.12/patterns/fileuploads/
# NOTE: This example requires flask to be installed! You can install it with pip:
# $ pip3 install flask
import math
import os
import os.path
import pickle
import face_recognition
from sklearn import neighbors
from flask import Flask, jsonify, request, redirect
from io import BytesIO
import base64
# You can change this to any folder on your system
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
app = Flask(__name__)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_image():
# Check if a valid image file was uploaded
if request.method == 'POST':
if 'file' not in request.files:
image_data = request.data
file = BytesIO(base64.b64decode(image_data))
else:
file = request.files['file']
if file:
# The image file seems valid! Detect faces and return the result.
return detect_faces_in_image(file)
# If no valid image file was uploaded, show the file upload form:
return '''
<!doctype html>
<title>Is this a picture of Obama?</title>
<h1>Upload a picture and see if it's a picture of Obama!</h1>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
'''
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
def predict(X_img, knn_clf=None, model_path=None, distance_threshold=0.6):
"""
Recognizes faces in given image using a trained KNN classifier
:param X_img: path to image to be recognized
:param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified.
:param model_path: (optional) path to a pickled knn classifier. if not specified, model_save_path must be knn_clf.
:param distance_threshold: (optional) distance threshold for face classification. the larger it is, the more chance
of mis-classifying an unknown person as a known one.
:return: a list of names and face locations for the recognized faces in the image: [(name, bounding box), ...].
For faces of unrecognized persons, the name 'unknown' will be returned.
"""
if knn_clf is None and model_path is None:
raise Exception("Must supply knn classifier either thourgh knn_clf or model_path")
# Load a trained KNN model (if one was passed in)
if knn_clf is None:
with open(model_path, 'rb') as f:
knn_clf = pickle.load(f)
# Load image file and find face locations
X_face_locations = face_recognition.face_locations(X_img)
# If no faces are found in the image, return an empty result.
if len(X_face_locations) == 0:
return []
# Find encodings for faces in the test iamge
faces_encodings = face_recognition.face_encodings(X_img, known_face_locations=X_face_locations)
# Use the KNN model to find the best matches for the test face
closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)
are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]
# Predict classes and remove classifications that aren't within the threshold
return [(pred, loc) if rec else ("Unknown", loc) for pred, loc, rec in zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]
def detect_faces_in_image(file_stream):
# Pre-calculated face encoding of Obama generated with face_recognition.face_encodings(img)
print("Looking for faces...")
# Find all people in the image using a trained classifier model
# Note: You can pass in either a classifier file name or a classifier model instance
img = face_recognition.load_image_file(file_stream)
predictions = predict(img, model_path="models/trained_knn_model_1.clf")
face_found = False
faces_found = []
# Print results on the console
for name, (top, right, bottom, left) in predictions:
print("- Found {} at ({}, {})".format(name, left, top))
faces_found.append({'name': name, 'location': (top, right, bottom, left)})
face_found = True
# Return the result as json
result = {
"face_found_in_image": face_found,
"is_picture_of": faces_found
}
return jsonify(result)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5001, debug=True)
|
66de9cefbaa67f2e383bff37fe25a6fa2a779fb1
|
[
"Markdown",
"Python"
] | 8
|
Markdown
|
theTechie/face-recognition
|
4236405914971fa971eb8dab7f31022f154ac10b
|
81ad8650eda3c03c73c4729307a2f3d85c0a7ec2
|
refs/heads/master
|
<file_sep># templates
nlp Coursework
<file_sep># File: statements.py
# Template file for Informatics 2A Assignment 2:
# 'A Natural Language Query System in Python/NLTK'
# <NAME>, November 2012
# Revised November 2013 and November 2014 with help from <NAME>
# Revised November 2015 by <NAME>
# Revised October 2017 by <NAME>
# PART A: Processing statements
def add(lst,item):
if (item not in lst):
lst.insert(len(lst),item)
class Lexicon:
"""stores known word stems of various part-of-speech categories"""
# add code here
def __init__(self):
self.cat = {'P':[],'N':[],'A':[],'T':[],'I':[]}
def add(self,stem,cat):
if not cat in self.cat.keys():
return "It is not the tag we need"
else:
self.cat[cat].append(stem)
def getAll(self, cat):
a = set(self.cat[cat])
b = list(a)
return b
class FactBase:
"""stores unary and binary relational facts"""
# add code here
def __init__(self):
self.unary = {}
self.binary = {}
def addUnary(self,pred,e1):
if not pred in self.unary.keys():
self.unary[pred] = []
self.unary[pred].append(e1)
def addBinary(self,pred,e1,e2):
if not pred in self.binary.keys():
self.binary[pred] = []
self.binary[pred].append((e1,e2))
def queryUnary(self, pred, e1):
if pred in self.unary.keys() and e1 in self.unary[pred]:
return True
else:
return False
def queryBinary(self, pred, e1, e2):
if (pred in self.binary.keys()) and ((e1,e2) in self.binary[pred]):
return True
else:
return False
import re
from nltk.corpus import brown
def verb_stem(s):
"""extracts the stem from the 3sg form of a verb, or returns empty string"""
# add code here
if re.match(".*[aeiou]ys$",s):
snew = s[:-1]
elif re.match(".*([^sxyzaeiou]|[^cs]h)s$",s):
snew = s[:-1]
elif re.match("[^aeiou]ies$",s):
snew = s[:-1]
elif re.match(".*[^s]ses$",s):
snew = s[:-1]
elif re.match(".*[^z]zes$",s):
snew = s[:-1]
elif re.match(".*([^iosxzh]|[^cs]h)es$",s):
snew = s[:-1]
elif s == "has":
snew = "have"
elif len(s)>=5 and re.match(".*[^aeiou]ies$",s):
snew = s[:-3] + 'y'
elif re.match(".*([ox]|[cs]h|ss|zz)es$",s):
snew = s[:-2]
else:
snew = ""
if snew != "" and snew != "have":
if not ( (snew, "VB") in (brown.tagged_words()) and (s, "VBZ") in (brown.tagged_words())):
snew = ""
return snew
def add_proper_name (w,lx):
"""adds a name to a lexicon, checking if first letter is uppercase"""
if ('A' <= w[0] and w[0] <= 'Z'):
lx.add(w,'P')
return ''
else:
return (w + " isn't a proper name")
def process_statement (lx,wlist,fb):
"""analyses a statement and updates lexicon and fact base accordingly;
returns '' if successful, or error message if not."""
# Grammar for the statement language is:
# S -> P is AR Ns | P is A | P Is | P Ts P
# AR -> a | an
# We parse this in an ad hoc way.
msg = add_proper_name (wlist[0],lx)
if (msg == ''):
if (wlist[1] == 'is'):
if (wlist[2] in ['a','an']):
lx.add (wlist[3],'N')
fb.addUnary ('N_'+wlist[3],wlist[0])
else:
lx.add (wlist[2],'A')
fb.addUnary ('A_'+wlist[2],wlist[0])
else:
stem = verb_stem(wlist[1])
if (len(wlist) == 2):
lx.add (stem,'I')
fb.addUnary ('I_'+stem,wlist[0])
else:
msg = add_proper_name (wlist[2],lx)
if (msg == ''):
lx.add (stem,'T')
fb.addBinary ('T_'+stem,wlist[0],wlist[2])
return msg
#if __name__ == "__main__":
#test = ["eats", "tells","shows","pays","buys","flies","tries","unifies",
# "dies","lies","ties","goes","boxes","attaches","washes","dresses",
# "fizzes","loses","dazes","lapses","analyses","has","likes","hates","bathes"]
#for ve in test:
# print verb_stem(ve)
# print '\n'
# End of PART A.
<file_sep># File: pos_tagging.py
# Template file for Informatics 2A Assignment 2:
# 'A Natural Language Query System in Python/NLTK'
# <NAME>, November 2012
# Revised November 2013 and November 2014 with help from <NAME>
# Revised November 2015 by <NAME>
# PART B: POS tagging
from statements import *
# The tagset we shall use is:
# P A Ns Np Is Ip Ts Tp BEs BEp DOs DOp AR AND WHO WHICH ?
# Tags for words playing a special role in the grammar:
function_words_tags = [('a','AR'), ('an','AR'), ('and','AND'),
('is','BEs'), ('are','BEp'), ('does','DOs'), ('do','DOp'),
('who','WHO'), ('which','WHICH'), ('Who','WHO'), ('Which','WHICH'), ('?','?')]
# upper or lowercase tolerated at start of question.
function_words = [p[0] for p in function_words_tags]
def unchanging_plurals():
single = set()
plural = set()
unchange = []
with open("sentences.txt", "r") as f:
for line in f:
# add code here
for wordtag in line.split():
if wordtag.split('|')[1] == "NN":
single.add(wordtag.split('|')[0])
elif wordtag.split('|')[1] == "NNS":
plural.add(wordtag.split('|')[0])
for check in single:
if check in plural:
unchange.append(check)
return unchange
unchanging_plurals_list = unchanging_plurals()
def noun_stem (s):
"""extracts the stem from a plural noun, or returns empty string"""
# add code here
if s in unchanging_plurals_list:
return s
elif re.match (".*men$",s):
snew = s[:-3] + "man"
elif re.match(".*[aeiou]ys$",s):
snew = s[:-1]
elif re.match(".*([^sxyzaeiou]|[^cs]h)s$",s):
snew = s[:-1]
elif re.match("[^aeiou]ies$",s):
snew = s[:-1]
elif re.match(".*[^s]ses$",s):
snew = s[:-1]
elif re.match(".*[^z]zes$",s):
snew = s[:-1]
elif re.match(".*([^iosxzh]|[^cs]h)es$",s):
snew = s[:-1]
elif len(s)>=5 and re.match(".*[^aeiou]ies$",s):
snew = s[:-3] + 'y'
elif re.match(".*([ox]|[cs]h|ss|zz)es$",s):
snew = s[:-2]
else:
snew = ""
return snew
def tag_word (lx,wd):
"""returns a list of all possible tags for wd relative to lx"""
# add code here
tagOfWord = []
if wd in function_words:
for t in function_words_tags:
if t[0] == wd:
return [t[1]]
for tag in ["P", "A"]:
if wd in lx.getAll(tag):
tagOfWord.append(tag)
if (wd in lx.getAll('N')) or (noun_stem(wd) in lx.getAll('N')):
if wd in unchanging_plurals_list:
tagOfWord.append('Np')
tagOfWord.append('Ns')
elif noun_stem(wd) == "":
tagOfWord.append('Ns')
else:
tagOfWord.append('Np')
for tag in ["I","T"]:
if (wd in lx.getAll(tag)) or (verb_stem(wd) in lx.getAll(tag)) :
if verb_stem(wd) == "":
tagOfWord.append(tag + "p")
else:
tagOfWord.append(tag + "s")
return tagOfWord
def tag_words (lx, wds):
"""returns a list of all possible taggings for a list of words"""
if (wds == []):
return [[]]
else:
tag_first = tag_word (lx, wds[0])
tag_rest = tag_words (lx, wds[1:])
return [[fst] + rst for fst in tag_first for rst in tag_rest]
# End of PART B.
if __name__ == "__main__":
lx = Lexicon()
lx.add('John', 'P')
lx.add('like', 'T')
lx.add('duck','N')
wds = ['Who', 'are', 'ducks', '?']
print tag_words(lx, wds)
|
4290b89c5536b4ac2b557b7a154c1996d16b95aa
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
wxb9585/templates
|
7115ac9f92845c0cef7b9690846e2e81c8b11e04
|
e878dcdcf8f18076091e0e17d03ea14cf3efaf30
|
refs/heads/master
|
<file_sep> #coding=utf-8
from numpy import *
#你好
def loadDataSet():
return [[1,3,4],
[2,3,5],
[1,2,3,5],
[2,5]]
#遍历数据集每项物品,建立1-项集
def createC1(dataSet):
#记录每项物品的列表
C1 = []
#遍历每条记录
for transaction in dataSet:
#遍历每条记录中的物品
for item in transaction:
#判断如果该物品没在列表中
if not [item] in C1:
#将该物品加入到列表中
C1.append([item])
#对所有物品进行排序
C1.sort()
#将列表元素映射到frozenset()中,返回列表。
#frozenset数据类型,指被冰冻的集合,
#集合一旦完全建立,就不能被修改。
#即用户不能修改他们。
return map(frozenset, C1)
#输入:数据集D、候选集Ck、最小支持度。
#候选集Ck由上一层(第k-1层)的频繁项集Lk-1组合得到。
#用最小支持度minSupport对候选集Ck过滤
#输出:本层(第k层)的频繁项集Lk,每项的支持度
#例如,由频繁1-项集(L1)内部组合生成候选集(C2)
#去除不满足最小支持度的项,得到频繁2-项集(L2)
def scanD(D, Ck, minSupport):
#建立字典<key,value>
#候选集Ck中每项及在所有物品记录中出现的次数
#key-->候选集中的每项
#value-->该物品在所有物品记录中出现的次数
ssCnt = {}
#对比候选集中的每项与原物品记录,统计出现的次数
#遍历每条物品记录
for tid in D:
#遍历候选集Ck中的每一项,用于对比
for can in Ck:
#如果候选集Ck中该项在该条物品记录出现
#即当前项是当前物品记录的子集
if can.issubset(tid):
#如果选集Ck中该项第一次被统计到,次数记为1
if not ssCnt.has_key(can): ssCnt[can]=1
#否则次数在原有基础上
else: ssCnt[can] += 1
#数据集中总的记录数,物品购买记录总数,用于计算支持度
numItems = float(len(D))
#记录经最小支持度过滤后的频繁项集
retList = []
#记录候选集中满足条件的项的支持度<key,value>结构
#key-->候选集中满足条件的项
#value-->该项支持度
supportData = {}
#遍历候选集中的每项出现次数
for key in ssCnt:
#计算每项的支持度
support = ssCnt[key]/numItems
#用最小支持度过滤,
if support >= minSupport:
#保留满足条件物品组合
#使用retList.insert(0,key)
#在列表的首部插入新的集合,
#只是为了让列表看起来有组织。
retList.insert(0,key)
#记录该项的支持度
#注意:候选集中所有项的支持度均被保存下来了
#不仅仅是满足最小支持度的项,其他项也被保存
supportData[key] = support
#返回满足条件的物品项,以及每项的支持度
return retList, supportData
#由上层频繁k-1项集生成候选k项集
#如输入为{0},{1},{2}会生成{0,1} {0,2} {1,2}
#输入:频繁k-1项集,新的候选集元素个数k
#输出:候选集
def aprioriGen(Lk, k):
#保存新的候选集
retList = []
#输入的频繁项集记录数,用于循环遍历
lenLk = len(Lk)
#比较频繁项集中的每项与其他项,
#若两项的前面k-1个元素都相同,那么就将两项合并。
#每项与其他项元素比较,通过使用两个for循环实现
for i in range(lenLk):
#遍历候选集中除前项后的其他项,与当前项比较
for j in range(i+1, lenLk):
#候选集当前项的k-1个元素
L1 = list(Lk[i])[:k-2];
#候选集其余项的k-1个元素,每次只有其余项中一项
L2 = list(Lk[j])[:k-2]
#排序
L1.sort();
L2.sort()
#相同,则两项合并
if L1==L2:
#合并,生成k+1项集
retList.append(Lk[i] | Lk[j])
#返回最终k+1项集
return retList
#输入:数据集、最小支持度
def apriori(dataSet, minSupport = 0.5):
#生成1-项集
C1 = createC1(dataSet)
#对数据集进行映射至D,去掉重复的数据记录
D = map(set, dataSet)
#过滤最小支持度,得到频繁1-项集L1以及每项的支持度
L1, supportData = scanD(D, C1, minSupport)
#将L1放入列表L中,L会包含L1、L2、L3
#L存放所有的频繁项集
#由L1产生L2,L2产生L3
L = [L1]
#Python中使用下标0表示第一个元素,k=2表示从1-项集产生2-项候选集
#L0为频繁1-项集
k = 2
#根据L1寻找L2、L3通过while循环来完成,
#它创建包含更大项集的更大列表,直到下一个更大的项集为空。
#候选集物品组合长度超过原数据集最大的物品记录长度
#如原始数据集物品记录最大长度为4,那么候选集最多为4-项集
while (len(L[k-2]) > 0):
#由频繁k-1项集,产生k项候选集
#(连接步)
Ck = aprioriGen(L[k-2], k)
#由k项候选集,经最小支持度筛选,生成频繁k项集
#(剪枝步)
Lk, supK = scanD(D, Ck, minSupport)
#更新支持度字典,用于加入新的支持度
supportData.update(supK)
#将新的频繁k项集加入已有频繁项集的列表中
L.append(Lk)
#k加1,用于产生下一项集
k += 1
#前面找不到支持的项,构建出更高的频繁项集Lk时,算法停止。
#返回所有频繁项集及支持度列表
return L, supportData
#输入:apriori函数生成频繁项集列表L
#支持度列表、最小置信度
#输出:包含可信度规则的列表
#作用:产生关联规则
def generateRules(L, supportData, minConf=0.7):
#置信度规则列表,最后返回
bigRuleList = []
#L0为频繁1-项集
#无法从1-项集中构建关联规则,所以从2-项集开始。
#遍历L中的每一个频繁项集。
for i in range(1, len(L)):
#遍历频繁项集的每一项
for freqSet in L[i]:
#对每个频繁项集构建只包含单个元素集合的列表H1。
#如{1,2,3,4},H1为[{1},{2},{3},{4}]
#关联规则从单个项开始逐步增加,
#1,2,3——>4 1,2——>3,4 1——>2,3,4
H1 = [frozenset([item]) for item in freqSet]
#频繁项集中元素大于3个及以上,
#规则右部需要不断合并作为整体,利用最小置信度进行过滤
if (i > 1):
#项集中元素超过2个,做合并。
rulesFromConseq(freqSet, H1, supportData, bigRuleList, minConf)
else:
#频繁项集只有2个元素时,直接计算置信度进行过滤
calcConf(freqSet, H1, supportData, bigRuleList, minConf)
#返回最后满足最小置信的规则列表
return bigRuleList
#输入:freqSet频繁项集、H关联规则右部的元素列表且为单个元素项,
#默认最小支持度0.7
#置信度计算,使用集合减操作。
#作用:计算规则的可信度以及找到满足最小可信度要求的规则
#注意:把1,2,3—>4看做1,2,3为一个整体,4为一个整体,
#即规则的前件为一个整体,后件为一个整体。
#上述规则就只有两部分,箭头前的项 与 箭头后的项
#产生后件为1项关联规则,频繁项集{1,2,3,4}
#H为[[1],[2],[3],[4]]。
#H中元素依次做关联规则的后项
#1,2,3——>4
#1,2,4——>3
#1,3,4——>2
#2,3,4——>1
#产生后件为2项关联规则,频繁项集{1,2,3,4}
#H为H = [[3,4],[2,4],[2,3],[1,4],[1,3],[1,2]]。
#H中元素依次做关联规则的后项
#1,2——>3,4
#1,3——>2,4
#1,4——>2,3
#2,3——>1,4
#2,4——>1,3
#3,4——>1,2
def calcConf(freqSet, H, supportData, brl, minConf=0.7):
#满足最小可信度要求的规则列表后项
prunedH = []
#遍历H中的所有项,用作关联规则的后项
for conseq in H:
#置信度计算,使用集合减操作
conf = supportData[freqSet]/supportData[freqSet-conseq]
#置信度大于最小置信度
if conf >= minConf:
#输出关联规则前件freqSet-conseq
#关联规则后件conseq
print freqSet-conseq,'-->',conseq,'conf:',conf
#保存满足条件的关联规则
#保存关联规则前件,后件,以及置信度
brl.append((freqSet-conseq, conseq, conf))
#满足最小可信度要求的规则列表后项
prunedH.append(conseq)
#返回满足条件的后项
return prunedH
#输入:频繁项集、关联规则右部的元素列表H
#supportData支持度列表
#brl需要填充的规则列表,最后返回
#H为关联关联规则右部的元素,如1,2—>3,4
#频繁项集为{1,2,3,4},H为3,4
#因此,先计算H大小m(此处m=2)
def rulesFromConseq(freqSet, H, supportData, brl, minConf=0.7):
#规则右边的元素个数
m = len(H[0])
#{1,2,3}产生规则1——>2,3
#规则右边的元素H 最多 比频繁项集freqSet元素少1,
#超过该条件无法产生关联规则
#如果H元素较少,那么可以对H元素进行组合。
#产生规则右边新的组合H,
#直到达到H元素 最多
#若{1,2,3,4},m=2时。可产生如下规则
#1,2——>3,4
#1,3——>2,4
#1,4——>2,3
#2,3——>1,4
#2,4——>1,3
#3,4——>1,2
if (len(freqSet) > (m + 1)):
#使用aprioriGen()函数对H元素进行无重复组合,
#用于产生更多的候选规则,结果存储在Hmp1中。
#Hmp1=[[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
Hmp1 = aprioriGen(H, m+1)
#利用最小置信度对这些候选规则进行过滤
Hmp1 = calcConf(freqSet, Hmp1, supportData, brl, minConf)
#过滤后Hmp1=[[1,2,3],[1,2,4]]
#如果不止一条规则满足要求,
#继续使用Hmp1调用函数rulesFromConseq()
#判断是否可以进一步组合这些规则。
if (len(Hmp1) > 1):
rulesFromConseq(freqSet, Hmp1, supportData, brl, minConf)
if __name__ == "__main__":
# dataSet=loadDataSet()
# L, supportData = apriori(dataSet, minSupport=0.5)
# rules=generateRules(L, supportData, minConf=0.5)
# print rules
# 毒蘑菇 第一列特征值为2 根据最小支持度过滤 找出不能吃的毒蘑菇
mushDatSet = [line.split() for line in open('mushroom.dat').readlines()]
L, supportData = apriori(mushDatSet, minSupport=0.3)
for item in L[3]:
if item.intersection('2'):
print item
|
884b6f463879e5011f8e9dc2abdc90d9e44c06ed
|
[
"Python"
] | 1
|
Python
|
bbaiggey/PythonAlgorithm
|
88ef0f7b4237393069236605135f3f37c6de35c9
|
24ba33c29f91fb0e781f6c3c23a8f4282246e8bc
|
refs/heads/master
|
<file_sep>import copy
from collections import deque
import sys
import re
keywords = ["room", "booths","dimension","target","position",
"horizon"]
#size
maxMoves = 0
numberOfBooths = 0
positions = {}
target = {}
dimensions = {}
roomSize = []
def nonblank_lines(f):
for l in f:
line = l.rstrip()
line = l.lstrip()
for key in keywords:
if (re.match(key+r'\(\d+(, \d+)*\)\.',line)):
parse_line(line, key)
def parse_line(op, key):
global maxMoves
global numberOfBooths
global positions
global roomSize
global target
global dimensions
values = re.findall('\d+', op)
if key is keywords[0]:
roomSize = values
elif key is keywords[1]:
numberOfBooths = values.pop()
elif key is keywords[2]:
dimensions.update({values.pop(0):tuple(values)})
elif key is keywords[3]:
target.update({values.pop(0):tuple(values)})
elif key is keywords[4]:
positions.update({values.pop(0):tuple(values)})
elif key is keywords[5]:
maxMoves = values.pop()
def bfs(initialObjects,dimensions,roomSize,maxSteps,startingMatrix,answerMatrix):
initialSteps = 0
alreadyExplored = []
queue = deque([(startingMatrix,initialObjects,initialSteps)]) #create queue
while len(queue)>0: #make sure there are nodes to check left
node = queue.popleft() #grab the first node
currentMatrix = node[0]
plainObjects = node[1]
# print("plainObjects: ", node)
numberOfSteps = node[2]
# print("trying:",currentMatrix,"\nSteps: ",numberOfSteps)
#we already saw this one
if currentMatrix in alreadyExplored:
continue
#check if its the answer
if are_equal(currentMatrix,answerMatrix):
return "moves("+str(numberOfSteps)+")."
if maxSteps < numberOfSteps:
return "more than "+str(maxSteps) +" steps required, quitting"
#add it to already explored
alreadyExplored.append(currentMatrix)
#if not an answer we generate all posible moves from this graph
for key, value in plainObjects.items():
moveUp = move_up(roomSize,key,value,plainObjects,dimensions,currentMatrix,numberOfSteps)
moveDown = move_down(roomSize,key,value,plainObjects,dimensions,currentMatrix,numberOfSteps)
moveRight = move_right(roomSize,key,value,plainObjects,dimensions,currentMatrix,numberOfSteps)
moveLeft = move_left(roomSize,key,value,plainObjects,dimensions,currentMatrix,numberOfSteps)
if moveUp:
queue.append(moveUp)
if moveDown:
queue.append(moveDown)
if moveRight:
queue.append(moveRight)
if moveLeft:
queue.append(moveLeft)
print("No answer found")
'''The initial objects should contain a matrix, dimensions'''
def move_up(roomSize,key,objectA,objects,dimensions,matrix,steps):
'''If a matrix is found it will return the updated information
like input else it will return an empty list'''
temp1 = int(objectA[1])+1
# print("in up key:",key)
#new tuple
# print("before",objectA)
# objectA = {key: (objectA[0],str(temp1))}
tempObjects = copy.deepcopy(objects)
tempCopy = {key: (objectA[0],str(temp1))}
tempObjects.update(tempCopy)
# print("after",objectA)
if temp1 >= int(roomSize[1]):
# print("out of bounds")
return []
newMatrix = create_matrix_with_new_point(roomSize, matrix, dimensions, tempCopy)
# print("NEW MATRIX UP: ", newMatrix)
#if the matrix is empty this means sometihng went wrong, return empty
if newMatrix:
# print("Can move up")
return [newMatrix,tempObjects,steps+1]
else:
# print("TEST")
return []
def move_down(roomSize,key,objectA,objects,dimensions,matrix,steps):
'''If a matrix is found it will return the updated information
like input else it will return an empty list'''
temp1 = int(objectA[1])-1
# print("in down key:",key)
#new tuple
# print("before",objectA)
tempObjects = copy.deepcopy(objects)
tempCopy = {key: (objectA[0],str(temp1))}
tempObjects.update(tempCopy)
# print("after",objectA)
if temp1 < 0:
return []
newMatrix = create_matrix_with_new_point(roomSize, matrix, dimensions, tempCopy)
#if the matrix is empty this means sometihng went wrong, return empty
if newMatrix:
# print("Can move down")
return [newMatrix,tempObjects,steps+1]
else:
return []
def move_left(roomSize,key,objectA,objects,dimensions,matrix,steps):
'''If a matrix is found it will return the updated information
like input else it will return an empty list'''
temp1 = int(objectA[0])-1
# print("in left key:",key)
#new tuple
# print("before",objectA)
tempObjects = copy.deepcopy(objects)
tempCopy = {key: (str(temp1),objectA[1])}
tempObjects.update(tempCopy)
# print("after",objectA)
if temp1 < 0:
return []
newMatrix = create_matrix_with_new_point(roomSize, matrix, dimensions, tempCopy)
#if the matrix is empty this means sometihng went wrong, return empty
if newMatrix:
# print("Can move left")
return [newMatrix,tempObjects,steps+1]
else:
return []
def move_right(roomSize,key,objectA,objects,dimensions,matrix,steps):
'''If a matrix is found it will return the updated information
like input else it will return an empty list'''
temp1 = int(objectA[0])+1
# print("in right key:",key)
#new tuple
# print("before",objectA)
tempObjects = copy.deepcopy(objects)
tempCopy = {key: (str(temp1),objectA[1])}
tempObjects.update(tempCopy)
# print("after",objectA)
if temp1 >= int(roomSize[0]):
return []
newMatrix = create_matrix_with_new_point(roomSize, matrix, dimensions, tempCopy)
#if the matrix is empty this means sometihng went wrong, return empty
if newMatrix:
# print("Can move right")
return [newMatrix,tempObjects,steps+1]
else:
return []
def are_equal(matrixOne, matrixTwo):
return matrixOne == matrixTwo
def print_matrix(matrix):
for line in matrix:
print(*line)
def create_matrix_with_new_point(roomSize,createdMatrix, dimensions,target):
keyTarget, valueTarget = target.popitem()
createdMatrix = [[subelt.replace(keyTarget,'0') for subelt in individualList] for individualList in createdMatrix]
for key, value in dimensions.items():
if key is keyTarget:
for i in range(int(dimensions.get(key)[0])):
if (int(valueTarget[0])+i) >= int(roomSize[0]) or (int(valueTarget[0])+i) < 0:
return []
for j in range(int(dimensions.get(key)[1])):
if (int(valueTarget[1])+j) >= int(roomSize[1]) or (int(valueTarget[1])+i) < 0 or createdMatrix[int(valueTarget[0])+i][int(valueTarget[1])+j] != '0':
return []
createdMatrix[int(valueTarget[0])+i][int(valueTarget[1])+j] = key
return createdMatrix
def create_matrix(width, height,objects,dimensions):
matrix = []
row = []
for i in range(height):
for j in range(width):
row.append('0')
matrix.append(row)
row = []
for key, value in objects.items():
for i in range(int(dimensions.get(key)[0])):
for j in range(int(dimensions.get(key)[1])):
matrix[int(value[0])+i][int(value[1])+j] = key
return matrix
def print_current_values():
print ("maxMoves: ", maxMoves, "\nnumberOfBooths:",numberOfBooths
,"\npositions:",positions,"\ntarget:",target,"\ndimensions:",dimensions
,"\nroomSize:",roomSize)
def main():
f = open(sys.argv[1], 'r')
nonblank_lines(f)
matrix = create_matrix(int(roomSize[0]),int(roomSize[0]),positions,dimensions)
answerMatrix = create_matrix_with_new_point(roomSize, matrix, dimensions,target)
print(bfs(positions,dimensions,roomSize,int(maxMoves),matrix,answerMatrix))
f.close()
main()<file_sep># <NAME> 107927299
#
# WolfieScript HW6
# -----------------------------------------------------------------------------
#Helper class
class Node:
def __init__(self):
print("init node")
def evaluate(self):
return 0
def execute(self):
return 0
#Can be real or integers
class NumberNode(Node):
def __init__(self, v):
self.value = v
def evaluate(self):
return self.value
#For a string type, does not have ''
class StringNode(Node):
def __init__(self, v):
self.value = v
def evaluate(self):
return self.value
#for a node of type list
class ListNode(Node):
def __init__(self, v):
self.value = v
def evaluate(self):
return self.value
class NameNode(Node):
def __init__(self, v):
self.value = v
def evaluate(self):
if self.value in names:
return names[self.value]
#check with the main stack (static scope)
elif len(stack) > 0:
# print("checking the main stack")
if self.value in stack[0]:
return stack[0][self.value]
else:
raise SemanticError()
else:
raise SemanticError()
#used to print for later
class PrintNode(Node):
def __init__(self, v):
self.value = v
def execute(self):
self.value = self.value.evaluate()
print(self.value)
#evaluates operations based on type
class BopNode(Node):
def __init__(self, op, v1, v2):
self.v1 = v1
self.v2 = v2
self.op = op
def evaluate(self):
operation = self.op
value1 = self.v1.evaluate()
value2 = self.v2.evaluate()
if (operation == '+'):
if((isinstance(value1, str) and isinstance(value2, str))
or (isinstance(value1, ( int, float )) and isinstance(value2, ( int, float )))
or (isinstance(value1, list) and isinstance(value2, list))):
return value1 + value2
else:
raise SemanticError()
elif (isinstance(value1, ( int, float )) and isinstance(value2, ( int, float ))):
if (operation == '-'):
return value1 - value2
elif(operation=='//'):
return value1 // value2
elif(operation =='**'):
return value1 ** value2
elif(operation == '%'):
return value1 % value2
elif (operation == '*'):
return value1 * value2
elif (operation == '/'):
if(value2 == 0):
raise SemanticError()
return value1 / value2
else:
raise SemanticError()
#for conditions primitive
class ConditionalNode(Node):
def __init__(self, op, v1, v2):
self.v1 = v1
self.v2 = v2
self.op = op
def evaluate(self):
operation = self.op
value1 = self.v1.evaluate()
value2 = self.v2.evaluate()
if (isinstance(value1, ( int, float )) and isinstance(value2, ( int, float ))):
if operation == '<':
if value1 < value2:
return 1
else:
return 0
elif operation == '<=':
if value1 <= value2:
return 1
else:
return 0
elif operation == '==':
if value1 == value2:
return 1
else:
return 0
elif operation == '<>':
if value1 != value2:
return 1
else:
return 0
elif operation == '>':
if value1 > value2:
return 1
else:
return 0
elif operation == '>=':
if value1 >= value2:
return 1
else:
return 0
else:
raise SemanticError()
else:
raise SemanticError()
#This is for boolean more recent
class BooleanNode(Node):
def __init__(self, op, v1, v2):
self.v1 = v1
self.v2 = v2
self.op = op
def evaluate(self):
operation = self.op
value1 = self.v1.evaluate()
value2 = self.v2.evaluate()
if (isinstance(value1, int) and isinstance(value2, int)):
if operation == 'and':
if((value1 and value2) == 0):
return 0
else:
return 1
elif operation == 'or':
if((value1 or value2) == 0):
return 0
else:
return 1
else:
raise SemanticError()
elif(isinstance(value2, (str,list))):
if(isinstance(value1,str) or isinstance(value2,list)):
if operation == 'in':
if((value1 in value2)):
return 1
else:
return 0
else:
raise SemanticError()
else:
raise SemanticError()
else:
raise SemanticError()
#just for the special case of not
class BooleanNotNode(Node):
def __init__(self, v):
self.v = v
def evaluate(self):
value = self.v.evaluate()
if (isinstance(value, int)):
if((not value) == 0):
return 0
else:
return 1
else:
raise SemanticError()
class AssignmentNode(Node):
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2
def execute(self):
v1 = self.v1
v2 = self.v2.evaluate()
# if isinstance(self.v2, FunExpNode):
# v2 = self.v2.execute()
# else:
# v2 = self.v2.evaluate()
# print("ASSIGMENT NODE", v1, v2)
#check if what we got is a name node, get its value
if isinstance(v1,NameNode):
names[v1.value] = v2
# print("ASSIGNED A VARIABLE",v1.value,names)
#check if its an indexnode with a name node, then we assign it
elif isinstance(v1,IndexNode):
if isinstance(v1.v1,NameNode):
index = v1.v2.evaluate()
variable = v1.v1.value
item = names[variable]
#cannot assign to string
if isinstance(item, str):
raise SemanticError()
#check for index out of bounds
if(len(item) > index):
names[variable][index] = v2
else:
raise SemanticError()
else:
raise SemanticError()
else:
# print("its something else")
raise SemanticError()
class WhileNode(Node):
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2
def execute(self):
import copy
test = copy.deepcopy(self.v2)
while(self.v1.evaluate() == 1):
test.execute()
test = copy.deepcopy(self.v2)
# #evaluates based on index given
class IndexNode(Node):
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2
def evaluate(self):
v1 = self.v1.evaluate()
v2 = self.v2.evaluate()
if isinstance(v1, (str,list)) and isinstance(v2, int):
return v1[v2]
else:
raise SemanticError()
class PrintNode(Node):
def __init__(self, v):
self.value = v
def execute(self):
self.value = self.value.evaluate()
print(self.value)
class OneStatementNode(Node):
def __init__(self, v):
self.v1 = v
def execute(self):
return self.v1.execute()
class MoreStatementNode(Node):
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2
def execute(self):
#one statement
v1 = self.v1.execute()
#multiple statements
v2 = self.v2.execute()
# we need to have a value, else no need to return
if v1 != None:
return v1
elif v2 != None:
return v2
class IfNode(Node):
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2
self.els = None
def execute(self):
if(self.v1.evaluate() == 1):
return self.v2.execute()
elif(self.els != None):
return self.els.execute()
class ElseNode(Node):
def __init__(self, v):
self.v = v
def execute(self):
return self.v.execute()
class BlockNode(Node):
def __init__(self, v):
self.v = v
def execute(self):
# print("executing block ")
return self.v.execute()
class FunctionNode(Node):
def __init__(self, v, arguments, block):
self.v = v
self.arguments = arguments
self.block = block
#add to current functions
if self.v.value in functions:
# print("already have it",self.v.value)
raise SemanticError()
else:
# print("adding to list of functions",self.v.value)
functions[self.v.value] = self
def execute(self, arguments):
global names
#push the previous frame
stack.append(names)
#this is in case we do have arguments passed
if(self.arguments != None and arguments != None):
#check that the size of the function and the arguments obtianed are the same
if len(arguments) != len(self.arguments):
# print("need more arguments or less")
raise SemanticError()
#create the new dictionary with values if needed of current one
temp = {}
for i in range(len(self.arguments)):
temp[self.arguments[i].value] = arguments[i].evaluate()
names = temp
if((self.arguments != None and arguments == None) or (self.arguments == None and arguments != None)):
raise SemanticError()
result = self.block.execute()
names = stack.pop()
return result
#this is when it is called
class FunExpNode(Node):
def __init__(self, v, arguments):
self.v = v #name
self.arguments = arguments
def evaluate(self):
function = functions.get(self.v.value)
r = function.execute(self.arguments)
# print("THIS IS R", r)
if r != None:
return r
# print(r)
#for then they use return
class ReturnNode(Node):
def __init__(self, v):
self.v = v #what to return
def execute(self):
# print("executing return",self.v.evaluate())
return self.v.evaluate()
#for those that we dont want to do anything
class EmptyNode(Node):
def __init__(self):
'''Empty'''
def evaluate(self):
pass
def execute(self):
pass
#main class for exceptions and errors
class Error(Exception):
'''Base class for exceptions in this module.'''
pass
#raised for different exeptions
class SemanticError(Error):
'''Exception raised for errors in the input.'''
pass
import ply.lex as lex
#LEX RULES
reserved = {
'in' : 'IN',
'or' : 'OR',
'not' : 'NOT',
'and' : 'AND',
'print': 'PRINT',
'if' : 'IF',
'else' : 'ELSE',
'while' : "WHILE",
'return' : "RETURN"
}
tokens = ['INTEGER','REAL','STRING','LPAREN','RPAREN','LBRACKET',
'RBRACKET','TIMES','DIVIDE','MODULO','EXPONENT','FLOORDIVISION','PLUS',
'MINUS','LESSTHAN','LESSTHANEQUAL','EQUAL','NOTEQUAL','GREATERTHAN',
'GREATERTHANEQUAL','COMMA','SEMICOLON','RCURLY','LCURLY','ASSIGMENT','ID']+ list(reserved.values())
# Tokens
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_LBRACKET = r'\['
t_RBRACKET = r'\]'
t_LCURLY = r'\{'
t_RCURLY = r'\}'
t_PLUS = r'\+'
t_MINUS = r'-'
t_EXPONENT = r'\*\*'
t_TIMES = r'\*'
t_FLOORDIVISION = r'//'
t_DIVIDE = r'/'
t_MODULO = r'%'
t_LESSTHANEQUAL = r'<='
t_LESSTHAN = r'<'
t_EQUAL = r'=='
t_ASSIGMENT = r'='
t_NOTEQUAL = r'<>'
t_GREATERTHANEQUAL = r'>='
t_GREATERTHAN = r'>'
t_COMMA = r','
t_SEMICOLON = r';'
def t_REAL(t):
r'(\d+\.\d*|\d*\.\d+)'
t.value = NumberNode(float(t.value))
return t
def t_INTEGER(t):
r'\d+'
t.value = NumberNode(int(t.value))
return t
def t_STRING(t):
r'\"(.*?)\"'
t.value = StringNode(str(t.value[1:-1]))
return t
# A string containing ignored characters (spaces and tabs)
t_ignore = ' \t'
# Define a rule so we can track line numbers
def t_newline(t):
r'\n+'
t.lexer.lineno += len(t.value)
#checks if the words is reserved
def t_ID(t):
r'[a-zA-Z_][a-zA-Z_0-9]*'
t.type = reserved.get(t.value,'ID') # Check for reserved words
if t.type == 'ID':
t.value = NameNode(t.value)
return t
# Error handling rule
def t_error(t):
t.lexer.skip(1)
raise SyntaxError
# data = '''
# 3 + 4 * 10
# + -20 *2 + 9.123 in not \\ ** * <> < >= <= print and "testing123jasdahjsd123h12j3bhj1v23ghabdhh12bh1"
# '''
# Build the lexer
lexer = lex.lex()
#for testing of token creation
# lexer.input(data)
# # # Tokenize
# for tok in lexer:
# print(tok)
# Parsing rules
#precedence from lowest to highest , those in the same line have equal precedence
precedence = (
('left','OR'),
('left','AND'),
('left','NOT'),
('left','LESSTHAN','LESSTHANEQUAL','EQUAL','NOTEQUAL','GREATERTHAN','GREATERTHANEQUAL'),
('left','IN'),
('left','PLUS','MINUS'),
('left','FLOORDIVISION'),
('left','EXPONENT'),
('left','MODULO'),
('left','TIMES','DIVIDE')
)
# dictionary of names
names = {}
functions = {}
stack = []
def p_program_func(t):
'''program : functions block'''
t[0] = t[2]
def p_program_block(t):
'''program : block'''
t[0] = t[1]
def p_functions(t):
'''functions : functions function'''
# t[0] = t[2]
def p_functions_function(t):
'''functions : function'''
t[0] = t[1]
def p_functions_one(t):
'''function : ID LPAREN IDlist RPAREN block'''
# print("here")
t[0] = FunctionNode(t[1],t[3],t[5])
def p_functions_noargs(t):
'''function : ID LPAREN RPAREN block'''
t[0] = FunctionNode(t[1],None,t[4])
#######################BLOCK##############################################
def p_block(t):
'''block : LCURLY statements RCURLY'''
t[0] = BlockNode(t[2])
def p_block_empty(t):
'''block : LCURLY RCURLY'''
t[0] = EmptyNode()
#######################STATEMENTS##############################################
def p_statements_more(t):
'''statements : statement statements'''
t[0] = MoreStatementNode(t[1], t[2])
def p_statements_one(t):
'''statements : statement'''
t[0] = OneStatementNode(t[1])
def p_statement_expr(t):
'''statement : printsmt
| ifstatement
| whilestatement
| elsestatement
| block
| returnstatement'''
t[0] = OneStatementNode(t[1])
def p_statement_assign(t):
'''statement : expression ASSIGMENT expression SEMICOLON'''
t[0] = AssignmentNode(t[1],t[3])
def p_statement_return(t):
'''returnstatement : RETURN expression SEMICOLON'''
t[0] = ReturnNode(t[2])
def p_bodystatement_onestatement(t):
'''bodystatement : statement'''
t[0] = t[1]
def p_printsmt_smt(t):
'''printsmt : PRINT LPAREN expression RPAREN SEMICOLON'''
t[0] = PrintNode(t[3])
def p_whilestatement_while(t):
'''whilestatement : WHILE LPAREN expression RPAREN bodystatement'''
t[0] = WhileNode(t[3], t[5])
def p_ifstatement_if(t):
'''ifstatement : IF LPAREN expression RPAREN bodystatement'''
t[0] = IfNode(t[3],t[5])
def p_elsestatement_ifelse(t):
'''elsestatement : ifstatement ELSE bodystatement'''
t[1].els = ElseNode(t[3])
t[0] = t[1]
#######################OPERATORS##############################################
def p_expression_binop(t):
'''expression : expression PLUS expression
| expression MINUS expression
| expression FLOORDIVISION expression
| expression EXPONENT expression
| expression MODULO expression
| expression TIMES expression
| expression DIVIDE expression'''
t[0] = BopNode(t[2], t[1], t[3])
def p_expression_conditional(t):
'''expression : expression LESSTHAN expression
| expression LESSTHANEQUAL expression
| expression EQUAL expression
| expression NOTEQUAL expression
| expression GREATERTHAN expression
| expression GREATERTHANEQUAL expression'''
t[0] = ConditionalNode(t[2], t[1], t[3])
def p_expression_booleans(t):
'''expression : expression OR expression
| expression AND expression
| expression IN expression'''
t[0] = BooleanNode(t[2],t[1], t[3])
def p_expression_not(t):
'''expression : NOT expression'''
t[0] = BooleanNotNode(t[2])
def p_expression_plusnum(t):
'''expression : PLUS expression'''
t[0] = t[2]
#######################INDEX##############################################
def p_index_list(t):
'''index : list bracket'''
t[0] = IndexNode(t[1],t[2])
def p_index_string(t):
'''index : STRING bracket'''
t[0] = IndexNode(t[1],t[2])
def p_index_id(t):
'''index : ID bracket'''
t[0] = IndexNode(t[1],t[2])
def p_index_expression(t):
'''index : expression bracket'''
t[0] = IndexNode(t[1],t[2])
def p_index_indeces(t):
'''index : indices'''
t[0] = t[1]
def p_indices_indices(t):
'''indices : index bracket'''
t[0] = IndexNode(t[1], t[2])
def p_bracket(t):
'''bracket : LBRACKET expression RBRACKET'''
t[0] = t[2]
#######################LISTS##############################################
def p_list_empty(t):
'''list : LBRACKET RBRACKET'''
t[0] = ListNode([])
def p_list_expr(t):
'''list : bracket'''
t[0] = ListNode([t[2]])
def p_list_bracket(t):
'''list : LBRACKET commalist RBRACKET'''
t[0] = ListNode(t[2])
def p_commalist_list(t):
'''commalist : expression'''
t[0] = [t[1].evaluate()]
def p_commalist_recursive(t):
'''commalist : commalist COMMA expression'''
t[0] = [t[3].evaluate()] + t[1]
#######################LISTS EXPRESSIONS##############################################
def p_expressionslist(t):
'''expressionlist : expressionlist COMMA expression'''
t[0] = [t[3]] + t[1]
def p_expressionslist_expression(t):
'''expressionlist : expression'''
t[0] = [t[1]]
#######################LISTS ID##############################################
def p_idlist(t):
'''IDlist : IDlist COMMA ID'''
t[0] = [t[3]] + t[1]
def p_idlist_id(t):
'''IDlist : ID'''
t[0] = [t[1]]
#######################TERMINALS##############################################
def p_expression_factor(t):
'''expression : factor'''
t[0] = t[1]
def p_factor_paren(t):
'''factor : LPAREN expression RPAREN'''
t[0] = t[2]
def p_funExp(t):
'''funExp : ID LPAREN expressionlist RPAREN'''
# print("inside funExp")
t[0] = FunExpNode(t[1],t[3])
def p_funExp_emptyargs(t):
'''funExp : ID LPAREN RPAREN'''
# print("inside funExp")
t[0] = FunExpNode(t[1],None)
def p_factor_type(t):
'''factor : INTEGER
| REAL
| STRING
| ID
| list
| index
| funExp'''
t[0] = t[1]
def p_error(t):
# print("throwing error",t)
raise SyntaxError()
import ply.yacc as yacc
import sys
yacc.yacc()
r = open(sys.argv[1], "r")
code = ""
for line in r:
code += line
try:
lex.input(code)
ast = yacc.parse(code)
ast.execute()
except IOError:
print("Error opening the file")
except SyntaxError:
print("SYNTAX ERROR")
except SemanticError:
print("SEMANTIC ERROR")
<file_sep>import sys
import re
import itertools
import copy
from collections import OrderedDict
keywords = ["people", "locations","preferences","location","prefer"]
people = 0
locations = 0
preferences = 0
location = {}
prefer = {}
def nonblank_lines(f):
for l in f:
line = l.rstrip()
line = l.lstrip()
for key in keywords:
if (re.match(key+r'\(\d+(, \d+)*\)\.',line)):
parse_line(line, key)
def parse_line(op, key):
global people
global locations
global preferences
global location
global prefer
values = re.findall('\d+', op)
if key is keywords[0]:
people = int(values.pop(0))
elif key is keywords[1]:
preferences = int(values.pop(0))
elif key is keywords[2]:
preferences = int(values.pop(0))
elif key is keywords[3]:
if int(values[0]) in location:
location.get(int(values.pop(0))).extend(list(map(int, values)))
else:
location.update({int(values.pop(0)):list(map(int, values))})
elif key is keywords[4]:
if int(values[0]) in prefer:
prefer.get(int(values.pop(0))).extend(list(map(int, values)))
else:
prefer.update({int(values.pop(0)):list(map(int, values))})
def print_current_values():
print ("people: ", people, "\nlocations:",locations
,"\npreferences:",preferences,"\nlocation:",location,"\nprefer",prefer)
def min_max_for_time(location):
times = []
for key, value in location.items():
times.extend(value[1:])
return [min(times),max(times)]
def get_satisfaction(prefer, location, permutation, current_time):
least_satisfied = 123123123
permutationSize = len(permutation)
# print("permutation:",permutation)
#get the locations we can go to
for perm in permutation[:]:
tempLoc = location.get(perm)
if check_if_it_is_within_time_frame(perm,tempLoc, current_time):
permutation.remove(perm)
#we have our locations now we can see the satisfaction of each person
valuesSatisfaction = []
sumValues = 0
for key, value in prefer.items():
temp = get_satisfaction_of_person(value[:], permutation[:], permutationSize)
valuesSatisfaction.append(temp)
sumValues +=temp
if least_satisfied > temp:
least_satisfied = temp
# print(valuesSatisfaction)
# print("LEAST SATISFIED",least_satisfied, "Sum:",sumValues)
return [least_satisfied,sumValues,valuesSatisfaction]
def get_satisfaction_of_person(personPlaces, locationsThatWereSelected,permutationSize):
satisfaction = 0
# print("Location selected:",locationsThatWereSelected)
for loc in personPlaces[:]:
# print("locations",loc)
if loc in locationsThatWereSelected:
# print("YES",satisfaction)
personPlaces.remove(loc)
satisfaction+=1
# print(personPlaces)
if personPlaces:
# print("has something satisfaction",satisfaction)
return satisfaction
else:
# print("has all",permutationSize)
return permutationSize
def check_if_it_is_within_time_frame(perm,tempLoc, current_time):
# print("perm",perm,"temp: ",tempLoc,"current_time:" ,current_time)
current_hour = current_time[0]
eventStartTime = tempLoc[1]
if current_hour < eventStartTime:
current_hour = eventStartTime
current_time[0] = eventStartTime
#we dont have time for anything else, remove it from list
if current_time[0] == current_time[1]:
# print("this")
return True
time_within_timeframe = (tempLoc[2] - current_hour)
# print("time_within_timeframe",time_within_timeframe)
if time_within_timeframe >= 0:
time_it_takes = tempLoc[0]
if (time_within_timeframe - time_it_takes) >=0:
# print("it fits updating time",time_it_takes,current_time)
current_time[0] = current_time[0] + time_it_takes
return False
return True
def main():
f = open(sys.argv[1], 'r')
nonblank_lines(f)
# print_current_values()
listOfPlaces = []
for key, value in prefer.items():
listOfPlaces.extend(value)
minValue = min(listOfPlaces)
maxValue = max(listOfPlaces)
permutations = list(itertools.permutations(range(minValue, maxValue+1),maxValue))
#obtain min and max for time
times = min_max_for_time(location)
# get_satisfaction(prefer, place, list(permutations[0]), times)
bestSatisfaction = [0,0,[0,0]]
least_satisfied = maxValue
for perm in permutations:
temp = get_satisfaction(prefer, location, list(perm) , times[:])
# print(temp)
if temp[0] > bestSatisfaction[0]:
# print("least HERE", bestSatisfaction,least_satisfied)
bestSatisfaction = temp
least_satisfied = temp
# print(bestSatisfaction)
print("satisfaction("+str(bestSatisfaction[0])+").")
f.close()
main()<file_sep>import sys
import re
keywords = ["dishes", "hot","separation","table_width","dish_width",
"demand"]
separation = 0
numberOfDishes = 0
firstKindOfDisheshot = 0
table_width = 0
dish_width = {}
demand = {}
def nonblank_lines(f):
for l in f:
line = l.rstrip()
line = l.lstrip()
for key in keywords:
if (re.match(key+r'\(\d+(, \d+)*\)\.',line)):
parse_line(line, key)
def parse_line(op, key):
global separation
global numberOfDishes
global firstKindOfDisheshot
global table_width
global dish_width
global demand
values = re.findall('\d+', op)
if key is keywords[0]:
numberOfDishes = int(values.pop(0))
elif key is keywords[1]:
firstKindOfDisheshot = int(values.pop(0))
elif key is keywords[2]:
separation = int(values.pop(0))
elif key is keywords[3]:
table_width = int(values.pop(0))
elif key is keywords[4]:
dish_width.update({int(values.pop(0)):int(values.pop(0))})
elif key is keywords[5]:
demand.update({int(values.pop(0)):int(values.pop(0))})
def print_current_values():
print ("dishes: ", numberOfDishes, "\nhot:",firstKindOfDisheshot
,"\nseparation:",separation,"\ntable_width:",table_width,"\ndish_width:",dish_width
,"\ndemand:",demand)
def getNumberOfTables(sortedDishes, tableSize,separation):
tableNumber = 0
while(sortedDishes):
tableNumber+=1
tempTableSize = tableSize
biggestItem = sortedDishes.pop(len(sortedDishes)-1)
tempTableSize -= biggestItem[1]
currentType = biggestItem[0]
#second take
# coldList = [cold for cold in sortedDishes if cold[0] is "cold"]
# hotList = [hot for hot in sortedDishes if hot[0] is "hot"]
# print("Cold List: ", coldList)
# print("Hot list: ", hotList)
# if currentType is "hot":
# for hot in hotList:
while(True):
done = False
for dish in sortedDishes[:]:
#sametype lets try adding this one
if dish[0] is currentType:
if (tempTableSize-dish[1]) > 0:
#pop this element
sortedDishes.remove(dish)
#tempTableSize new size
tempTableSize -= dish[1]
continue
elif (tempTableSize-dish[1]) == 0:
sortedDishes.remove(dish)
done = True
break
#no element of same type found
if done:
break
elif tempTableSize > 0:
#we still got space check with the smallest one now
if not sortedDishes:
break
tempElement = sortedDishes[0]
tempTableSize2 = tempTableSize - (tempElement[1]+separation)
if tempTableSize2 >= 0:
sortedDishes.pop(0)
tempTableSize -= tempTableSize2
elif tempTableSize2 < 0:
break
if tempTableSize == 0:
break
return tableNumber
def main():
f = open(sys.argv[1], 'r')
nonblank_lines(f)
#put them in a list
dishesHotLeft = firstKindOfDisheshot
typeOfDish = "hot"
dishesDict = []#has
for key, value in demand.items():
if dishesHotLeft <= 0:
typeOfDish = "cold"
for i in range(value):
dishesDict.append((typeOfDish,dish_width.get(key)))
dishesHotLeft-=1
# #going to the next type
#sort them by length
dishesDict.sort(key=lambda tup: tup[1])
# print(dishesDict)
# print_current_values()
print("tables("+str(getNumberOfTables(dishesDict, table_width,separation))+").")
f.close()
main()<file_sep>import sys
import re
import itertools
import copy
from collections import OrderedDict
keywords = ["people", "locations","preferences","order"]
people = 0
locations = 0
preferences = 0
orders = {}
def nonblank_lines(f):
for l in f:
line = l.rstrip()
line = l.lstrip()
for key in keywords:
if (re.match(key+r'\(\d+(, \d+)*\)\.',line)):
parse_line(line, key)
def parse_line(op, key):
global people
global locations
global preferences
global orders
values = re.findall('\d+', op)
if key is keywords[0]:
people = int(values.pop(0))
elif key is keywords[1]:
locations = int(values.pop(0))
elif key is keywords[2]:
preferences = int(values.pop(0))
elif key is keywords[3]:
if int(values[0]) in orders:
orders.get(int(values.pop(0))).append(list(map(int, values)))
else:
orders.update({int(values.pop(0)):[list(map(int, values))]})
def getViolations(listOfPreferences, listToCheckWith):
violations = 0
for item in listToCheckWith:
for i in range(len(listOfPreferences)):
if item not in listOfPreferences[i]:
continue
for k in listOfPreferences[i][listOfPreferences[i].index(item)+1:]:
if listToCheckWith.index(item) < listToCheckWith.index(k):
violations+=1
return violations
def print_current_values():
print ("people: ", people, "\nlocations:",locations
,"\npreferences:",preferences,"\norders:",orders)
def main():
f = open(sys.argv[1], 'r')
nonblank_lines(f)
# print_current_values()
preferencesList = []
for key, value in orders.items():
chainList = list(itertools.chain.from_iterable(value))
removedDuplicateList = list(OrderedDict.fromkeys(chainList))
preferencesList.append(removedDuplicateList)
chainList = list(itertools.chain.from_iterable(preferencesList))
minValue = min(chainList)
maxValue = max(chainList)
permutations = list(itertools.permutations(range(minValue, maxValue+1),maxValue))
violations = getViolations(preferencesList,permutations[0])
for permu in permutations:
currentViolation = getViolations(preferencesList,permu)
if currentViolation < violations:
violations = currentViolation
print("violations("+str(violations)+").")
f.close()
main()<file_sep>import copy
from collections import deque
import sys
import re
keywords = ["vessels", "source","people","capacity","horizon"]
#size
vessels = 0
source = 0
people = 0
capacity = {}
horizon = 0
def bfs(initialArray,capacities,initial_steps,people,splitAmount,horizon):
alreadyExplored = []
queue = deque([(initialArray,initial_steps)]) #create queue
while len(queue)>0: #make sure there are nodes to check left
node = queue.popleft() #grab the first node
currentConfiguration = node[0]
steps = node[1]
# print("trying:",currentMatrix,"\nSteps: ",numberOfSteps)
#we already saw this one
if currentConfiguration in alreadyExplored:
continue
#check if its the answer
if is_correct(currentConfiguration,splitAmount,people):
return "split(yes)."
if horizon < steps:
return ("split(no).")
# #add it to already explored
alreadyExplored.append(currentConfiguration)
#if not an answer we generate all posible moves from this graph
index = 0
options = []
for i in currentConfiguration:
#add to queue here check if already in checked before adding to queue
for j in range(len(currentConfiguration)):
currentState = getState(currentConfiguration,index, j, capacities)
options.append(currentState)
# print(currentState)
index+=1
# print("i:\n",i)
#remove duplicates
b_set = set(map(tuple,options)) #need to convert the inner lists to tuples so they are hashable
b = map(list,b_set) #Now convert tuples back into lists
# print(list(b))
for lst in b:
#put in queue
queue.append([lst,steps+1])
return ("split(no).")
def getState(arrayCurrentState ,currentVessel, toVessel, capacities):
# print("inside get states")
arr = arrayCurrentState[:]
toVesselMaxCapacity = capacities.get(toVessel+1)
# print("ARRAY: ",toVessel," current ", currentVessel)
toVesselCurrentCapacity = arr[toVessel]
currentVesselCurrentCapacity = arr[currentVessel]
# print(arr[currentVessel])
# print(arr[toVessel], "capacity: ", toVesselMaxCapacity, "toVesselCurrentCapacity:",toVesselCurrentCapacity)
if(toVesselMaxCapacity-toVesselCurrentCapacity)>=0 and (currentVessel != toVessel):
needed = toVesselMaxCapacity-toVesselCurrentCapacity
if(currentVesselCurrentCapacity-needed) >= 0:
# print("Left: ",currentVesselCurrentCapacity-needed)
tranfer = currentVesselCurrentCapacity-needed
#update the array with new value
arr[currentVessel] = tranfer
arr[toVessel] = arr[toVessel] + needed
# print("new array: ", arr)
elif(needed > currentVesselCurrentCapacity):
# print("test")
arr[toVessel] = arr[toVessel] + currentVesselCurrentCapacity
arr[currentVessel] = 0
# print("new array: ", arr)
# print("needed: ", needed)
return arr
def create_initial_state(source, capacities):
size = len(capacities)
# print("source key:, ",source)
arr = []
for key, value in capacities.items():
if key == source:
arr.append(value)
else:
arr.append(0)
# print(arr)
return arr
def is_correct(arr, partition, numberPeople):
total = 0
peopleCounter = 0
for i in arr:
if(total+i) < partition:
total+=i
elif (total+i) == partition:
peopleCounter+=1
total=0
if peopleCounter > numberPeople:
break
return (peopleCounter == numberPeople)
def nonblank_lines(f):
for l in f:
line = l.rstrip()
line = l.lstrip()
for key in keywords:
if (re.match(key+r'\(\d+(, \d+)*\)\.',line)):
parse_line(line, key)
def parse_line(op, key):
global vessels
global source
global people
global capacity
global horizon
values = re.findall('\d+', op)
if key is keywords[0]:
vessels = int(values.pop())
elif key is keywords[1]:
source = int(values.pop())
elif key is keywords[2]:
people = int(values.pop())
elif key is keywords[3]:
capacity.update({int(values.pop(0)):int(values.pop(0))})
elif key is keywords[4]:
horizon = int(values.pop())
def print_current_values():
print ("vessels: ", vessels, "\nsource:",source
,"\npeople:",people,"\ncapacity:",capacity,"\nhorizon:",horizon)
def main():
f = open(sys.argv[1], 'r')
nonblank_lines(f)
initial_array = create_initial_state(source,capacity)
print(bfs(initial_array,capacity,0,people,(capacity.get(source)/people),horizon))
f.close()
main()
|
6ebb67dfe8de546c48e20bc8602aad9c9e8e3096
|
[
"Python"
] | 6
|
Python
|
p0dxD/Programming-language
|
1ab5f57d423507dd0966928331b92540eb87399e
|
3351e8311bebb517e2c0cd360be1c413cc7d83ee
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.