Initial Commit.

This commit is contained in:
Travis Burtrum 2011-09-18 23:41:12 -04:00
commit b215cd0d2a
21 changed files with 5593 additions and 0 deletions

218
ServerChecker.java Executable file
View File

@ -0,0 +1,218 @@
/*
MoparScape.org server status page
Copyright (C) 2011 Travis Burtrum (moparisthebest)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.GregorianCalendar;
import java.util.Date;
import java.util.HashMap;
public class ServerChecker {
// remove dups : SELECT * FROM servers s1, servers s2 WHERE s1.id != s2.id AND s1.ipaddress = s2.ipaddress
/*
select bad_rows.*
from servers as bad_rows
inner join (
SELECT s1.* FROM servers s1, servers s2 WHERE s1.id != s2.id AND s1.ipaddress = s2.ipaddress
) as good_rows on good_rows.id = bad_rows.id;
*/
private static final String userName = "user";
private static final String userPass = "pass";
private static final String databaseUrl = "jdbc:mysql://localhost:3306/serverstat";
private static final String sqlOr = " OR id=";
private HashMap<String, String> iphostname = new HashMap<String, String>(1000);
private Connection conn;
public ServerChecker() {
System.out.println(new Date()+" - STARTING...");
try {
connect();
// timeFromDate();
updateServers();
validateNewServers();
// timestamp();
disconnect();
System.out.println(new Date()+" - FINISHED SUCCESSFULLY!!");
} catch (Exception e) {
System.out.println(new Date()+" - ERROR!!");
e.printStackTrace(System.out);
}
}
/*
private void timestamp() throws Exception {
DataOutputStream dos = new DataOutputStream(new FileOutputStream("/opt/lampp/htdocs/moparscape.org/timestamp"));
dos.writeLong(System.currentTimeMillis()/1000);
dos.close();
}
*/
private void connect() throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(databaseUrl, userName, userPass);
}
private void disconnect() throws Exception {
conn.close();
}
private void safeExecuteUpdate(Statement stmt, String update){
try{
stmt.executeUpdate(update);
}catch(Exception e){
System.out.println("safeExecuteUpdate error!");
System.out.println("update: "+update);
System.out.println("Error: "+e.getMessage());
e.printStackTrace(System.out);
}
}
private void updateServers() throws Exception {
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT `id`, `ip`, `port` from `servers` where sponsored = '0'");
StringBuilder online = new StringBuilder("UPDATE servers SET online=1, totalcount=totalcount+1, oncount=oncount+1, `uptime` = (oncount / totalcount * 100) WHERE id=");
StringBuilder offline = new StringBuilder("UPDATE servers SET online=0, totalcount=totalcount+1, `uptime` = (oncount / totalcount * 100) WHERE id=");
int onLength = online.length();
int offLength = offline.length();
while (result.next()) {
// System.out.println("Name:\t" + result.getString("id"));
// System.out.println("IP:\t" + result.getString("IP"));
// System.out.println("Port:\t" + result.getString("Port"));
if (validServer(result.getString("ip"), result.getInt("port"))) {
// System.out.println("ONLINE");
online.append(result.getString("id")).append(sqlOr);
} else {
// System.out.println("OFFLINE");
offline.append(result.getString("id")).append(sqlOr);
}
}
//System.out.println(online.substring(0, online.length()-sqlOr.length()));
//System.out.println(offline.substring(0, offline.length()-sqlOr.length()));
if(online.length() > onLength)
safeExecuteUpdate(stmt, online.substring(0, online.length()-sqlOr.length()));
if(offline.length() > offLength)
safeExecuteUpdate(stmt, offline.substring(0, offline.length()-sqlOr.length()));
safeExecuteUpdate(stmt, "DELETE FROM `servers` WHERE `uptime` < '40'");
}
private void validateNewServers() throws Exception {
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT `id`, `ip`, `port` from `toadd` WHERE `verified` = '1'");
Statement stmt2 = conn.createStatement();
while (result.next()) {
// System.out.println("Name:\t" + result.getString("id"));
// System.out.println("IP:\t" + result.getString("IP"));
// System.out.println("Port:\t" + result.getString("Port"));
if (validServer(result.getString("ip"), result.getInt("port"))) {
// System.out.println("ONLINE");
safeExecuteUpdate(stmt2, "INSERT INTO `servers` (`uid`, `uname`, `name`, `ip`, `port`, `version`, `time`, `info`, `ipaddress`, `rs_name`, `rs_pass`) SELECT `uid`, `uname`, `name`, `ip`, `port`, `version`, `time`, `info`, `ipaddress`, `rs_name`, `rs_pass` FROM `toadd` WHERE `id` = "+result.getString("id"));
safeExecuteUpdate(stmt2, "DELETE FROM `toadd` WHERE `id` = "+result.getString("id"));
}
}
// delete entries that are past a certain date old
// System.currentTimeMillis()/1000 is unix timestamp
// 86400 is 24 hours in seconds
long oldSeconds = (System.currentTimeMillis()/1000) - 86400;
safeExecuteUpdate(stmt2, "DELETE FROM `toadd` WHERE `time` < "+oldSeconds);
}
/*
private void timeFromDate() throws Exception {
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT `id`, `date` from `servers`");
Statement stmt2 = conn.createStatement();
while (result.next()) {
String[] date = result.getString("date").split("-");
safeExecuteUpdate(stmt2, "UPDATE servers SET time="+new GregorianCalendar(Integer.parseInt("20"+date[2]),Integer.parseInt(date[0])-1,Integer.parseInt(date[1])).getTimeInMillis()/1000 +" WHERE id="+result.getString("id"));
}
}
*/
private void deleteServers(String s1, String s2) throws Exception {
Statement stmt = conn.createStatement();
safeExecuteUpdate(stmt, "DELETE FROM `servers` WHERE `ip` = '"+s1+"' OR `ip` = '"+s2+"'");
}
private boolean validServer(String ip, int port) throws Exception {
Socket s;
try {
s = new Socket();
s.setSoTimeout(2000);
InetSocketAddress addy = new InetSocketAddress(ip, port);
if(addy.isUnresolved())
return false;
// System.out.println("addy: "+addy.getAddress().getHostAddress());
String resolvedIP = addy.getAddress().getHostAddress();
if(iphostname.containsKey(resolvedIP)){
// System.out.println("deleteServers("+ip+", "+iphostname.get(resolvedIP)+")");
// if you delete the server in the database, anyone can delete any server by posting a duplicate
// instead simply don't allow this one in.
//deleteServers(ip, iphostname.get(resolvedIP));
return false;
}
// System.out.println("iphostname.put("+resolvedIP+", "+ip+")");
iphostname.put(resolvedIP, ip);
s.connect(addy, 2000);
} catch (Exception e) {
// e.printStackTrace();
return false;
}
try {
s.close();
} catch (Exception e) {}
return true;
/* try {
DataOutputStream out = new DataOutputStream(s.getOutputStream());
DataInputStream in = new DataInputStream(s.getInputStream());
out.writeChar(14 << 8);
out.flush();
in.skip(8);
int response = in.readByte() & 0xff;
try {
s.close();
} catch (Exception e) {}
return response == 0;
} catch (Exception e) {
// e.printStackTrace();
}
try {
s.close();
} catch (Exception e) {}
return false;
*/ }
public static void main(String args[]) {
// System.out.println(new GregorianCalendar(2008,2-1,1).getTimeInMillis()/1000);// 1204329600
new ServerChecker();
}
}

661
agpl-3.0.txt Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.

100
serverstatus.php Executable file
View File

@ -0,0 +1,100 @@
<?php
/*
MoparScape.org server status page
Copyright (C) 2011 Travis Burtrum (moparisthebest)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if($_REQUEST['action'] != 'verify')
require_once('/path/to/agreed.php');
//ini_set('display_errors', 0);
//error_reporting(E_ALL);
define('SS_PAGE', 1);
global $ss_sourcedir;
$ss_sourcedir = './ss_sources';
require_once($ss_sourcedir.'/util.php');
// What function shall we execute? (done like this for memory's sake.)
// defaults
$header = true;
$do_setup = true;
$action = ss_main($header, $do_setup);
if($do_setup)
doSetup();
if($header)
echoHeader($action);
call_user_func($action);
if($header)
echoFooterExit();
// The main controlling function.
function ss_main(&$header, &$do_setup)
{
global $ss_sourcedir;
if (empty($_REQUEST['action'])){
if(!empty($_REQUEST['server'])){
require_once($ss_sourcedir . '/view.php');
return 'view';
}
require_once($ss_sourcedir . '/display.php');
return 'display';
}
// Here's the monstrous $_REQUEST['action'] array - $_REQUEST['action'] => array($file, $function, $header, $do_setup).
$actionArray = array(
'display' => array('display.php', 'display'),
'view' => array('view.php', 'view'),
'register' => array('register.php', 'register'),
'register2' => array('register.php', 'register2'),
'verify' => array('verify.php', 'verify', false, false),
'random' => array('random.php', 'random_page', false, false),
'up' => array('vote.php', 'vote'),
'down' => array('vote.php', 'vote'),
'vote' => array('vote.php', 'vote2'),
'ban' => array('moderate.php', 'banServ'),
'delete' => array('moderate.php', 'deleteServ'),
'search' => array('search.php', 'search'),
'search2' => array('search.php', 'search2'),
'search3' => array('search.php', 'search3'),
);
// Get the function and file to include - if it's not there, do the board index.
if (!isset($_REQUEST['action']) || !isset($actionArray[$_REQUEST['action']]))
{
// xxx maybe they are trying to ddos us (action=hackedbybattlescapecrew)
//global $thispage;
//die('No action found, try '.$thispage);
// Fall through to the display then...
require_once($ss_sourcedir . '/display.php');
return 'display';
}
// Otherwise, it was set - so let's go to that action.
require_once($ss_sourcedir . '/' . $actionArray[$_REQUEST['action']][0]);
// here is the only place we NEED to set $header and $do_setup
$header = (isset($actionArray[$_REQUEST['action']][2]) ? $actionArray[$_REQUEST['action']][2] : true);
$do_setup = (isset($actionArray[$_REQUEST['action']][3]) ? $actionArray[$_REQUEST['action']][3] : true);
return $actionArray[$_REQUEST['action']][1];
}
?>

325
ss_sources/display.php Executable file
View File

@ -0,0 +1,325 @@
<?php
/*
MoparScape.org server status page
Copyright (C) 2011 Travis Burtrum (moparisthebest)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('SS_PAGE'))
die('Hacking attempt...');
function display(){
//echo 'this is display';
$online = isset($_GET['offline']) ? 0 : 1;
display_table($online, "`online` = '$online' AND `sponsored` = '0'");
}
function display_table($online, $where, $num_servers = null){
$num_per_page = 30;
global $g_headers;
$g_headers = array(
'name' => 'Server Name',
'version' => 'Client Version',
'uname' => 'Owner',
'uptime' => 'Uptime',
'time' => 'Since',
'vote' => 'Votes',
);
$start = isset($_GET['start']) ? $_GET['start'] : 0;
mysql_con();
global $g_mysqli;
$start = $g_mysqli->real_escape_string($start);
//$start = mysqli_real_escape_string($g_mysqli, $start);
//if($_SERVER['REMOTE_ADDR'] == "24.172.204.242") echo "start is: $start";
if(isset($_GET['sort']) && isset($g_headers[$_GET['sort']])){
$order_by = 'ORDER BY `'.$g_mysqli->real_escape_string($_GET['sort']).'` '.(isset($_GET['desc']) ? 'DESC' : 'ASC');
}else{
//default sort
// $_GET['sort'] = 'uptime';
// $_GET['desc'] = '';
$order_by = 'ORDER BY `uptime` DESC, `time` ASC';
}
$order_by .= " LIMIT $start, $num_per_page";
if($start == 0 && $online == 1 && !isset($_GET['sort']))
echoTable('Spons', "`sponsored` != '0'", "ORDER BY `sponsored` DESC, RAND() LIMIT 10");
echoTable('Other', $where, $order_by, $online, $start, $num_per_page, $num_servers);
close_mysql();
}
function getPageIndex($where, $start, $num_per_page, $num_servers, $online){
if($num_servers == null){
global $g_mysqli;
$stmt = $g_mysqli->prepare("SELECT COUNT(*) FROM `servers` WHERE ".$where) or debug($g_mysqli->error);
$stmt->execute();
// bind result variables
$stmt->bind_result($num_servers);
$stmt->fetch();
$stmt->close();
}
//echo (sprintf('$num_servers: %s', $num_servers));
// if we don't have enough for pages, just forget it
if($num_servers <= $num_per_page)
return null;
else
return ss_constructPageIndex($_SERVER['PHP_SELF'], &$start, $num_servers, $num_per_page, $online);
}
function echoTable($class, $where, $order_by, $online = 1, $start = 0, $num_per_page = 30, $num_servers = null){
$pageindex = getPageIndex($where, $start, $num_per_page, &$num_servers, $online);
echoTableHeader($class, $num_servers, $pageindex, $online);
global $g_mysqli;
//echo "SELECT `name`, `pic_url`, `uid`, `uname`, `online`, `ip`, `port`, `version`, `uptime`, `time`, `vote` FROM `servers` WHERE ".$where.' '.$order_by;
$stmt = $g_mysqli->prepare("SELECT `name`, `pic_url`, `uid`, `uname`, `online`, `ip`, `port`, `version`, `uptime`, `time`, `vote` FROM `servers` WHERE ".$where.' '.$order_by) or debug($g_mysqli->error);
$stmt->execute();
// bind result variables
$stmt->bind_result($name, $pic_url, $uid, $uname, $online, $ip, $port, $version, $uptime, $time, $votes);
$odd = false;
while($stmt->fetch()){
echoTableRow($class, $name, $pic_url, $uid, $uname, $ip, $port, $version, $uptime, $time, $votes, $online, $odd);
$odd = !$odd;
}
$stmt->close();
echoTableFooter();
}
function echoTableRow($class, $name, $pic_url, $uid, $uname, $ip, $port, $version, $uptime, $time, $votes, $online = 1, $odd = False){
global $thispage;
if($pic_url != '')
$name = '<img src="'.$pic_url.'" alt="'.$name.'" width="185" height="25" />';
if($online == 1){
$link = "http://www.moparscape.org/index.php?server=%s&amp;port=%s&amp;version=%s&amp;detail=";
$link = sprintf($link, $ip, $port, $version);
$play = '<a href="%s0">High</a> / <a href="%s1">Low</a>';
$play = sprintf($play, $link, $link);
}else{
$play = '<div class="offline">Server Offline!</div>';
}
// date("m-d-y", $time)
// strftime($time_format, $time+$time_offset)
?>
<tr<?php if($odd) echo ' class="odd"'; ?>>
<td><a href="?server=<?php echo $ip; ?>"><?php echo $name; ?></a></td>
<td><?php echo $version; ?></td>
<td><a href="http://www.moparscape.org/smf/index.php?action=profile;u=<?php echo $uid; ?>"><?php echo $uname; ?></a></td>
<td><?php echo $uptime; ?>%</td>
<td><?php echo date("m-d-y", $time); ?></td>
<td><?php echo ($votes > 0) ? '+'.$votes: $votes; ?></td>
<td><a href="<?php echo $thispage ?>?action=up&amp;server=<?php echo $ip ?>"><img src="http://<?php echo $_SERVER['SERVER_NAME']; ?>/images/up.png" alt="Up" /></a><a href="<?php echo $thispage ?>?action=down&amp;server=<?php echo $ip ?>"><img src="http://<?php echo $_SERVER['SERVER_NAME']; ?>/images/down.png" alt="Down" /></a></td>
<?php
if(!can_mod() || $class == "Spons"){
?>
<td><?php echo $play; ?></td>
<?php
}else{
?>
<td><a href="<?php echo $thispage ?>?action=delete&amp;server=<?php echo $ip ?>">X</a> / <a href="<?php echo $thispage ?>?action=ban&amp;server=<?php echo $ip ?>">X</a></td>
<?php
}
?>
</tr>
<?php
}
function echoTableHeader($class, $num, $pageindex = null, $online = 1){
global $g_headers, $thispage;
if($class == "Spons")
$caption = 'Sponsored Servers';
elseif($online == 2)
$caption = 'Search Results';
// other
else
$caption = 'Other Servers';
?>
<table class="<?php echo strtolower($class); ?>" summary="<?php echo $caption; ?>">
<caption>
<?php echo $caption; ?>
</caption>
<thead>
<tr>
<?php
if($class == "Spons")
$link = ' <th scope="col">%s</th>'."\n";
else
$link = ' <th scope="col"><a class="tdheader" href="'.$thispage.'?'.((isset($_GET['action']) && strpos($_GET['action'], 'search') !== false) ? 'action=search3&amp;' : '').(isset($_GET['offline']) ? 'offline&amp;' : '').'sort=%s">%s</a></th>'."\n";
foreach ($g_headers as $sort => $name){
if($class == "Spons"){
printf($link, $name);
}else{
$pic = '';
if((!isset($_GET['sort']) && $sort == 'uptime') || $sort == $_GET['sort']){
if(!isset($_GET['sort']) || isset($_GET['desc'])){
$name .= ' <img src="http://'.$_SERVER['SERVER_NAME'].'/images/sort_down.gif" alt="" />';
}else{
$sort .= '&amp;desc';
$name .= ' <img src="http://'.$_SERVER['SERVER_NAME'].'/images/sort_up.gif" alt="" />';
}
}
printf($link, $sort, $name);
}
}
?>
<th scope="col">Vote here!</th>
<?php
if(!can_mod() || $class == "Spons"){
?>
<th scope="col">Play (select detail)</th>
<?php
}else{
?>
<th scope="col">Delete / Ban</th>
<?php
}
?>
</tr>
</thead>
<tfoot>
<tr>
<th scope="row">Total</th>
<th scope="row" colspan="7"><?php echo $num; ?> Servers</th>
</tr>
<?php
if($class == "Spons"){
?>
<tr>
<th scope="row">Info</th>
<th scope="row" colspan="7"><a href="http://www.moparscape.org/sponsbid.php">How to get Sponsored</a>.</th>
</tr>
<?php
}
?>
<?php
if($pageindex != null){
?>
<tr>
<th scope="row">Pages</th>
<th scope="row" colspan="7"><?php echo $pageindex; ?></th>
</tr>
<?php
}
?>
</tfoot>
<tbody>
<?php
}
function echoTableFooter(){
?>
</tbody>
</table>
<br />
<?php
}
function ss_constructPageIndex($base_url, &$start, $max_value, $num_per_page, $online)
{
switch ($online) {
case 0:
$prefix = '?offline&amp;';
break;
case 1:
$prefix = '?';
break;
// this means search
case 2:
$prefix = '?action=search3&amp;';
break;
}
$prefix .= (isset($_GET['sort']) ? 'sort='.$_GET['sort'].'&amp;':'').(isset($_GET['desc']) ? 'desc&amp;':'');
// Save whether $start was less than 0 or not.
$start_invalid = $start < 0;
// Make sure $start is a proper variable - not less than 0.
if ($start_invalid)
$start = 0;
// Not greater than the upper bound.
elseif ($start >= $max_value)
$start = max(0, (int) $max_value - (((int) $max_value % (int) $num_per_page) == 0 ? $num_per_page : ((int) $max_value % (int) $num_per_page)));
// And it has to be a multiple of $num_per_page!
else
$start = max(0, (int) $start - ((int) $start % (int) $num_per_page));
$base_link = '<a href="' . strtr($base_url, array('%' => '%%')) . $prefix . 'start=%d' . '">%s</a> ';
// If they didn't enter an odd value, pretend they did.
$PageContiguous = (int) 3;
// Show the first page. (>1< ... 6 7 [8] 9 10 ... 15)
if ($start > $num_per_page * $PageContiguous)
$pageindex = sprintf($base_link, 0, '1');
else
$pageindex = '';
// Show the ... after the first page. (1 >...< 6 7 [8] 9 10 ... 15)
if ($start > $num_per_page * ($PageContiguous + 1))
$pageindex .= '<b> ... </b>';
// Show the pages before the current one. (1 ... >6 7< [8] 9 10 ... 15)
for ($nCont = $PageContiguous; $nCont >= 1; $nCont--)
if ($start >= $num_per_page * $nCont)
{
$tmpStart = $start - $num_per_page * $nCont;
$pageindex.= sprintf($base_link, $tmpStart, $tmpStart / $num_per_page + 1);
}
// Show the current page. (1 ... 6 7 >[8]< 9 10 ... 15)
if (!$start_invalid)
$pageindex .= '[<b>' . ($start / $num_per_page + 1) . '</b>] ';
else
$pageindex .= sprintf($base_link, $start, $start / $num_per_page + 1);
// Show the pages after the current one... (1 ... 6 7 [8] >9 10< ... 15)
$tmpMaxPages = (int) (($max_value - 1) / $num_per_page) * $num_per_page;
for ($nCont = 1; $nCont <= $PageContiguous; $nCont++)
if ($start + $num_per_page * $nCont <= $tmpMaxPages)
{
$tmpStart = $start + $num_per_page * $nCont;
$pageindex .= sprintf($base_link, $tmpStart, $tmpStart / $num_per_page + 1);
}
// Show the '...' part near the end. (1 ... 6 7 [8] 9 10 >...< 15)
if ($start + $num_per_page * ($PageContiguous + 1) < $tmpMaxPages)
$pageindex .= '<b> ... </b>';
// Show the last number in the list. (1 ... 6 7 [8] 9 10 ... >15<)
if ($start + $num_per_page * $PageContiguous < $tmpMaxPages)
$pageindex .= sprintf($base_link, $tmpMaxPages, $tmpMaxPages / $num_per_page + 1);
return $pageindex;
}
?>

BIN
ss_sources/fonts/arial.ttf Executable file

Binary file not shown.

BIN
ss_sources/fonts/arial_black.ttf Executable file

Binary file not shown.

BIN
ss_sources/fonts/arial_bold.ttf Executable file

Binary file not shown.

Binary file not shown.

BIN
ss_sources/fonts/arial_italic.ttf Executable file

Binary file not shown.

172
ss_sources/image_server.php Executable file
View File

@ -0,0 +1,172 @@
<?php
/*
MoparScape.org server status page
Copyright (C) 2011 Travis Burtrum (moparisthebest)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
$script_name = '/serverstatus/';
$script_name_len = strlen($script_name);
/*
function echoImage($online = -1){
if($online == 1)
$url = 'http://mopar.moparscape.org/images/online.gif';
elseif($online == 0)
$url = 'http://mopar.moparscape.org/images/offline.gif';
else
$url = 'http://mopar.moparscape.org/images/error.gif';
close_mysql();
header("Location: $url");
//echo("Location: $url"); debug_print_backtrace();
exit;
}
*/
function scale(&$img, $scale) {
$width = imagesx($img) * $scale/100;
$height = imagesy($img) * $scale/100;
resize($img, $width, $height);
}
function resize(&$img, $width, $height) {
// enforce max res. 1920x1200
if($width > 1920 || $height > 1200)
return;
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $img, 0, 0, 0, 0, $width, $height, imagesx($img), imagesy($img));
$img = $new_image;
}
/*
function centerImageString($image, $string, $font_size, $y){
$text_width = imagefontwidth($font_size)*strlen($string);
$center = ceil(imagesx($image) / 2);
$x = $center - (ceil($text_width/2));
// $color = imagecolorallocate($image, 230, 230, 255);
$color = imagecolorallocate($image, 199, 208, 227);
imagestring($image, $font_size, $x, $y, $string, $color);
}
*/
function centerTtfString($image, $string, $font_size, $y, $font='./fonts/arial_bold.ttf'){
$color = imagecolorallocate($image, 199, 208, 227);
$tb = imagettfbbox($font_size, 0, $font, $string);
$x = ceil((imagesx($image) - $tb[2]) / 2); // lower left X coordinate for text
imagettftext($image, $font_size, 0, $x, $y, $color, $font, $string);
}
function echoImage($online = -1, $text = 'Error!', $size_req = ''){
close_mysql();
if($online == 1)
$file = '../images/online.png';
elseif($online == 0)
$file = '../images/offline.png';
else
$file = '../images/error.png';
$im = imagecreatefrompng($file);
// the following not needed, since there is no more transparency in image
// imagealphablending($im, true); // setting alpha blending on
// imagesavealpha($im, true); // save alphablending setting (important)
// centerImageString($im, $text, 5, 20);
// size 12, y 35 can be used with <= 27 chars
centerTtfString($im, $text, 11, 34);
if($size_req != ''){
$x_pos = strpos($size_req, 'x');
if($x_pos !== false){
$width = substr($size_req, 0, $x_pos);
$height = substr($size_req, ++$x_pos, strlen($size_req));
// width and height must be digit integers
if(ctype_digit($width) && ctype_digit($height))
resize($im, $width, $height);
}elseif(ctype_digit($size_req)){
scale($im, $size_req);
}
}
// Turn on output buffering
ob_start();
// Output will now go to a buffer rather than the browser.
imagepng($im);
imagedestroy($im);
// header("X-Powered-By: lighttpd (Ubuntu)");
header('Content-Type: image/png');
//header('Last-Modified: Mon, 05 Jan 2009 21:37:52 GMT');
header("Pragma: no-cache");
header('Cache-Control: private');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// header('Expires: 0');
// header('Content-Length: ' . filesize($file));
// Tell the browser the number of bytes that have been
// written to the buffer.
header("Content-Length: " . ob_get_length());
// Now send the buffer's contents to the browser and turn off
// output buffering.
ob_end_flush();
// ob_clean();
// flush();
// readfile($file);
exit;
}
define('SS_PAGE', 1);
require_once('./util.php');
// if there is no URI, some error, so forward to error
if (empty($_SERVER['REQUEST_URI']))
echoImage();
// get the server, if there isn't one, forward to error
if ( (substr($_SERVER['REQUEST_URI'], strrpos($_SERVER['REQUEST_URI'], '.'), 4) == '.png') && (substr($_SERVER['REQUEST_URI'], 0, $script_name_len) == $script_name) )
$server = substr($_SERVER['REQUEST_URI'], $script_name_len, strrpos($_SERVER['REQUEST_URI'], '.')-$script_name_len);
else
echoImage();
// check if $server contains a size request, it would be before the /, the real ip after.
$slash_pos = strpos($server, '/');
if($slash_pos !== false){
$size_req = substr($server, 0, $slash_pos);
$server = substr($server, ++$slash_pos, strlen($server));
}else
$size_req = '';
mysql_con();
global $g_mysqli;
$stmt = $g_mysqli->prepare('SELECT `online` FROM `servers` WHERE `ip` = ? LIMIT 1') or debug($g_mysqli->error);
$stmt->bind_param("s", $server);
$stmt->execute() or debug($g_mysqli->error);
// bind result variables
$stmt->bind_result($online);
// if there is no server in the database, forward to error
if(!$stmt->fetch())
echoImage(-1, $server, $size_req);
$stmt->close();
// forward to the right page
echoImage($online, $server, $size_req);
?>

69
ss_sources/moderate.php Executable file
View File

@ -0,0 +1,69 @@
<?php
/*
MoparScape.org server status page
Copyright (C) 2011 Travis Burtrum (moparisthebest)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('SS_PAGE'))
die('Hacking attempt...');
function banServ(){
forceAdmin();
global $g_mysqli;
mysql_con();
$sql = "INSERT INTO `banned` SELECT * FROM `servers` WHERE `ip` = ? AND `sponsored` = '0' LIMIT 1";
$stmt = $g_mysqli->prepare($sql) or debug($g_mysqli->error);
$stmt->bind_param("s", $_GET['server']);
// execute the query
$stmt->execute() or debug($g_mysqli->error);
if ($stmt->affected_rows != 1) {
echo 'Ban failed, is it a sponsored server?, PM <a href="http://www.moparscape.org/smf/index.php?action=profile;u=1">Moparisthebest</a> on the forums to with details so he can fix it.';
return;
}
$stmt->close();
deleteServ();
}
function deleteServ(){
forceAdmin();
global $g_mysqli;
mysql_con();
$sql = "DELETE FROM `servers` WHERE `ip` = ? AND `sponsored` = '0' LIMIT 1";
$stmt = $g_mysqli->prepare($sql) or debug($g_mysqli->error);
$stmt->bind_param("s", $_GET['server']);
// execute the query
$stmt->execute() or debug($g_mysqli->error);
if ($stmt->affected_rows != 1) {
echo 'Delete failed, is it a sponsored server?, PM <a href="http://www.moparscape.org/smf/index.php?action=profile;u=1">Moparisthebest</a> on the forums to with details so he can fix it.';
return;
}
$stmt->close();
forward();
}
?>

364
ss_sources/oldpost.txt.php Executable file
View File

@ -0,0 +1,364 @@
<?php
/*
MoparScape.org server status page
Copyright (C) 2011 Travis Burtrum (moparisthebest)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
die('hacking attempt...');
// Parses some bbc before sending into the database...
function preparsecode(&$message, $previewing = false)
{
global $user_info, $modSettings, $context;
// This line makes all languages *theoretically* work even with the wrong charset ;).
//$message = preg_replace('~&amp;#(\d{4,5}|[2-9]\d{2,4}|1[2-9]\d);~', '&#$1;', $message);
// Clean up after nobbc ;).
$message = preg_replace('~\[nobbc\](.+?)\[/nobbc\]~ie', '\'[nobbc]\' . strtr(\'$1\', array(\'[\' => \'&#91;\', \']\' => \'&#93;\', \':\' => \'&#58;\', \'@\' => \'&#64;\')) . \'[/nobbc]\'', $message);
// Remove \r's... they're evil!
$message = strtr($message, array("\r" => ''));
// You won't believe this - but too many periods upsets apache it seems!
$message = preg_replace('~\.{100,}~', '...', $message);
// Trim off trailing quotes - these often happen by accident.
while (substr($message, -7) == '[quote]')
$message = substr($message, 0, -7);
while (substr($message, 0, 8) == '[/quote]')
$message = substr($message, 8);
// Check if all code tags are closed.
$codeopen = preg_match_all('~(\[code(?:=[^\]]+)?\])~is', $message, $dummy);
$codeclose = preg_match_all('~(\[/code\])~is', $message, $dummy);
// Close/open all code tags...
if ($codeopen > $codeclose)
$message .= str_repeat('[/code]', $codeopen - $codeclose);
elseif ($codeclose > $codeopen)
$message = str_repeat('[code]', $codeclose - $codeopen) . $message;
// Now that we've fixed all the code tags, let's fix the img and url tags...
$parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $message, -1, PREG_SPLIT_DELIM_CAPTURE);
// The regular expression non breaking space has many versions.
$non_breaking_space = $context['utf8'] ? ($context['server']['complex_preg_chars'] ? '\x{A0}' : pack('C*', 0xC2, 0xA0)) : '\xA0';
// Only mess with stuff outside [code] tags.
for ($i = 0, $n = count($parts); $i < $n; $i++)
{
// It goes 0 = outside, 1 = begin tag, 2 = inside, 3 = close tag, repeat.
if ($i % 4 == 0)
{
fixTags($parts[$i]);
// Replace /me.+?\n with [me=name]dsf[/me]\n.
if (strpos($user_info['name'], '[') !== false || strpos($user_info['name'], ']') !== false || strpos($user_info['name'], '\'') !== false || strpos($user_info['name'], '"') !== false)
$parts[$i] = preg_replace('~(?:\A|\n)/me(?: |&nbsp;)([^\n]*)(?:\z)?~i', '[me=&quot;' . $user_info['name'] . '&quot;]$1[/me]', $parts[$i]);
else
$parts[$i] = preg_replace('~(?:\A|\n)/me(?: |&nbsp;)([^\n]*)(?:\z)?~i', '[me=' . $user_info['name'] . ']$1[/me]', $parts[$i]);
if (!$previewing && strpos($parts[$i], '[html]') !== false)
{
if (allowedTo('admin_forum'))
$parts[$i] = preg_replace('~\[html\](.+?)\[/html\]~ise', '\'[html]\' . strtr(un_htmlspecialchars(\'$1\'), array("\n" => \'&#13;\', \' \' => \' &#32;\')) . \'[/html]\'', $parts[$i]);
// We should edit them out, or else if an admin edits the message they will get shown...
else
{
while (strpos($parts[$i], '[html]') !== false)
$parts[$i] = preg_replace('~\[[/]?html\]~i', '', $parts[$i]);
}
}
// Let's look at the time tags...
$parts[$i] = preg_replace('~\[time(=(absolute))*\](.+?)\[/time\]~ie', '\'[time]\' . (is_numeric(\'$3\') || @strtotime(\'$3\') == 0 ? \'$3\' : strtotime(\'$3\') - (\'$2\' == \'absolute\' ? 0 : (($modSettings[\'time_offset\'] + $user_info[\'time_offset\']) * 3600))) . \'[/time]\'', $parts[$i]);
$list_open = substr_count($parts[$i], '[list]') + substr_count($parts[$i], '[list ');
$list_close = substr_count($parts[$i], '[/list]');
if ($list_close - $list_open > 0)
$parts[$i] = str_repeat('[list]', $list_close - $list_open) . $parts[$i];
if ($list_open - $list_close > 0)
$parts[$i] = $parts[$i] . str_repeat('[/list]', $list_open - $list_close);
// Make sure all tags are lowercase.
$parts[$i] = preg_replace('~\[([/]?)(list|li|table|tr|td)([^\]]*)\]~ie', '\'[$1\' . strtolower(\'$2\') . \'$3]\'', $parts[$i]);
$mistake_fixes = array(
// Find [table]s not followed by [tr].
'~\[table\](?![\s' . $non_breaking_space . ']*\[tr\])~s' . ($context['utf8'] ? 'u' : '') => '[table][tr]',
// Find [tr]s not followed by [td].
'~\[tr\](?![\s' . $non_breaking_space . ']*\[td\])~s' . ($context['utf8'] ? 'u' : '') => '[tr][td]',
// Find [/td]s not followed by something valid.
'~\[/td\](?![\s' . $non_breaking_space . ']*(?:\[td\]|\[/tr\]|\[/table\]))~s' . ($context['utf8'] ? 'u' : '') => '[/td][/tr]',
// Find [/tr]s not followed by something valid.
'~\[/tr\](?![\s' . $non_breaking_space . ']*(?:\[tr\]|\[/table\]))~s' . ($context['utf8'] ? 'u' : '') => '[/tr][/table]',
// Find [/td]s incorrectly followed by [/table].
'~\[/td\][\s' . $non_breaking_space . ']*\[/table\]~s' . ($context['utf8'] ? 'u' : '') => '[/td][/tr][/table]',
// Find [table]s, [tr]s, and [/td]s (possibly correctly) followed by [td].
'~\[(table|tr|/td)\]([\s' . $non_breaking_space . ']*)\[td\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_td_]',
// Now, any [td]s left should have a [tr] before them.
'~\[td\]~s' => '[tr][td]',
// Look for [tr]s which are correctly placed.
'~\[(table|/tr)\]([\s' . $non_breaking_space . ']*)\[tr\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_tr_]',
// Any remaining [tr]s should have a [table] before them.
'~\[tr\]~s' => '[table][tr]',
// Look for [/td]s followed by [/tr].
'~\[/td\]([\s' . $non_breaking_space . ']*)\[/tr\]~s' . ($context['utf8'] ? 'u' : '') => '[/td]$1[_/tr_]',
// Any remaining [/tr]s should have a [/td].
'~\[/tr\]~s' => '[/td][/tr]',
// Look for properly opened [li]s which aren't closed.
'~\[li\]([^\[\]]+?)\[li\]~s' => '[li]$1[_/li_][_li_]',
'~\[li\]([^\[\]]+?)$~s' => '[li]$1[/li]',
// Lists - find correctly closed items/lists.
'~\[/li\]([\s' . $non_breaking_space . ']*)\[/list\]~s' . ($context['utf8'] ? 'u' : '') => '[_/li_]$1[/list]',
// Find list items closed and then opened.
'~\[/li\]([\s' . $non_breaking_space . ']*)\[li\]~s' . ($context['utf8'] ? 'u' : '') => '[_/li_]$1[_li_]',
// Now, find any [list]s or [/li]s followed by [li].
'~\[(list(?: [^\]]*?)?|/li)\]([\s' . $non_breaking_space . ']*)\[li\]~s' . ($context['utf8'] ? 'u' : '') => '[$1]$2[_li_]',
// Any remaining [li]s weren't inside a [list].
'~\[li\]~' => '[list][li]',
// Any remaining [/li]s weren't before a [/list].
'~\[/li\]~' => '[/li][/list]',
// Put the correct ones back how we found them.
'~\[_(li|/li|td|tr|/tr)_\]~' => '[$1]',
);
// Fix up some use of tables without [tr]s, etc. (it has to be done more than once to catch it all.)
for ($j = 0; $j < 3; $j++)
$parts[$i] = preg_replace(array_keys($mistake_fixes), $mistake_fixes, $parts[$i]);
}
}
// Put it back together!
if (!$previewing)
$message = strtr(implode('', $parts), array(' ' => '&nbsp; ', "\n" => '<br />', $context['utf8'] ? "\xC2\xA0" : "\xA0" => '&nbsp;'));
else
$message = strtr(implode('', $parts), array(' ' => '&nbsp; ', $context['utf8'] ? "\xC2\xA0" : "\xA0" => '&nbsp;'));
// Now let's quickly clean up things that will slow our parser (which are common in posted code.)
$message = strtr($message, array('[]' => '&#91;]', '[&#039;' => '&#91;&#039;'));
}
// Fix any URLs posted - ie. remove 'javascript:'.
function fixTags(&$message)
{
global $modSettings;
// WARNING: Editing the below can cause large security holes in your forum.
// Edit only if you are sure you know what you are doing.
$fixArray = array(
// [img]http://...[/img] or [img width=1]http://...[/img]
array(
'tag' => 'img',
'protocols' => array('http', 'https'),
'embeddedUrl' => false,
'hasEqualSign' => false,
'hasExtra' => true,
),
// [url]http://...[/url]
array(
'tag' => 'url',
'protocols' => array('http', 'https'),
'embeddedUrl' => true,
'hasEqualSign' => false,
),
// [url=http://...]name[/url]
array(
'tag' => 'url',
'protocols' => array('http', 'https'),
'embeddedUrl' => true,
'hasEqualSign' => true,
),
// [iurl]http://...[/iurl]
array(
'tag' => 'iurl',
'protocols' => array('http', 'https'),
'embeddedUrl' => true,
'hasEqualSign' => false,
),
// [iurl=http://...]name[/iurl]
array(
'tag' => 'iurl',
'protocols' => array('http', 'https'),
'embeddedUrl' => true,
'hasEqualSign' => true,
),
// [ftp]ftp://...[/ftp]
array(
'tag' => 'ftp',
'protocols' => array('ftp', 'ftps'),
'embeddedUrl' => true,
'hasEqualSign' => false,
),
// [ftp=ftp://...]name[/ftp]
array(
'tag' => 'ftp',
'protocols' => array('ftp', 'ftps'),
'embeddedUrl' => true,
'hasEqualSign' => true,
),
// [flash]http://...[/flash]
array(
'tag' => 'flash',
'protocols' => array('http', 'https'),
'embeddedUrl' => false,
'hasEqualSign' => false,
'hasExtra' => true,
),
);
// Fix each type of tag.
foreach ($fixArray as $param)
fixTag($message, $param['tag'], $param['protocols'], $param['embeddedUrl'], $param['hasEqualSign'], !empty($param['hasExtra']));
// Now fix possible security problems with images loading links automatically...
$message = preg_replace('~(\[img.*?\])(.+?)\[/img\]~eis', '\'$1\' . preg_replace(\'~action(=|%3d)(?!dlattach)~i\', \'action-\', \'$2\') . \'[/img]\'', $message);
// Limit the size of images posted?
if (!empty($modSettings['max_image_width']) || !empty($modSettings['max_image_height']))
{
// Find all the img tags - with or without width and height.
preg_match_all('~\[img(\s+width=\d+)?(\s+height=\d+)?(\s+width=\d+)?\](.+?)\[/img\]~is', $message, $matches, PREG_PATTERN_ORDER);
$replaces = array();
foreach ($matches[0] as $match => $dummy)
{
// If the width was after the height, handle it.
$matches[1][$match] = !empty($matches[3][$match]) ? $matches[3][$match] : $matches[1][$match];
// Now figure out if they had a desired height or width...
$desired_width = !empty($matches[1][$match]) ? (int) substr(trim($matches[1][$match]), 6) : 0;
$desired_height = !empty($matches[2][$match]) ? (int) substr(trim($matches[2][$match]), 7) : 0;
// One was omitted, or both. We'll have to find its real size...
if (empty($desired_width) || empty($desired_height))
{
list ($width, $height) = url_image_size(un_htmlspecialchars($matches[4][$match]));
// They don't have any desired width or height!
if (empty($desired_width) && empty($desired_height))
{
$desired_width = $width;
$desired_height = $height;
}
// Scale it to the width...
elseif (empty($desired_width) && !empty($height))
$desired_width = (int) (($desired_height * $width) / $height);
// Scale if to the height.
elseif (!empty($width))
$desired_height = (int) (($desired_width * $height) / $width);
}
// If the width and height are fine, just continue along...
if ($desired_width <= $modSettings['max_image_width'] && $desired_height <= $modSettings['max_image_height'])
continue;
// Too bad, it's too wide. Make it as wide as the maximum.
if ($desired_width > $modSettings['max_image_width'] && !empty($modSettings['max_image_width']))
{
$desired_height = (int) (($modSettings['max_image_width'] * $desired_height) / $desired_width);
$desired_width = $modSettings['max_image_width'];
}
// Now check the height, as well. Might have to scale twice, even...
if ($desired_height > $modSettings['max_image_height'] && !empty($modSettings['max_image_height']))
{
$desired_width = (int) (($modSettings['max_image_height'] * $desired_width) / $desired_height);
$desired_height = $modSettings['max_image_height'];
}
$replaces[$matches[0][$match]] = '[img' . (!empty($desired_width) ? ' width=' . $desired_width : '') . (!empty($desired_height) ? ' height=' . $desired_height : '') . ']' . $matches[4][$match] . '[/img]';
}
// If any img tags were actually changed...
if (!empty($replaces))
$message = strtr($message, $replaces);
}
}
// Fix a specific class of tag - ie. url with =.
function fixTag(&$message, $myTag, $protocols, $embeddedUrl = false, $hasEqualSign = false, $hasExtra = false)
{
global $boardurl, $scripturl;
if (preg_match('~^([^:]+://[^/]+)~', $boardurl, $match) != 0)
$domain_url = $match[1];
else
$domain_url = $boardurl . '/';
$replaces = array();
if ($hasEqualSign)
preg_match_all('~\[(' . $myTag . ')=([^\]]*?)\](?:(.+?)\[/(' . $myTag . ')\])?~is', $message, $matches);
else
preg_match_all('~\[(' . $myTag . ($hasExtra ? '(?:[^\]]*?)' : '') . ')\](.+?)\[/(' . $myTag . ')\]~is', $message, $matches);
foreach ($matches[0] as $k => $dummy)
{
// Remove all leading and trailing whitespace.
$replace = trim($matches[2][$k]);
$this_tag = $matches[1][$k];
$this_close = $hasEqualSign ? (empty($matches[4][$k]) ? '' : $matches[4][$k]) : $matches[3][$k];
$found = false;
foreach ($protocols as $protocol)
{
$found = strncasecmp($replace, $protocol . '://', strlen($protocol) + 3) === 0;
if ($found)
break;
}
if (!$found && $protocols[0] == 'http')
{
if (substr($replace, 0, 1) == '/')
$replace = $domain_url . $replace;
elseif (substr($replace, 0, 1) == '?')
$replace = $scripturl . $replace;
elseif (substr($replace, 0, 1) == '#' && $embeddedUrl)
{
$replace = '#' . preg_replace('~[^A-Za-z0-9_\-#]~', '', substr($replace, 1));
$this_tag = 'iurl';
$this_close = 'iurl';
}
else
$replace = $protocols[0] . '://' . $replace;
}
elseif (!$found)
$replace = $protocols[0] . '://' . $replace;
if ($hasEqualSign && $embeddedUrl)
$replaces[$matches[0][$k]] = '[' . $this_tag . '=' . $replace . ']' . (empty($matches[4][$k]) ? '' : $matches[3][$k] . '[/' . $this_close . ']');
elseif ($hasEqualSign)
$replaces['[' . $matches[1][$k] . '=' . $matches[2][$k] . ']'] = '[' . $this_tag . '=' . $replace . ']';
elseif ($embeddedUrl)
$replaces['[' . $matches[1][$k] . ']' . $matches[2][$k] . '[/' . $matches[3][$k] . ']'] = '[' . $this_tag . '=' . $replace . ']' . $matches[2][$k] . '[/' . $this_close . ']';
else
$replaces['[' . $matches[1][$k] . ']' . $matches[2][$k] . '[/' . $matches[3][$k] . ']'] = '[' . $this_tag . ']' . $replace . '[/' . $this_close . ']';
}
foreach ($replaces as $k => $v)
{
if ($k == $v)
unset($replaces[$k]);
}
if (!empty($replaces))
$message = strtr($message, $replaces);
}
?>

40
ss_sources/random.php Executable file
View File

@ -0,0 +1,40 @@
<?php
/*
MoparScape.org server status page
Copyright (C) 2011 Travis Burtrum (moparisthebest)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('SS_PAGE'))
die('Hacking attempt...');
function random_page(){
mysql_con();
global $g_mysqli, $thispage;
$stmt = $g_mysqli->prepare("SELECT `ip` FROM `servers` WHERE `online` = ? ORDER BY RAND() LIMIT 1") or debug($g_mysqli->error);
$online = isset($_GET['offline']) ? 0 : 1;
$stmt->bind_param("i", $online);
$stmt->execute();
// bind result variables
$stmt->bind_result($rand_server);
$stmt->fetch();
$stmt->close();
close_mysql();
if(isset($_GET['offline']))
$rand_server .= "&offline";
header("Location: $thispage?server=$rand_server");
}
?>

277
ss_sources/recaptchalib.php Executable file
View File

@ -0,0 +1,277 @@
<?php
/*
* This is a PHP library that handles calling reCAPTCHA.
* - Documentation and latest version
* http://recaptcha.net/plugins/php/
* - Get a reCAPTCHA API Key
* https://www.google.com/recaptcha/admin/create
* - Discussion group
* http://groups.google.com/group/recaptcha
*
* Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net
* AUTHORS:
* Mike Crawford
* Ben Maurer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* The reCAPTCHA server URL's
*/
define("RECAPTCHA_API_SERVER", "http://www.google.com/recaptcha/api");
define("RECAPTCHA_API_SECURE_SERVER", "https://www.google.com/recaptcha/api");
define("RECAPTCHA_VERIFY_SERVER", "www.google.com");
/**
* Encodes the given data into a query string format
* @param $data - array of string elements to be encoded
* @return string - encoded request
*/
function _recaptcha_qsencode ($data) {
$req = "";
foreach ( $data as $key => $value )
$req .= $key . '=' . urlencode( stripslashes($value) ) . '&';
// Cut the last '&'
$req=substr($req,0,strlen($req)-1);
return $req;
}
/**
* Submits an HTTP POST to a reCAPTCHA server
* @param string $host
* @param string $path
* @param array $data
* @param int port
* @return array response
*/
function _recaptcha_http_post($host, $path, $data, $port = 80) {
$req = _recaptcha_qsencode ($data);
$http_request = "POST $path HTTP/1.0\r\n";
$http_request .= "Host: $host\r\n";
$http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
$http_request .= "Content-Length: " . strlen($req) . "\r\n";
$http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
$http_request .= "\r\n";
$http_request .= $req;
$response = '';
if( false == ( $fs = @fsockopen($host, $port, $errno, $errstr, 10) ) ) {
die ('Could not open socket');
}
fwrite($fs, $http_request);
while ( !feof($fs) )
$response .= fgets($fs, 1160); // One TCP-IP packet
fclose($fs);
$response = explode("\r\n\r\n", $response, 2);
return $response;
}
/**
* Gets the challenge HTML (javascript and non-javascript version).
* This is called from the browser, and the resulting reCAPTCHA HTML widget
* is embedded within the HTML form it was called from.
* @param string $pubkey A public key for reCAPTCHA
* @param string $error The error given by reCAPTCHA (optional, default is null)
* @param boolean $use_ssl Should the request be made over ssl? (optional, default is false)
* @return string - The HTML to be embedded in the user's form.
*/
function recaptcha_get_html ($pubkey, $error = null, $use_ssl = false)
{
if ($pubkey == null || $pubkey == '') {
die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
}
if ($use_ssl) {
$server = RECAPTCHA_API_SECURE_SERVER;
} else {
$server = RECAPTCHA_API_SERVER;
}
$errorpart = "";
if ($error) {
$errorpart = "&amp;error=" . $error;
}
return '<script type="text/javascript" src="'. $server . '/challenge?k=' . $pubkey . $errorpart . '"></script>
<noscript>
<iframe src="'. $server . '/noscript?k=' . $pubkey . $errorpart . '" height="300" width="500" frameborder="0"></iframe><br/>
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>
</noscript>';
}
/**
* A ReCaptchaResponse is returned from recaptcha_check_answer()
*/
class ReCaptchaResponse {
var $is_valid;
var $error;
}
/**
* Calls an HTTP POST function to verify if the user's guess was correct
* @param string $privkey
* @param string $remoteip
* @param string $challenge
* @param string $response
* @param array $extra_params an array of extra variables to post to the server
* @return ReCaptchaResponse
*/
function recaptcha_check_answer ($privkey, $remoteip, $challenge, $response, $extra_params = array())
{
if ($privkey == null || $privkey == '') {
die ("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");
}
if ($remoteip == null || $remoteip == '') {
die ("For security reasons, you must pass the remote ip to reCAPTCHA");
}
//discard spam submissions
if ($challenge == null || strlen($challenge) == 0 || $response == null || strlen($response) == 0) {
$recaptcha_response = new ReCaptchaResponse();
$recaptcha_response->is_valid = false;
$recaptcha_response->error = 'incorrect-captcha-sol';
return $recaptcha_response;
}
$response = _recaptcha_http_post (RECAPTCHA_VERIFY_SERVER, "/recaptcha/api/verify",
array (
'privatekey' => $privkey,
'remoteip' => $remoteip,
'challenge' => $challenge,
'response' => $response
) + $extra_params
);
$answers = explode ("\n", $response [1]);
$recaptcha_response = new ReCaptchaResponse();
if (trim ($answers [0]) == 'true') {
$recaptcha_response->is_valid = true;
}
else {
$recaptcha_response->is_valid = false;
$recaptcha_response->error = $answers [1];
}
return $recaptcha_response;
}
/**
* gets a URL where the user can sign up for reCAPTCHA. If your application
* has a configuration page where you enter a key, you should provide a link
* using this function.
* @param string $domain The domain where the page is hosted
* @param string $appname The name of your application
*/
function recaptcha_get_signup_url ($domain = null, $appname = null) {
return "https://www.google.com/recaptcha/admin/create?" . _recaptcha_qsencode (array ('domains' => $domain, 'app' => $appname));
}
function _recaptcha_aes_pad($val) {
$block_size = 16;
$numpad = $block_size - (strlen ($val) % $block_size);
return str_pad($val, strlen ($val) + $numpad, chr($numpad));
}
/* Mailhide related code */
function _recaptcha_aes_encrypt($val,$ky) {
if (! function_exists ("mcrypt_encrypt")) {
die ("To use reCAPTCHA Mailhide, you need to have the mcrypt php module installed.");
}
$mode=MCRYPT_MODE_CBC;
$enc=MCRYPT_RIJNDAEL_128;
$val=_recaptcha_aes_pad($val);
return mcrypt_encrypt($enc, $ky, $val, $mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
}
function _recaptcha_mailhide_urlbase64 ($x) {
return strtr(base64_encode ($x), '+/', '-_');
}
/* gets the reCAPTCHA Mailhide url for a given email, public key and private key */
function recaptcha_mailhide_url($pubkey, $privkey, $email) {
if ($pubkey == '' || $pubkey == null || $privkey == "" || $privkey == null) {
die ("To use reCAPTCHA Mailhide, you have to sign up for a public and private key, " .
"you can do so at <a href='http://www.google.com/recaptcha/mailhide/apikey'>http://www.google.com/recaptcha/mailhide/apikey</a>");
}
$ky = pack('H*', $privkey);
$cryptmail = _recaptcha_aes_encrypt ($email, $ky);
return "http://www.google.com/recaptcha/mailhide/d?k=" . $pubkey . "&c=" . _recaptcha_mailhide_urlbase64 ($cryptmail);
}
/**
* gets the parts of the email to expose to the user.
* eg, given johndoe@example,com return ["john", "example.com"].
* the email is then displayed as john...@example.com
*/
function _recaptcha_mailhide_email_parts ($email) {
$arr = preg_split("/@/", $email );
if (strlen ($arr[0]) <= 4) {
$arr[0] = substr ($arr[0], 0, 1);
} else if (strlen ($arr[0]) <= 6) {
$arr[0] = substr ($arr[0], 0, 3);
} else {
$arr[0] = substr ($arr[0], 0, 4);
}
return $arr;
}
/**
* Gets html to display an email address given a public an private key.
* to get a key, go to:
*
* http://www.google.com/recaptcha/mailhide/apikey
*/
function recaptcha_mailhide_html($pubkey, $privkey, $email) {
$emailparts = _recaptcha_mailhide_email_parts ($email);
$url = recaptcha_mailhide_url ($pubkey, $privkey, $email);
return htmlentities($emailparts[0]) . "<a href='" . htmlentities ($url) .
"' onclick=\"window.open('" . htmlentities ($url) . "', '', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=500,height=300'); return false;\" title=\"Reveal this e-mail address\">...</a>@" . htmlentities ($emailparts [1]);
}
?>

628
ss_sources/register.php Executable file
View File

@ -0,0 +1,628 @@
<?php
/*
MoparScape.org server status page
Copyright (C) 2011 Travis Burtrum (moparisthebest)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('SS_PAGE'))
die('Hacking attempt...');
function register2(){
forceLogin('register');
// error('this is register2');
// preview is set, refer to echoPostForm()
if(isset($_POST['preview'])){
echoPostForm();
return;
}
// neither preview or post is set, probably hacking attempt
// but let's say something nicer instead
if(!isset($_POST['post'])){
error('Session expired, go back and try again');
return;
}
// if we get here, post is set, verify the rest of the info
// verify user input
$requiredPosts = array('name', 'ip', 'port', 'version', 'message');
foreach($requiredPosts as $r){
if(!isset($_POST[$r])){
error("You must provide a $r.");
echoPostForm();
return;
}
}
$name = trim($_POST['name']);
$ip = trim($_POST['ip']);
$port = trim($_POST['port']);
$version = trim($_POST['version']);
$message = trim($_POST['message']);
$pic_url = trim($_POST['pic_url']);
// if the info isn't valid, set up a preview instead
if(!verifyInput($name, $ip, $port, $version, $message, $pic_url, isset($_POST['edit']))){
echoPostForm();
return;
}
// if we make it here, then all the input is valid
// connect to the db and set the edit and spons variables
$edit = false;
$spons = false;
mysql_con();
global $g_mysqli, $uid;
$stmt = $g_mysqli->prepare('SELECT `sponsored` FROM `servers` WHERE `uid` = ? LIMIT 1') or debug($g_mysqli->error);
$stmt->bind_param("i", $uid);
$stmt->execute();
// bind result variables
$stmt->bind_result($sponsored);
if($stmt->fetch()){
$edit = true;
$spons = ($sponsored > 0);
}
$stmt->close();
// enter into database
// if it isn't a sponsored server, they can't have a picture
if (!$spons)
$pic_url = '';
if ($edit){
$sql = 'UPDATE `servers` SET `name` = ?, `pic_url` = ?, `version` = ?, `info` = ? WHERE `uid` = ? LIMIT 1';
$stmt = $g_mysqli->prepare($sql) or debug($g_mysqli->error);
$stmt->bind_param("ssisi", $name, $pic_url, $version, $message, $uid);
$success_msg = "Server $name succesfully updated.";
$fail_msg = "Editing $name failed, did you actually change anything?";
}else{
// since we are adding a new server, need to make sure it isn't already added, user isn't banned etc
// make sure it's not already scheduled to be added
if (checkRows("SELECT `id` FROM `toadd` WHERE `ip` = ? OR `uid` = ?", 'si', $ip, $uid)) {
error("This server has already been posted, but not yet approved, have some patience!.");
return;
}
// make sure user and IP is not banned
if (checkRows("SELECT `id` FROM `banned` WHERE `ip` = ? OR `uid` = ?", 'si', $ip, $uid)) {
error("This server has been banned, contact moparisthebest on the forums for assistance.");
return;
}
// we know another server hasn't been posted by this user, because we would be in edit
// but this ip may have been posted by another user, check to make sure
if (checkRows("SELECT `id` FROM `servers` WHERE `ip` = ?", 's', $ip)) {
error("This server has already been posted, you may not post it again.");
return;
}
global $g_allowed_key;
//die('$g_allowed_key: '.$g_allowed_key);
$key = randString($g_allowed_key, 5, 10);
$rs_name = randString($g_allowed_key);
$rs_pass = randString($g_allowed_key);
$verified = 1;
if(!verifyIP($ip, &$resolved_ip, &$remote_ip)){
$verified = 0;
global $thispage;
$verify_url = $thispage."?action=verify&amp;server=$ip&amp;key=$key";
$verify_msg = "<br />The server you posted, $ip, resolves to $resolved_ip, which does not match your ip, $remote_ip.\n<br />
This means that you must verify that you own this IP by visiting this URL from the IP that you posted.<br />
If you have a browser on the machine, simply visit the following URL:<br />
<a href=\"$verify_url\">$verify_url</a><br />
If you only have a command line, visit the URL with wget, curl, or an equivalent command to this:<br />
<div class=\"codeheader\">Code:</div><div class=\"code\"><pre style=\"margin-top: 0; display: inline;\">wget -O- -q \"$verify_url\"</pre></div><br />
The message you recieve will tell you if verification was successful.<br />
If you have problems with this, PM Moparisthebest on the forums.";
}
global $uname;
// don't bother with pic_url, they can edit it if they are sponsored
$sql = 'INSERT INTO `toadd` (`uid`, `uname`, `name`, `ip`, `port`, `version`, `time`, `info`, `ipaddress`, `rs_name`, `rs_pass`, `key`, `verified`) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
$stmt = $g_mysqli->prepare($sql) or debug($g_mysqli->error);
$stmt->bind_param("isssiiisssssi", $uid, $uname, $name, $ip, $port, $version, time(), $message, $_SERVER['REMOTE_ADDR'], $rs_name, $rs_pass, $key, $verified);
$success_msg = "<strong class=\"largetext error\">Further Action Required, Read:</strong><br />New server $name succesfully entered, however it will not show up on the list until it has been verified and approved.<br /> Your server will now be checked by logging into it with the following credentials:\n<br />
Username: <strong class=\"highlight\">$rs_name</strong>\n<br />
Password: <strong class=\"highlight\">$rs_pass</strong>\n<br />
to make sure it is online, and if successful, it will be posted. <br />
You must register this username and password for me on your server and allow it to be logged into from the IP 69.39.224.55<br />
The server will be deleted from the queue if not verified and logged into within 24 hours of posting.<br />".$verify_msg;
$fail_msg = 'Registration failed, PM <a href="http://www.moparscape.org/smf/index.php?action=profile;u=1">Moparisthebest</a> on the forums to with details so he can fix it.';
}
// execute the query
$stmt->execute();
if ($stmt->affected_rows == 1) {
echo $success_msg;
}else{
error($fail_msg);
}
$stmt->close();
close_mysql();
}
function register(){
forceLogin();
// echo "this is register<br />\n";
$edit = false;
// then we are trying to edit a server
// load the proper values from the database
if(isset($_GET['edit'])){
mysql_con();
global $g_mysqli, $uid;
$stmt = $g_mysqli->prepare('SELECT `name`, `ip`, `port`, `version`, `info`, `pic_url`, `sponsored` FROM `servers` WHERE `uid` = ? LIMIT 1') or debug($g_mysqli->error);
$stmt->bind_param("i", $uid);
$stmt->execute();
// bind result variables
$stmt->bind_result($name, $ip, $port, $version, $info, $pic_url, $sponsored);
if(!$stmt->fetch()){
error('You have not posted a server, but you may register a new one instead.<br />');
return;
}
$edit = true;
$stmt->close();
close_mysql();
if($sponsored == 0)
unset($pic_url);
}
/* if($edit)
echo 'edit true';
else
echo 'edit false';
*/ echoForm($name, $ip, $port, $version, $info, $pic_url, $edit);
}
// returns true if input is valid
// prints out a message and returns false otherwise
function verifyInput($name, $ip, $port, $version, $info, $pic_url, $edit){
global $g_allowed_url, $g_allowed_alpha, $g_allowed_dns, $g_versions;
// validate name
$namelen = strlen($name);
if ($namelen > 25 || $namelen < 1) {
error("The name cannot exceed 25 characters, and must be at least one.<br />");
return false;
}
if (!isAllowed($name, $g_allowed_alpha)) {
error("The name can only contain the following characters:<br />$g_allowed_alpha<br /><br />");
return false;
}
// only bother with ip and port if we are not editing, don't care about permissions because it will
// only be entered into the database if they are actually posting a new server and not editing
if(!$edit){
// validate ip
if (strlen($ip) < 6) {
error("The ip must be at least 6 characters.<br />");
return false;
}
if (!isAllowed($ip, $g_allowed_dns)) {
error("The ip can only contain the following characters:<br />$g_allowed_dns<br /><br />");
return false;
}
if ($ip[0] == '.' || $ip[strlen($ip)-1] == '.') {
error("The ip cannot start or begin with a period.<br />");
return false;
}
//validate port
if ($port > 65535 || $port < 1) {
error("Please enter a valid port number between 1 and 65534.<br />");
return false;
}
// now that the ip and port are validated, check to make sure the server is online
$fp = @fsockopen($ip, $port, $errno, $errstr, 4);
if (!$fp) {
error("The server " . $name . " is offline, it must be online before you can register it here.");
return false;
}
fclose($fp);
}
// validate info
$info_len = strlen($info);
if ($info_len > 10000) {
error("The info cannot exceed 10,000 characters. You currently have $info_len characters.");
return false;
}
// validate version
if (!in_array($version, $g_versions)) {
// they must be hackers, since the select box only contains values from $g_versions
error("The version must be one of the supported versions.<br />");
return false;
}
// validate picture, again don't care about permissions because it will
// only be entered into the database if they are sponsored
$piclen = strlen($pic_url);
if ($piclen > 0){
$ext = strtolower(substr($pic_url, $piclen-3, $piclen));
if($ext == 'gif') {
error("The picture cannot be of type gif.<br />");
return false;
}
if (!isAllowed($pic_url, $g_allowed_url)) {
error("The picture can only contain the following characters:<br />$g_allowed_url<br /><br />");
return false;
}
}
// we have passed through all the trials, return true
return true;
}
function echoPostForm($edit = null){
if($edit == null)
$edit = isset($_POST['edit']);
else
$edit = false;
echoForm($_POST['name'], $_POST['ip'], $_POST['port'], $_POST['version'], $_POST['message'], $_POST['pic_url'], $edit);
}
function echoForm($name, $ip, $port, $version, $message, $pic_url, $edit = false){
global $g_versions;
if(isset($name))
censorText($name);
$preview_message = $message;
if(isset($preview_message)){
// Do all bulletin board code tags, with smileys.
$preview_message = bb2html($preview_message, true);
}
?>
<script type="text/javascript" src="script.js"></script>
<div class="post"<?php echo (isset($preview_message) ? '' : ' style="display: none;"'); ?>>
<?php echo $preview_message; ?>
</div>
<form action="<?php echo actionURL('register2'); ?>" method="post" id="postmodify" onsubmit="submitonce(this);saveEntities();" enctype="multipart/form-data" style="margin: 0;">
<fieldset>
<table class="other" summary="Register your Server">
<caption>
Register Server
</caption>
<thead>
<tr>
<td colspan="2">
<div class="title">Rules</div>
<ul style="margin: 0px 5px 5px 25px;">
<li>The server must be <b>online</b> to add it to the status list.</li>
<li>Selling admin or mod spots on your server is <b>against the rules</b> and will result in a ban, here, and on the
forums.</li>
</ul>
</td>
</tr>
</thead>
<tbody>
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name; ?>" /></td>
</tr>
<?php
if (isset($pic_url)){
?>
<tr>
<td>Picture</td>
<td><input type="text" name="pic_url" value="<?php echo $pic_url; ?>" /></td>
</tr>
<?php
}
if (!$edit){
?>
<tr class="odd">
<td>IP</td>
<td><input type="text" name="ip" value="<?php echo $ip; ?>" /></td>
</tr>
<tr>
<td>Port</td>
<td><input type="text" name="port" value="<?php echo (isset($port) ? $port : '43594'); ?>" /></td>
</tr>
<?php
}
?>
<tr class="odd">
<td>Version</td>
<td><select name="version">
<?php
$v_template = "<option>%d</option>\n";
if(isset($version))
printf($v_template, $version);
foreach($g_versions as $v)
printf($v_template, $v);
?>
</select></td>
</tr>
<tr>
<td colspan="2">Info</td>
</tr>
</tbody>
</table>
<table border="0" width="100%" cellspacing="1" cellpadding="3" class="smf_edit">
<tr>
<td align="right"></td>
<td valign="middle">
<a href="javascript:void(0);" onclick=
"surroundText('[b]', '[/b]', document.forms.postmodify.message); return false;"><img onmouseover="bbc_highlight(this, true);"
onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/bold.gif" width="23" height="22" alt="Bold" title=
"Bold" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[i]', '[/i]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/italicize.gif" width="23" height="22" alt=
"Italicized" title="Italicized" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[u]', '[/u]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/underline.gif" width="23" height="22" alt=
"Underline" title="Underline" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[s]', '[/s]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/strike.gif" width="23" height="22" alt=
"Strikethrough" title="Strikethrough" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><img src="http://www.moparscape.org/images/bbc/divider.gif"
alt="|" style="margin: 0 3px 0 3px;" /><a href="javascript:void(0);" onclick=
"surroundText('[shadow=red,left]', '[/shadow]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/shadow.gif" width="23" height="22" alt="Shadow"
title="Shadow" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><img src="http://www.moparscape.org/images/bbc/divider.gif"
alt="|" style="margin: 0 3px 0 3px;" /><a href="javascript:void(0);" onclick=
"surroundText('[pre]', '[/pre]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/pre.gif" width="23" height="22" alt=
"Preformatted Text" title="Preformatted Text" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[left]', '[/left]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/left.gif" width="23" height="22" alt="Left Align"
title="Left Align" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[center]', '[/center]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/center.gif" width="23" height="22" alt="Centered"
title="Centered" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[right]', '[/right]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/right.gif" width="23" height="22" alt=
"Right Align" title="Right Align" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><img src="http://www.moparscape.org/images/bbc/divider.gif"
alt="|" style="margin: 0 3px 0 3px;" /><a href="javascript:void(0);" onclick=
"replaceText('[hr]', document.forms.postmodify.message); return false;"><img onmouseover="bbc_highlight(this, true);"
onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/hr.gif" width="23" height="22" alt=
"Horizontal Rule" title="Horizontal Rule" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><img src="http://www.moparscape.org/images/bbc/divider.gif"
alt="|" style="margin: 0 3px 0 3px;" /><a href="javascript:void(0);" onclick=
"surroundText('[size=10pt]', '[/size]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/size.gif" width="23" height="22" alt="Font Size"
title="Font Size" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[font=Verdana]', '[/font]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/face.gif" width="23" height="22" alt="Font Face"
title="Font Face" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a>
<select onchange=
"surroundText('[color=' + this.options[this.selectedIndex].value.toLowerCase() + ']', '[/color]', document.forms.postmodify.message); this.selectedIndex = 0; document.forms.postmodify.message.focus(document.forms.postmodify.message.caretPos);"
style="margin-bottom: 1ex;">
<option value="" selected="selected">
Change Color
</option>
<option value="Black">
Black
</option>
<option value="Red">
Red
</option>
<option value="Yellow">
Yellow
</option>
<option value="Pink">
Pink
</option>
<option value="Green">
Green
</option>
<option value="Orange">
Orange
</option>
<option value="Purple">
Purple
</option>
<option value="Blue">
Blue
</option>
<option value="Beige">
Beige
</option>
<option value="Brown">
Brown
</option>
<option value="Teal">
Teal
</option>
<option value="Navy">
Navy
</option>
<option value="Maroon">
Maroon
</option>
<option value="LimeGreen">
Lime Green
</option>
</select><br />
<a href="javascript:void(0);" onclick=
"surroundText('[img]', '[/img]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/img.gif" width="23" height="22" alt="Insert Image"
title="Insert Image" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[url]', '[/url]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/url.gif" width="23" height="22" alt=
"Insert Hyperlink" title="Insert Hyperlink" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[email]', '[/email]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/email.gif" width="23" height="22" alt=
"Insert Email" title="Insert Email" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[ftp]', '[/ftp]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/ftp.gif" width="23" height="22" alt=
"Insert FTP Link" title="Insert FTP Link" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><img src="http://www.moparscape.org/images/bbc/divider.gif"
alt="|" style="margin: 0 3px 0 3px;" /><a href="javascript:void(0);" onclick=
"surroundText('[table]', '[/table]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/table.gif" width="23" height="22" alt=
"Insert Table" title="Insert Table" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[tr]', '[/tr]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/tr.gif" width="23" height="22" alt=
"Insert Table Row" title="Insert Table Row" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[td]', '[/td]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/td.gif" width="23" height="22" alt=
"Insert Table Column" title="Insert Table Column" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><img src="http://www.moparscape.org/images/bbc/divider.gif"
alt="|" style="margin: 0 3px 0 3px;" /><a href="javascript:void(0);" onclick=
"surroundText('[sup]', '[/sup]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/sup.gif" width="23" height="22" alt="Superscript"
title="Superscript" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[sub]', '[/sub]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/sub.gif" width="23" height="22" alt="Subscript"
title="Subscript" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[tt]', '[/tt]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/tele.gif" width="23" height="22" alt="Teletype"
title="Teletype" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><img src="http://www.moparscape.org/images/bbc/divider.gif"
alt="|" style="margin: 0 3px 0 3px;" /><a href="javascript:void(0);" onclick=
"surroundText('[code]', '[/code]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/code.gif" width="23" height="22" alt="Insert Code"
title="Insert Code" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><a href="javascript:void(0);"
onclick="surroundText('[quote]', '[/quote]', document.forms.postmodify.message); return false;"><img onmouseover=
"bbc_highlight(this, true);" onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/quote.gif" width="23" height="22" alt=
"Insert Quote" title="Insert Quote" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a><img src="http://www.moparscape.org/images/bbc/divider.gif"
alt="|" style="margin: 0 3px 0 3px;" /><a href="javascript:void(0);" onclick=
"surroundText('[list]\n[li]', '[/li]\n[li][/li]\n[/list]', document.forms.postmodify.message); return false;"><img onmouseover="bbc_highlight(this, true);"
onmouseout="if (window.bbc_highlight) bbc_highlight(this, false);" src=
"http://www.moparscape.org/images/bbc/list.gif" width="23" height="22" alt="Insert List"
title="Insert List" style=
"background-image: url(http://www.moparscape.org/images/bbc/bbc_bg.gif); margin: 1px 2px 1px 1px;" /></a>
</td>
</tr>
<tr>
<td align="right"></td>
<td valign="middle"><a href="javascript:void(0);" onclick=
"replaceText(' :)', document.forms.postmodify.message); return false;"><img src=
"http://www.moparisthebest.com/smf/Smileys/vb/smile.gif" alt="Smiley" title="Smiley" /></a> <a href=
"javascript:void(0);" onclick="replaceText(' ;)', document.forms.postmodify.message); return false;"><img src=
"http://www.moparisthebest.com/smf/Smileys/vb/wink.gif" alt="Wink" title="Wink" /></a> <a href=
"javascript:void(0);" onclick="replaceText(' :D', document.forms.postmodify.message); return false;"><img src=
"http://www.moparisthebest.com/smf/Smileys/vb/biggrin.gif" alt="Big Grin" title="Big Grin" /></a> <a href=
"javascript:void(0);" onclick="replaceText(' :mad:', document.forms.postmodify.message); return false;"><img src=
"http://www.moparisthebest.com/smf/Smileys/vb/mad.gif" alt="Mad" title="Mad" /></a> <a href="javascript:void(0);"
onclick="replaceText(' :(', document.forms.postmodify.message); return false;"><img src=
"http://www.moparisthebest.com/smf/Smileys/vb/frown.gif" alt="Sad" title="Sad" /></a> <a href=
"javascript:void(0);" onclick="replaceText(' :eek:', document.forms.postmodify.message); return false;"><img src=
"http://www.moparisthebest.com/smf/Smileys/vb/eek.gif" alt="Shocked" title="Shocked" /></a> <a href=
"javascript:void(0);" onclick="replaceText(' :cool:', document.forms.postmodify.message); return false;"><img src=
"http://www.moparisthebest.com/smf/Smileys/vb/cool.gif" alt="Cool" title="Cool" /></a> <a href=
"javascript:void(0);" onclick="replaceText(' :rolleyes:', document.forms.postmodify.message); return false;"><img src=
"http://www.moparisthebest.com/smf/Smileys/vb/rolleyes.gif" alt="Roll Eyes" title="Roll Eyes" /></a> <a href=
"javascript:void(0);" onclick="replaceText(' :P', document.forms.postmodify.message); return false;"><img src=
"http://www.moparisthebest.com/smf/Smileys/vb/tongue.gif" alt="Tongue" title="Tongue" /></a> <a href=
"javascript:void(0);" onclick="replaceText(' :o', document.forms.postmodify.message); return false;"><img src=
"http://www.moparisthebest.com/smf/Smileys/vb/redface.gif" alt="Embarrassed" title="Embarrassed" /></a> <a href=
"javascript:void(0);" onclick="replaceText(' :confused:', document.forms.postmodify.message); return false;"><img src=
"http://www.moparisthebest.com/smf/Smileys/vb/confused.gif" alt="Confused" title="Confused" /></a> <a href=
"javascript:void(0);" onclick="replaceText(' :|', document.forms.postmodify.message); return false;"><img src=
"http://www.moparisthebest.com/smf/Smileys/vb/shifty.gif" alt="shifty" title="shifty" /></a> <a href=
"javascript:void(0);" onclick="replaceText(' ;D', document.forms.postmodify.message); return false;"><img src=
"http://www.moparisthebest.com/smf/Smileys/vb/winkgrin.gif" alt="winksmile" title="winksmile" /></a></td>
</tr>
<tr>
<td valign="top" align="right"></td>
<td>
<textarea class="editor" name="message" rows="12" cols="60" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup=
"storeCaret(this);" onchange="storeCaret(this);" tabindex="2">
<?php echo $message; ?>
</textarea></td>
</tr>
<tr>
<td align="center" colspan="2">
<?php
if ($edit){
?>
<input type="hidden" name="edit" value="1" />
<input type="hidden" name="ip" value="<?php echo $ip; ?>" />
<input type="hidden" name="port" value="<?php echo (isset($port) ? $port : '43594'); ?>" />
<?php
}
?>
<input type="submit" name="post" value="<?php echo $edit ? 'Edit' : 'Register'; ?> Server" tabindex="3" onclick="return submitThisOnce(this);" accesskey="s" /> <input type=
"submit" name="preview" value="Preview Info" tabindex="4" onclick="return event.ctrlKey || previewPost();" accesskey="p" /></td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
</table>
</fieldset>
</form>
<?php
}
?>

178
ss_sources/search.php Executable file
View File

@ -0,0 +1,178 @@
<?php
/*
MoparScape.org server status page
Copyright (C) 2011 Travis Burtrum (moparisthebest)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('SS_PAGE'))
die('Hacking attempt...');
function search(){
forceLogin();
$chk_template = "\t\t".'<input type="checkbox" checked="checked" name="versions[]" value="%d" /> %d <br />'."\n";
global $g_versions;
echo "Enter your search terms.<br />";
?>
<script type="text/javascript">
//<![CDATA[
<!--
function toggle(source) {
checkboxes = document.getElementsByName('versions[]');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
//-->
//]]>
</script>
<form action="<?php echo actionURL('search2'); ?>" method="post" enctype="multipart/form-data" style="margin: 0;">
<fieldset style="margin: 0;">
<input type="text" name="query" value="<?php echo $_POST['query']; ?>" /><br /><br />
Version:<br />
<?php
foreach($g_versions as $v)
printf($chk_template, $v, $v);
?>
<br />
<input type="checkbox" checked="checked" onClick="toggle(this)" /> Check All<br/>
<br />
<input type="submit" name="submit" value="Search" accesskey="s" />
</fieldset>
</form>
<?php
}
function search2(){
forceLogin();
global $uid, $uname, $thispage, $time_format, $time_offset, $g_mysqli, $g_versions;
//wait time in seconds to search again
$wait_time = 20;
$query = $_POST['query'];
if($query == ""){
error("You must type something to search for!<br />");
search();
return;
}
$versions = $_POST['versions'];
// print_r($versions);
// echo '<br />';
// print_r($g_versions);
// echo '<br />';
// print_r(array_diff($versions, $g_versions));
if(count($versions) == 0 || count(array_diff($versions, $g_versions)) != 0){
error("You must specify a valid version!<br />");
search();
return;
}
// we checked out so far, make sure they haven't searched in the set amount of time
$threshold = time()-$wait_time;
// first check the session variable, since it is cheaper than a query
if(isset($_SESSION['last_search']) && $_SESSION['last_search'] > $threshold){
echo "You have searched within the last $wait_time seconds, you may do this again in ".($_SESSION['last_search']-$threshold).' seconds.<br />';
return;
}
// do processing on $query
// get your sphinx on
require_once('sphinxapi.php');
$cl = new SphinxClient();
$cl->SetServer( "localhost", 9312 );
$cl->SetLimits(0, 6000);
$cl->SetMatchMode( SPH_MATCH_ANY );
$cl->SetFilter('version', $versions);
// clean a dirty query
$query = clean_word_sphinx($query, $cl);
//echo "<br />query: ".$query."<br />";
$result = $cl->Query( $query, 'sstat_index' );
if ( $result === false ) {
error("Query failed: " . $cl->GetLastError() . ".\n");
return;
}
if ( $cl->GetLastWarning() ) {
echo "WARNING (not an error!): " . $cl->GetLastWarning();
}
// if there weren't any matches, say so
if (empty($result["matches"])) {
error("No results for that query.");
return;
}
// then it's successfull, set it up
$_SESSION['last_search_results'] = implode(",", array_keys($result["matches"]));
$_SESSION['last_search_total'] = $result['total'];
//echo "<br />implode: ".$_SESSION['last_search_results']."<br />";
//echo "num results: ".$_SESSION['last_search_total']."<br />";
//echo "count: ".count($result["matches"])."<br />";
//foreach ( $result["matches"] as $doc => $docinfo )
// echo "$doc\n";
//print_r( $result );
search3();
$_SESSION['last_search'] = time();
}
function search3(){
forceLogin();
if(!isset($_SESSION['last_search_results']) || !isset($_SESSION['last_search_total'])){
search();
return;
}
// then we are in business
require_once('display.php');
// online is 2 for searches
display_table(2, "`id` IN (".$_SESSION['last_search_results'].")", $_SESSION['last_search_total']);
}
// Clean up a search word/phrase/term for Sphinx (from SMF)
function clean_word_sphinx($sphinx_term, $sphinx_client)
{
// Multiple quotation marks in a row can cause fatal errors, so handle them
$sphinx_term = preg_replace('/""+/', '"', $sphinx_term);
// Unmatched (i.e. odd number of) quotation marks also cause fatal errors, so handle them
if (substr_count($sphinx_term, '"') % 2)
// Using preg_replace since it supports limiting the number of replacements
$sphinx_term = preg_replace('/"/', '', $sphinx_term, 1);
// Use the Sphinx API's built-in EscapeString function to escape special characters
$sphinx_term = $sphinx_client->EscapeString($sphinx_term);
// Since it escapes quotation marks and we don't want that, unescape them
$sphinx_term = str_replace('\"', '"', $sphinx_term);
return $sphinx_term;
}
?>

1626
ss_sources/sphinxapi.php Executable file

File diff suppressed because it is too large Load Diff

481
ss_sources/util.php Executable file
View File

@ -0,0 +1,481 @@
<?php
/*
MoparScape.org server status page
Copyright (C) 2011 Travis Burtrum (moparisthebest)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//die('disabled for a moment, upgrading the page...');
if (!defined('SS_PAGE'))
die('Hacking attempt...');
$thispage = 'http'.(isset($_SERVER['HTTPS']) ? 's' : '').'://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
function doSetup(){
global $g_mysqli, $g_allowed_url, $g_allowed_alpha, $g_allowed_key, $g_allowed_dns, $thispage, $g_versions, $g_login_check;
$g_allowed_url = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ /-:.%0123456789";
$g_allowed_alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789- ";
$g_allowed_key = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$g_allowed_dns = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.";
$g_versions = array(317, 508);
define('MSCP', 1);
global $forumid;
$forumid = 1;
require_once('/path/to/smf/SSI.php');
global $user_info;
$user = ssi_welcome('array');
// vars from SMF that we use, for easy compatibility for future versions
global $groups, $time_format, $time_offset, $is_admin, $is_guest, $uname, $uid;
$groups = $user_info['groups'];
$time_format = $user_info['time_format'];
# this is the number of seconds to add to time()
$time_offset = $user_info['time_offset']*3600;
$is_admin = $user['is_admin'] || $groups[0] == 2 || $groups[0] == 63 || in_array(70, $groups);
$is_guest = $user['is_guest'];
$uname = $user['name'];
$uid = $user['id'];
}
function error($s){
info($s, 'Error');
}
function info($s, $header='Very Important'){
echo '
<div style="margin: 2ex; padding: 2ex; border: 2px dashed #cc3344; color: black; background-color: #ffe4e9;">
<div style="float: left; width: 2ex; font-size: 2em; color: red;">!!</div>
<b style="text-decoration: underline;">'.$header.':</b><br />
<div style="padding-left: 6ex;">
'.$s.'
</div>
</div>';
}
function debug($s){
die('error: '.$s);
}
function forward($url = null){
if($url == null){
global $thispage;
$url = $thispage;
}
close_mysql();
header("Location: $url");
exit;
}
function randString($allowed, $min_length = 4, $max_length = 8){
$allowed_len = strlen($allowed);
$length = mt_rand($min_length,$max_length);
$ret = '';
for($x = 0; $x < $length; ++$x)
$ret .= $allowed[mt_rand(0, $allowed_len)];
return $ret;
}
function actionURL($action){
global $thispage;
return $thispage.'?action='.$action;
}
function can_mod(){
global $is_admin;
return $is_admin;
}
function forceAdmin(){
global $is_admin;
if(!$is_admin)
forward();
}
function forceLogin($action = null){
global $g_login_check;
// then we already checked
if(isset($g_login_check))
return;
$g_login_check = 1;
global $is_guest;
if ($is_guest){
global $thispage;
if($action != null)
$thisurl = $thispage.'?action='.$action;
else
$thisurl = $thispage.'?'.$_SERVER['QUERY_STRING'];
echo 'Enter your forum username and password to login:<br />';
ssi_login($thisurl);
echoFooterExit();
}else{
global $uname, $time_format, $time_offset;
echo "Welcome $uname!";
// echo ' | Time: '.strftime($time_format, time()+$time_offset);
echo '<br />';
}
}
//make sure the string is normalized first.
function isAllowed($s, $allowed){
for($x = 0; $x < strlen($s); ++$x)
if(strpos($allowed, $s[$x]) === false)
return false;
return true;
}
//make sure the string is normalized first.
function stripUnAllowed($s, $allowed){
for($x = 0; $x < strlen($s); ++$x)
if(strpos($allowed, $s[$x]) === false)
$s[$x] = ' ';
return str_replace(' ', '', $s);
}
function verifyIP($hostname, $ip, $remote_ip){
$ip = gethostbyname($hostname);
$remote_ip = $_SERVER['REMOTE_ADDR'];
return $ip == $remote_ip;
}
/*
function checkRows111(){
$args = func_get_args();
$sql = array_shift($args);
$link = self::establish_db_conn();
if (!$stmt = mysqli_prepare($link, $sql)) {
self::close_db_conn();
die('Please check your sql statement : unable to prepare');
}
$types = str_repeat('s', count($args));
array_unshift($args, $types);
array_unshift($args, $stmt);
call_user_func_array('mysqli_stmt_bind_param', $args);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_result_metadata($stmt);
$fields = array();
while ($field = mysqli_fetch_field($result)) {
$name = $field->name;
$fields[$name] = &$$name;
}
array_unshift($fields, $stmt);
call_user_func_array('mysqli_stmt_bind_result', $fields);
array_shift($fields);
$results = array();
while (mysqli_stmt_fetch($stmt)) {
$temp = array();
foreach($fields as $key => $val) { $temp[$key] = $val; }
array_push($results, $temp);
}
mysqli_free_result($result);
mysqli_stmt_close($stmt);
self::close_db_conn();
return $results;
}
*/
function checkRows($sql, $types){
$numargs = func_num_args();
//echo "Number of arguments: $numargs<br />\n";
if (strlen($types) != ($numargs - 2)) {
debug("checkRows: Length of types must be equal to the number of extra args passed in.");
return false;
}
global $g_mysqli;
$stmt = $g_mysqli->prepare($sql) or debug($g_mysqli->error);
$arg_list = func_get_args();
// start at 2, because of $sql and $types
$params = array();
for ($i = 0; $i < $numargs-1; $i++){
$params[$i] = &$arg_list[$i+1];
}
//print_r($params);
call_user_func_array(array($stmt, 'bind_param'), $params);
$stmt->execute();
$rows = $stmt->fetch();
$stmt->close();
return $rows;
}
function getTimeStamp(){
$contents = file_get_contents("timestamp") or die("Can't read timestamp");
return $contents;
}
function mysql_con(){
global $g_mysqli;
// then we are already connected
if(isset($g_mysqli))
return;
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'serverstat';
$g_mysqli = new mysqli($host, $user, $pass, $db);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* change character set to utf8 */
if (!$g_mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $g_mysqli->error);
}
}
function close_mysql(){
global $g_mysqli;
// then we are already connected
if(isset($g_mysqli)){
$g_mysqli->close();
unset($GLOBALS['g_mysqli']);
}
}
function html_special(&$bb_code){
return htmlspecialchars($bb_code, ENT_QUOTES, 'UTF-8');
}
function html_special_decode(&$bb_code){
return htmlspecialchars_decode($bb_code, ENT_QUOTES);
}
function bb2html($bb_code, $previewing = false){
$bb_code = html_special($bb_code);
//old preparsecode($bb_code);
require_once('/path/to/smf/Sources/Subs-Post.php');
preparsecode($bb_code, $previewing);
// Do all bulletin board code tags, with or without smileys.
//old $bb_code = parse_bbc($bb_code, 1);
// require_once('/home/mopar/htdocs/moparisthebest.com/smf/Sources/Subs-Post.php');
censorText($bb_code);
$bb_code = parse_bbc($bb_code);
return $bb_code;
}
// echos the header
function echoHeader($action) {
global $thispage;
//$action = (empty($_REQUEST['action'])) ? 'display' : $_REQUEST['action'];
//<meta http-equiv="content-type" content="text/html; charset=utf-8" />
/*echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Mopar's Server Status Checker - Beta 2</title>
<link rel="stylesheet" type="text/css" href="newstyle.css" />
</head>
<body>
<div id="wrapper">
<div id="header">
<div id="lefthead"> <a href="http://www.moparscape.org/smf/index.php"><img src="images/visit.png" alt="Visit Forums" /></a> </div>
<div id="righthead"> <a href="http://www.moparscape.org/moparscape.html"><img src="images/dlmoparscape.png" alt="Download MoparScape Here!" /></a> </div>
<div id="banner"> <a href="http://www.moparscape.org/serverstatus.php"><img src="images/mscp_banner.png" alt="MoparScape Server Status" /></a> </div>
<ul id="nav">
<li><a href="?"<?php if($action == 'display' && !isset($_GET['offline'])) echo ' class="on"'; ?>>Online Servers</a></li>
<li><a href="?offline"<?php if($action == 'display' && isset($_GET['offline'])) echo ' class="on"'; ?>>Offline Servers</a></li>
<li><a href="?sort=vote&amp;desc<?php if(isset($_GET['offline'])) echo '&amp;offline'; ?>"<?php if($action == 'display' && isset($_GET['sort']) && $_GET['sort'] == 'vote' && isset($_GET['desc'])) echo ' class="on"'; ?>>Most Popular</a></li>
<li><a href="?action=random<?php if(isset($_GET['offline'])) echo '&amp;offline'; ?>">Random Server</a></li>
<li><a href="?action=register"<?php if($action == 'register' && !isset($_GET['edit'])) echo ' class="on"'; ?>>Register Server</a></li>
<li><a href="?action=register&amp;edit"<?php if($action == 'register' && isset($_GET['edit'])) echo ' class="on"'; ?>>Edit my Server</a></li>
<li><a href="?action=search"<?php if(strpos($action, 'search') !== false) echo ' class="on"'; ?>>Search</a></li>
<li><?php ssi_logout($thispage.'?'.$_SERVER['QUERY_STRING']); ?></li>
</ul>
</div>
<div id="leftcolumn">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-3055920918910714";
/* serverstatus */
google_ad_slot = "0121476779";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
<div id="centercolumn">
This new page is beta, servers may be added and deleted while I finish it. Thanks for being patient. Post
comments about the new page <a href="http://www.moparscape.org/smf/index.php/topic,363862.0.html">here</a>.<br /><br />
<?php
}
// echos the footer and then exits
function echoFooterExit($echo = ''){
global $thispage;
$uri = urlencode($thispage.'?'.$_SERVER['QUERY_STRING']);
// can call this because it only closes it if it is set
close_mysql();
echo $echo;
?>
</div>
<div id="rightcolumn">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-3055920918910714";
/* serverstatus */
google_ad_slot = "0121476779";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
<div id="footer">
<p>
<a href="http://validator.w3.org/check?uri=<?php echo $uri; ?>"><img
src="images/valid-xhtml10-blue.png"
alt="Valid XHTML 1.0 Strict" height="31" width="88" /></a>
Copyright &copy; 2009 MoparScape.org
<a href="http://jigsaw.w3.org/css-validator/validator?uri=<?php echo $uri; ?>"><img
src="images/vcss-blue.gif"
alt="Valid CSS 2.1!" height="31" width="88" /></a>
</p>
</div>
</div>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/ga.js\' type=\'text/javascript\'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-6877554-1");
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
</html>
<?php
exit;
}
/*
DROP TABLE IF EXISTS `toadd`;
CREATE TABLE IF NOT EXISTS `toadd` (
`id` int(11) unsigned NOT NULL auto_increment,
`uid` mediumint(8) unsigned NOT NULL,
`uname` varchar(80) NOT NULL,
`online` tinyint(1) unsigned NOT NULL default '1',
`name` tinytext NOT NULL,
`pic_url` tinytext NOT NULL default '',
`ip` varchar(30) NOT NULL,
`port` smallint(5) unsigned NOT NULL,
`version` smallint(3) unsigned NOT NULL,
`time` int(10) unsigned NOT NULL,
`info` text NOT NULL,
`oncount` int(11) unsigned NOT NULL default '1',
`totalcount` int(11) unsigned NOT NULL default '1',
`uptime` tinyint(3) unsigned NOT NULL default '100',
`ipaddress` varchar(15) NOT NULL,
`sponsored` smallint(5) unsigned NOT NULL default '0',
`rs_name` tinytext NOT NULL,
`rs_pass` tinytext NOT NULL,
`key` varchar(15) NOT NULL,
`verified` tinyint(1) unsigned NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `uid` (`uid`),
KEY `online` (`online`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `banned`;
CREATE TABLE IF NOT EXISTS `banned` (
`id` int(11) unsigned NOT NULL auto_increment,
`uid` mediumint(8) unsigned NOT NULL,
`uname` varchar(80) NOT NULL,
`online` tinyint(1) unsigned NOT NULL default '1',
`name` tinytext NOT NULL,
`pic_url` tinytext NOT NULL default '',
`ip` varchar(30) NOT NULL,
`port` smallint(5) unsigned NOT NULL,
`version` smallint(3) unsigned NOT NULL,
`time` int(10) unsigned NOT NULL,
`info` text NOT NULL,
`oncount` int(11) unsigned NOT NULL default '1',
`totalcount` int(11) unsigned NOT NULL default '1',
`uptime` tinyint(3) unsigned NOT NULL default '100',
`ipaddress` varchar(15) NOT NULL,
`sponsored` smallint(5) unsigned NOT NULL default '0',
`rs_name` tinytext NOT NULL,
`rs_pass` tinytext NOT NULL,
PRIMARY KEY (`id`),
KEY `uid` (`uid`),
KEY `online` (`online`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
DROP TABLE IF EXISTS `servers`;
CREATE TABLE IF NOT EXISTS `servers` (
`id` int(11) unsigned NOT NULL auto_increment,
`uid` mediumint(8) unsigned NOT NULL,
`uname` varchar(80) NOT NULL,
`online` tinyint(1) unsigned NOT NULL default '1',
`name` tinytext NOT NULL,
`pic_url` tinytext NOT NULL,
`ip` varchar(30) NOT NULL,
`port` smallint(5) unsigned NOT NULL,
`version` smallint(3) unsigned NOT NULL,
`time` int(10) unsigned NOT NULL,
`info` text NOT NULL,
`oncount` int(11) unsigned NOT NULL default '1',
`totalcount` int(11) unsigned NOT NULL default '1',
`uptime` tinyint(3) unsigned NOT NULL default '100',
`ipaddress` varchar(15) NOT NULL,
`sponsored` smallint(5) unsigned NOT NULL default '0',
`rs_name` tinytext NOT NULL,
`rs_pass` tinytext NOT NULL,
`vote` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `uid` (`uid`),
KEY `online` (`online`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
DROP TABLE IF EXISTS `log_voted`;
CREATE TABLE IF NOT EXISTS `log_voted` (
`id` int(11) unsigned NOT NULL auto_increment,
`uid` mediumint(8) unsigned NOT NULL,
`uname` varchar(80) NOT NULL,
`server_id` int(11) unsigned NOT NULL,
`time` int(10) unsigned NOT NULL,
`ip` varchar(15) NOT NULL,
PRIMARY KEY (`id`),
KEY `uid` (`uid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
*/
?>

108
ss_sources/verify.php Executable file
View File

@ -0,0 +1,108 @@
<?php
/*
MoparScape.org server status page
Copyright (C) 2011 Travis Burtrum (moparisthebest)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('SS_PAGE'))
die('Hacking attempt...');
function verify(){
header("Content-type: text/plain");
//echo 'this is verify';
//echo time(); return;
//global $g_allowed_alpha; echo randString($g_allowed_alpha); return;
if(!isset($_GET['server']) || !isset($_GET['key'])){
echo "Error: Both server and key must be set.\n";
return;
}
// if we are here, server and key are set
$server = $_GET['server'];
$key = $_GET['key'];
writeToFile("server: $server key: $key");
if(verifyIP($server, &$ip, &$remote_ip)){
echo "Success: $server resolves to $ip, which matches your ip, $remote_ip.\n";
writeToFile("Success: $server resolves to $ip, which matches your ip, $remote_ip.");
}else{
echo "Error: $server resolves to $ip, which does not match your ip, $remote_ip.\n";
writeToFile("Error: $server resolves to $ip, which does not match your ip, $remote_ip.\n");
return;
}
// if we are here, remote ip matches the hostname, so verify the key
mysql_con();
global $g_mysqli;
$stmt = $g_mysqli->prepare('SELECT `id`, `key`, `rs_name`, `rs_pass`, `verified` FROM `toadd` WHERE `ip` = ? LIMIT 1') or debug($g_mysqli->error);
$stmt->bind_param("s", $server);
$stmt->execute();
// bind result variables
$stmt->bind_result($id, $db_key, $rs_name, $rs_pass, $verified);
if(!$stmt->fetch()){
echo "Error: This server does not exist, you may repost it, and then verify it.\n";
writeToFile("server doesn't exist");
return;
}
$stmt->close();
if($key != $db_key){
echo "Error: The key is not correct, you may only verify the ip with the correct key.\n";
writeToFile("key incorrect");
return;
}
if($verified == 1){
writeToFile("already verified");
echo "You have already verified that you own this server.\n
Your server will be checked by logging into it with the following credentials:\n
Username: $rs_name\n
Password: $rs_pass\n
to make sure it is online, and if successful, it will be posted.";
return;
}
// if we are here, the ip and key is valid so set the server as verified
$sql = "UPDATE `toadd` SET `verified` = '1' WHERE `id` = ? LIMIT 1";
$stmt = $g_mysqli->prepare($sql) or debug($g_mysqli->error);
$stmt->bind_param("i", $id);
// execute the query
$stmt->execute();
if ($stmt->affected_rows == 1) {
writeToFile("success verified");
echo "Congratulations, you have verified you own this IP.\n
Your server will now be checked by logging into it with the following credentials:\n
Username: $rs_name\n
Password: $rs_pass\n
to make sure it is online, and if successful, it will be posted.";
}else{
writeToFile("strange failure");
echo "Strange failure, PM Moparisthebest on the forums to with details so he can fix it.\n";
}
$stmt->close();
close_mysql();
}
function writeToFile($message, $fname = 'verify_log', $mode = 'a'){
$fp = fopen($fname, $mode);
fwrite($fp, time().': '.$message."\n");
fclose($fp);
}
?>

162
ss_sources/view.php Executable file
View File

@ -0,0 +1,162 @@
<?php
/*
MoparScape.org server status page
Copyright (C) 2011 Travis Burtrum (moparisthebest)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('SS_PAGE'))
die('Hacking attempt...');
function view(){
//echo 'this is view';
mysql_con();
global $g_mysqli;
$stmt = $g_mysqli->prepare('SELECT `name`, `pic_url`, `uid`, `uname`, `ip`, `port`, `version`, `uptime`, `time`, `info`, `online`, `sponsored`, `vote` FROM `servers` WHERE `ip` = ? LIMIT 1') or debug($g_mysqli->error);
$stmt->bind_param("s", $_GET['server']);
$stmt->execute();
// bind result variables
$stmt->bind_result($name, $pic_url, $uid, $uname, $ip, $port, $version, $uptime, $time, $info, $online, $spons, $votes);
if(!$stmt->fetch()){
echo 'This server does not exist.<br />';
return;
}
$stmt->close();
close_mysql();
if($online == 1){
$link = "http://www.moparscape.org/index.php?server=%s&amp;port=%s&amp;version=%s&amp;detail=";
$link = sprintf($link, $ip, $port, $version);
$play = '<a href="%s0">High</a> / <a href="%s1">Low</a>';
$play = sprintf($play, $link, $link);
}else{
$play = '<div class="offline">Server Offline!</div>';
}
$info = bb2html($info);
$status_img_url = "http://".$_SERVER['SERVER_NAME']."/serverstatus/$ip.png";
$this_url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
?>
<script type="text/javascript">
//<![CDATA[
<!--
function selectText()
{
var oCodeArea = document.getElementById('selectme');
if (typeof(oCodeArea) != 'object' || oCodeArea == null)
return false;
// Start off with my favourite, internet explorer.
if ('createTextRange' in document.body)
{
var oCurRange = document.body.createTextRange();
oCurRange.moveToElementText(oCodeArea);
oCurRange.select();
}
// Firefox at el.
else if (window.getSelection)
{
var oCurSelection = window.getSelection();
// Safari is special!
if (oCurSelection.setBaseAndExtent)
{
var oLastChild = oCodeArea.lastChild;
oCurSelection.setBaseAndExtent(oCodeArea, 0, oLastChild, 'innerText' in oLastChild ? oLastChild.innerText.length : oLastChild.textContent.length);
}
else
{
var curRange = document.createRange();
curRange.selectNodeContents(oCodeArea);
oCurSelection.removeAllRanges();
oCurSelection.addRange(curRange);
}
}
return false;
}
//-->
//]]>
</script>
<table class="<?php echo ($spons == 0) ? 'other' : 'spons'; ?>" summary="<?php echo $name; ?>">
<caption>
<?php echo ($pic_url != '') ? '<img src="'.$pic_url.'" alt="'.$name.'" width="185" height="25" />' : $name; ?>
</caption>
<thead>
<tr>
<th scope="col">IP</th>
<th scope="col">Port</th>
<th scope="col">Client Version</th>
<th scope="col">Owner</th>
<th scope="col">Uptime</th>
<th scope="col">Since</th>
<th scope="col">Votes</th>
<th scope="col">Vote here!</th>
<th scope="col">Play (select detail)</th>
<?php
if(can_mod() && $spons == 0){
?>
<th scope="col">Delete / Ban</th>
<?php
}
?>
</tr>
</thead>
<tfoot>
<tr>
<th scope="row">Image: </th>
<th scope="row" colspan="3"><a href="<?php echo $this_url; ?>"><img src="<?php echo $status_img_url; ?>" alt="Status Image" /></a></th>
<th scope="row">BBcode:<br /><a href="javascript:void(0);" onclick="return selectText();">[Select]</a></th>
<th scope="row" colspan="<?php echo ((can_mod() && $spons == 0) ? '5' : '4'); ?>"><div id="selectme">[url=<?php echo $this_url; ?>][img]<?php echo $status_img_url; ?>[/img][/url]</div></th>
</tr>
</tfoot>
<tbody>
<tr>
<td><?php echo $ip; ?></td>
<td><?php echo $port; ?></td>
<td><?php echo $version; ?></td>
<td><a href="http://www.moparscape.org/smf/index.php?action=profile;u=<?php echo $uid; ?>"><?php echo $uname; ?></a></td>
<td><?php echo $uptime; ?>%</td>
<td><?php echo date("m-d-y", $time); ?></td>
<td><?php echo ($votes > 0) ? '+'.$votes: $votes; ?></td>
<td><a href="<?php echo $thispage ?>?action=up&amp;server=<?php echo $ip ?>"><img src="http://<?php echo $_SERVER['SERVER_NAME']; ?>/images/up.png" alt="Up" /></a><a href="<?php echo $thispage ?>?action=down&amp;server=<?php echo $ip ?>"><img src="http://<?php echo $_SERVER['SERVER_NAME']; ?>/images/down.png" alt="Down" /></a></td>
<td><?php echo $play; ?></td>
<?php
if(can_mod() && $spons == 0){
?>
<td><a href="<?php echo $thispage ?>?action=delete&amp;server=<?php echo $ip ?>">X</a> / <a href="<?php echo $thispage ?>?action=ban&amp;server=<?php echo $ip ?>">X</a></td>
<?php
}
?>
</tr>
</tbody>
</table>
<div class="post">
<?php echo $info; ?>
</div>
<?php
}
?>

184
ss_sources/vote.php Executable file
View File

@ -0,0 +1,184 @@
<?php
/*
MoparScape.org server status page
Copyright (C) 2011 Travis Burtrum (moparisthebest)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('SS_PAGE'))
die('Hacking attempt...');
function vote(){
// forceLogin();
global $uid;
$action = $_GET['action'];
if(!isset($_GET['server']))
forward();
$server = $_GET['server'];
if(!getMysqlId($server, $id, $suid, $name, $ip))
return;
if($uid == $suid){
echo "It isn't right for you to vote on your own server, now is it?";
return;
}
echo "Are you sure you wish to vote <b>$action</b> server $name? You only get to vote once per hour.<br />";
?>
<form action="<?php echo actionURL('vote'); ?>" method="post" enctype="multipart/form-data" style="margin: 0;">
<fieldset style="margin: 0;">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="hidden" name="vote" value="<?php echo $action; ?>" />
<input type="hidden" name="ip" value="<?php echo $ip; ?>" />
<?php
require_once('recaptchalib.php');
$publickey = "6LddIr4SAAAAALtdzE4zN3pkquo40zhRrOlab-Gf "; // you got this from the signup page
echo recaptcha_get_html($publickey, null, ($_SERVER['HTTPS'] == "on") );
?>
<input type="submit" name="submit" value="Vote" accesskey="s" />
</fieldset>
</form>
<?php
}
function vote2(){
// $_SERVER['HTTP_REFERER'] : http://mopar.moparscape.org/serverstatus.php?action=up&server=72.9.251.24
// forceLogin();
global $uid, $uname, $thispage, $time_format, $time_offset, $g_mysqli;
//wait time in seconds to vote again
$wait_time = 3600;
$action = $_POST['vote'];
if($action != 'up' && $action != 'down')
forward();
require_once('recaptchalib.php');
$privatekey = "6LddIr4SAAAAAIPlo9971NoHMx2HCUbHATsQVSX5";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
//die ("The reCAPTCHA wasn't entered correctly. Go back and try it again."."(reCAPTCHA said: " . $resp->error . ")");
//forward();
error("The reCAPTCHA wasn't entered correctly. Go back and try it again.");
return;
}
$server = $_POST['ip'];
if(!getMysqlId($server, $id, $suid, $name, $ip))
return;
if($uid == $suid){
echo "It isn't right for you to vote on your own server, now is it?";
return;
}
$expected_referer = "$thispage?action=$action&server=$ip";
//die($expected_referer.':'.$_SERVER['HTTP_REFERER']);
//die($ip.':'.$server);
//die($id.':'.$_POST['id']);
//die('$uid:'.$uid.' $uname:'.$uname.' $time_format:'.$time_format.' $time_offset:'.$time_offset);
if($ip != $server || $id != $_POST['id'] || $_SERVER['HTTP_REFERER'] != $expected_referer)
forward($expected_referer);
// we checked out so far, make sure they haven't voted in the last hour
$threshold = time()-$wait_time;
// first check the session variable, since it is cheaper than a query
if(isset($_SESSION['last_voted']) && $_SESSION['last_voted'] > $threshold){
echo 'You have voted within the last hour, you may do this again at '.strftime($time_format, $_SESSION['last_voted']+$wait_time+$time_offset).'<br />';
return;
}
$stmt = $g_mysqli->prepare("SELECT `time` FROM `log_voted` WHERE `time` > ? AND ( (`uid` != '0' AND`uid` = ?) OR `ip` = ?) LIMIT 1") or debug($g_mysqli->error);
$stmt->bind_param("iis", $threshold, $uid, $_SERVER['REMOTE_ADDR']);
$stmt->execute();
// bind result variables
$stmt->bind_result($time);
if($stmt->fetch()){
echo 'You have voted within the last hour, you may do this again at '.strftime($time_format, $time+$wait_time+$time_offset).'<br />';
return;
}
$stmt->close();
// we haven't voted in the last hour, now enter the vote AND update the log
if($action == 'up')
$op = '+';
else
$op = '-';
$sql = "UPDATE `servers` SET `vote` = `vote` $op '1' WHERE `id` = ? LIMIT 1";
$stmt = $g_mysqli->prepare($sql) or debug($g_mysqli->error);
$stmt->bind_param("i", $id);
// execute the query
$stmt->execute();
if ($stmt->affected_rows != 1) {
echo 'Vote failed, PM <a href="http://www.moparscape.org/smf/index.php?action=profile;u=1">Moparisthebest</a> on the forums to with details so he can fix it.';
return;
}
$stmt->close();
// we have voted now, so we need to insert it into the log to enforce the 1 per hour limit, and set session variable last_voted
$_SESSION['last_voted'] = time();
$sql = 'INSERT INTO `log_voted` (`uid`, `uname`, `server_id`, `time`, `ip`, `op`) VALUES(?, ?, ?, ?, ?, ?)';
$stmt = $g_mysqli->prepare($sql) or debug($g_mysqli->error);
$stmt->bind_param("isiiss", $uid, $uname, $id, $_SESSION['last_voted'], $_SERVER['REMOTE_ADDR'], $op);
$stmt->execute() or debug($g_mysqli->error);
if ($stmt->affected_rows != 1) {
echo 'Vote log failed, PM <a href="http://www.moparscape.org/smf/index.php?action=profile;u=1">Moparisthebest</a> on the forums to with details so he can fix it.';
return;
}
$stmt->close();
close_mysql();
forward("$thispage?server=$ip");
}
function getMysqlId($server, &$id, &$suid, &$name, &$ip){
global $g_mysqli;
mysql_con();
$stmt = $g_mysqli->prepare('SELECT `id`, `uid`, `name`, `ip` FROM `servers` WHERE `ip` = ? LIMIT 1') or debug($g_mysqli->error);
$stmt->bind_param("s", $server);
$stmt->execute();
// bind result variables
$stmt->bind_result($id, $suid, $name, $ip);
if(!$stmt->fetch()){
echo 'This server does not exist.<br />';
return false;
}
$stmt->close();
return true;
}
?>