90 Commits
mw_28 ... mw_34

Author SHA1 Message Date
3f4213ac25 session.hash_function/hash_bits_per_character was removed in php 7.1 2019-12-30 01:34:00 -06:00
2c25c90bc6 never mind 2019-12-30 01:14:47 -06:00
2832f455a7 php-fpm seems to be outputting log messages anyway so don't need to tail the log 2019-12-30 01:11:34 -06:00
695137b441 various updates to make it run on debian 10
still doesn't quite work properly, Special:RecentChanges is broken and so is logging in
2019-12-30 01:10:22 -06:00
21257d7047 fix includes of some extensions 2019-12-29 20:46:35 -06:00
a5115a7579 update mediawiki to 1.34 and smf to 2.0.16 2019-12-29 03:55:14 -06:00
21919211e5 Merge branch 'master' of ssh://forge.monarch-pass.net/glitch-city-laboratories/glitch-city-laboratories 2019-11-10 20:54:19 -06:00
46f253f757 refresh_styles: add script for pulling in updated styles from production 2019-11-10 20:28:58 -06:00
eb861824ea mediawiki: update to 1.33.1 2019-11-10 20:02:09 -06:00
77aa8d4581 Fix positioning of pokeball bullet icon.
Thanks hunk and Sherkel for bringing this up. https://forums.glitchcity.info/index.php?topic=6361.msg215429#msg215429
2019-10-30 08:24:52 +00:00
cf1d555978 add Cite extension 2019-09-30 20:19:42 -05:00
469c64490c add missing comment id fields (that were probably supposed to be added by a migration we skipped)
These fields exist in the live database so migration should still work there.
2019-07-06 00:49:32 -05:00
5c0a6dfd6d Merge branch 'master' into mw_33 2019-07-06 00:17:54 -05:00
ade6a6d415 update database dump with 1.32 dump 2019-07-06 00:17:38 -05:00
e020b4cc3f add wait-for-it 2019-07-02 20:11:42 -05:00
b2a5879743 update to mediawiki 1.33.0 2019-07-02 19:09:17 -05:00
026b2947d4 enable WikiEditor and CodeEditor for source editing 2019-06-16 21:01:23 -05:00
ec397feed6 add VisualEditor/Parsoid info to readme 2019-06-15 18:29:24 -05:00
829a51384b Add parsoid image & configuration 2019-06-15 18:24:40 -05:00
d8dd54dc9f add VisualEditor extension 2019-06-15 17:43:28 -05:00
f97da260d8 add ca- ids to content action links, this is required for VisualEditor 2019-06-15 17:43:03 -05:00
72dced4c8d change add_extension.sh to init submodules, in case the extension requires submodules (like visualeditor) 2019-06-15 17:41:07 -05:00
c20d8d4f6e remove deprecated calls to wfRunHooks 2019-06-15 16:12:22 -05:00
935997cc75 it is an error to use a boolean here, so don't 2019-06-15 15:57:14 -05:00
07094ab956 update mediawiki to 1.32.1 (finally) 2019-06-09 15:01:59 -05:00
b6c96f9d3c Merge branch 'master' of ssh://forge.monarch-pass.net/glitch-city-laboratories/glitch-city-laboratories 2019-02-15 21:07:52 -06:00
5f68d09c72 gate phpinfo.php behind an environment variable so it doesn't get shown to the public 2019-02-15 21:07:26 -06:00
9c9baee367 gate phpinfo.php behind an environment variable so it doesn't accidentally leak to the public 2019-02-16 03:07:10 +00:00
f747f18acd fix msmtprc syntax 2018-09-04 01:42:04 -05:00
abee89b732 Load CheckUser with wfLoadExtension.
This seems to be the preferred way to load extensions but FlaggedRevs doesn't support it for some reason, so we need to include it directly.
2018-09-03 23:01:48 -05:00
a866d8dd74 exit 0 from setup.sh 2018-09-03 22:53:18 -05:00
6dd7961ebd Implement printable mode. 2018-09-03 22:41:34 -05:00
53447ad8ef Remove UserRightsList extension; it's currently not maintained 2018-09-03 22:03:30 -05:00
d2c68efe43 Remove install.php 2018-09-03 22:00:56 -05:00
2d417f433d Add a script to install SMF packages into the image. 2018-09-03 21:53:41 -05:00
dcdb8ea4db Set $$wgPHPSessionHandling to false to disable mediawiki using php sessions.
This seems to resolve the issue of mediawiki and smf sessions colliding, as mediawiki will no longer touch smf's session. The "loss of session data" error seems to still not be present.
2018-08-27 03:32:14 -05:00
72b7638d11 remove print_r 2018-08-13 02:00:12 -05:00
83f36080e3 Destroy SMF session to work around MW/SMF collision issue. Coincidentally, this also seems to actually resolve "loss of session data" errors. 2018-08-13 01:35:39 -05:00
2c0e67e675 initial implementation of Auth remoteuser, of course it doesn't work 2018-08-13 00:39:19 -05:00
e038483e69 Add support for email with msmtp 2018-08-12 06:30:19 -05:00
5ee52eb5a1 messy hack around "loss of session data"
Should go away if/when we switch to Auth remoteuser extension
2018-08-12 05:30:18 -05:00
b365cfa58e create links to mediawiki maintenance scripts 2018-08-12 03:39:44 -05:00
b8c8bc331e Install nuke extension, since it's not included with MediaWiki 1.31 2018-08-12 02:54:33 -05:00
2da5e9837d move responsibility for creating the initial database to the database container 2018-08-12 02:50:11 -05:00
91b0cecf74 actually update to mw 31 2018-08-11 13:10:42 -05:00
c1bf04fbd2 Update mediawiki to 1.31 2018-08-08 20:54:57 -05:00
baa50b5ded Merge branch 'master' of gitlab.monarch-pass.net:glitch-city-laboratories/glitch-city-laboratories 2018-02-07 19:20:01 -06:00
ada88102c6 correctly set remote addr from x-forwarded-for 2018-02-04 00:26:09 -06:00
021a710fc9 add parser function to get a user's display name 2018-02-04 00:25:55 -06:00
673d7e61d4 more improved header link generation 2018-02-03 23:40:31 -06:00
12ab7f0012 remove deprecated GCL skin 2018-02-03 22:36:13 -06:00
658af7e28f fix generation of header links 2018-02-03 22:35:30 -06:00
54ffb306f7 add command to dump test database 2018-02-03 22:31:33 -06:00
8879c07677 chmod $SOURCE_ROOT 2018-02-03 22:11:39 -06:00
ba116f42cb chown to www-data after installing extension 2018-02-03 21:11:36 -06:00
6b30481c88 chown application source after untarring it 2018-02-03 21:10:03 -06:00
d0ab55ddfa add info about admin login 2018-02-02 11:55:09 -06:00
b9996c771f Disable file cache and individual page caching. This should ensure the session id in the login form is consistently correct. 2018-02-02 03:09:49 -06:00
001fad60d6 remove stale sessions 2018-02-02 01:01:20 -06:00
8453d10ab9 more database stuff 2018-02-02 01:00:22 -06:00
6281163a79 fix test database 2018-02-02 00:56:49 -06:00
037fb61490 trim down test database 2018-02-02 00:14:22 -06:00
de182b86fd enable Nuke extension 2018-02-01 23:05:58 -06:00
6ea439cde8 need to add scripts up here before we use them 2018-02-01 22:40:59 -06:00
51f3bfcd1a add config/scripts after we install the wiki/forum 2018-02-01 22:35:42 -06:00
c8409ccd84 fix path 2018-02-01 21:41:23 -06:00
7eb613d31a remove extensions that we can pull from mediawiki repo 2018-02-01 21:37:32 -06:00
6bde45cc79 add add_extension script 2018-02-01 21:33:56 -06:00
420bbac561 run composer after install 2018-02-01 09:11:35 -06:00
4fd7a8cbc9 dockerfile improvements for performance, actually download mediawiki 1.30 2018-02-01 02:36:19 -06:00
ba4f2c3cd2 add missing hidden input field to login form 2018-02-01 02:36:14 -06:00
45bb011774 disable createaccount permission for all users 2018-02-01 00:55:37 -06:00
84df8c7131 update mediawiki to 1.30, smf to 2.0.15 2018-02-01 00:53:58 -06:00
1ae67657bb disable Prof Glitch's extension, so I don't keep having to enter the container and do it each time it starts 2018-01-06 01:28:17 +00:00
ec07c687b0 i think the arguments go like this 2017-10-29 11:32:34 -05:00
6ace0af5f8 properly construct url 2017-10-29 11:30:44 -05:00
9f4ddd6afe remove comment 2017-10-29 11:27:07 -05:00
05af6991f1 these make more sense as tags and not parser functions 2017-10-22 03:19:35 -05:00
c0d5f6f2ad oops 2017-10-22 02:29:31 -05:00
3e40c33db9 remove SecureHTML extension too, since that too was only ever used for one thing. Replace with an extension that specifically encapsulates what that extension was used for. 2017-10-22 02:21:18 -05:00
4a7577cc34 Remove securephp extension. It was only used on the main page for displaying news. This can be implemented as an extension. 2017-10-22 02:01:43 -05:00
95ce71ca78 load ssi before api 2017-10-22 01:29:07 -05:00
4b7c4f7be3 Update smf_api.php 2017-10-22 01:03:04 -05:00
8b2e8e318e migrate to php 7 2017-10-21 23:35:43 -05:00
fc49ccb695 use compose version 3 2017-10-21 20:49:16 -05:00
191ba253c4 use member_name (username) instead of real_name (display name) 2017-10-21 20:48:05 -05:00
92be189e58 actually commit these changes 2017-10-21 20:47:52 -05:00
ba70c3e3cf add smf_api.php 2017-10-21 20:43:04 -05:00
06a857084c remove PGSAEX and CHU extensions. Auth will go back from being display name based to username based, as it should have been. 2017-10-21 20:31:49 -05:00
2af58df9de Update mediawiki and smf to latest versions. Remove smf source and pull from site on build. For now this means we are running vanilla smf. We will add extensions later. 2017-10-21 20:28:31 -05:00
5205 changed files with 13226 additions and 377870 deletions

View File

@ -1,36 +1,61 @@
FROM debian:stable
FROM debian:buster
RUN apt-get -y update && apt-get -y install nginx php5-fpm php5-mysql php-apc supervisor python-pip mysql-client imagemagick curl wget
RUN apt-get -y update && apt-get -y install nginx php-fpm php-mysql php-apcu php-mbstring php-xml supervisor python-pip \
default-mysql-client imagemagick curl wget zip unzip php-pclzip git msmtp msmtp-mta
RUN pip install supervisor-stdout
ENV MW_VERSION REL1_28
ENV MW_SOURCE https://releases.wikimedia.org/mediawiki/1.28/mediawiki-1.28.0.tar.gz
ENV SMF_VERSION 2-0-11
ENV MW_VERSION REL1_34
ENV MW_SOURCE https://releases.wikimedia.org/mediawiki/1.34/mediawiki-1.34.0.tar.gz
ENV SMF_VERSION 2.0.16
ENV SMF_SOURCE https://download.simplemachines.org/index.php/smf_2-0-16_install.tar.gz
ENV SOURCE_ROOT /application
ENV WIKI_SOURCE $SOURCE_ROOT/w
ENV FORUMS_SOURCE $SOURCE_ROOT/forums
RUN mkdir userdata
ADD configuration configuration
ADD application application
ADD scripts scripts
RUN mkdir userdata && mkdir $SOURCE_ROOT && \
mkdir $WIKI_SOURCE && mkdir $FORUMS_SOURCE
# Install composer
RUN cd /usr/src && curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
# Clone mediawiki source into temp directory, install and then copy over to application dir
# Clone mediawiki and SMF source into temp directory, install and then copy over to application dir
RUN cd /tmp && wget $MW_SOURCE && tar -xvf mediawiki-*.tar.gz && \
cp -Rv mediawiki-*/* $WIKI_SOURCE && rm -rf mediawiki-*
cp -Rv mediawiki-*/* $WIKI_SOURCE && rm -rf mediawiki-* && \
mkdir smf && cd smf && wget $SMF_SOURCE && tar -xvf smf_*.tar.gz && \
rm -rf Settings.php attachments smf_*.tar.gz && cp -Rv * $FORUMS_SOURCE
RUN ln -sf /configuration/supervisord.conf /etc/supervisor/supervisord.conf && \
ln -sf /configuration/nginx.conf /etc/nginx/nginx.conf && \
ln -sf /configuration/php-fpm.conf /etc/php5/fpm/php-fpm.conf && \
ln -sf /configuration/php-fpm-pool.conf /etc/php5/fpm/pool.d/www.conf && \
ln -sf /configuration/php.ini /etc/php5/fpm/php.ini
RUN chown -R www-data:www-data $SOURCE_ROOT
RUN chown -R www-data:www-data /application
RUN cd "$WIKI_SOURCE/maintenance" && \
sh -c 'for TOOL in *.php; do LINK="/usr/bin/$(basename $TOOL .php)"; echo "#!/bin/sh\nphp $WIKI_SOURCE/maintenance/$TOOL \$@" > $LINK; chmod +x $LINK; done'
# Add our scripts
ADD scripts scripts
# Install additional extensions
# 12 August 2018: Nuke extension is not bundled with MediaWiki 1.31 by mistake.
# It will be added back in the next release.
RUN /scripts/add_extension.sh FlaggedRevs $MW_VERSION && \
/scripts/add_extension.sh CheckUser $MW_VERSION && \
/scripts/add_extension.sh Contributors $MW_VERSION && \
/scripts/add_extension.sh Nuke $MW_VERSION && \
/scripts/add_extension.sh Auth_remoteuser $MW_VERSION && \
/scripts/add_extension.sh VisualEditor $MW_VERSION && \
/scripts/add_extension.sh Cite $MW_VERSION
# Install SMF mods
# 3 September 2018: These would also need to be installed in the database.
RUN /scripts/add_mod.php "http://custom.simplemachines.org/mods/index.php?action=download;mod=3067;id=179832"
# Add our stuff
ADD --chown=www-data:www-data application application
RUN cd $WIKI_SOURCE && composer update --no-dev
ADD configuration configuration
ADD https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh /usr/bin/wait-for-it
RUN chmod +x /usr/bin/wait-for-it
EXPOSE 80
CMD /usr/bin/supervisord -n
CMD /scripts/start

View File

@ -3,6 +3,12 @@ This version of Glitch City Laboratories - tentatively v3.5 - is implemented as
As of **9 August 2016** this version of GCL is live on the Monarch Pass server. All development will be done in this repo.
## Info about the test database
The test database is a small collection of wiki pages, boards, and posts. There is an admin user (username `Abwayax`, password `testadmin`).
## VisualEditor
As of **15 June 2019** (MediaWiki 1.32) the VisualEditor extension is included. This requires a Parsoid service, which is *not* included. See the `docker-compose.yml` for details.
## Commands
### Build development environment
`docker-compose build`
@ -12,3 +18,6 @@ As of **9 August 2016** this version of GCL is live on the Monarch Pass server.
### Follow PHP logs
`docker exec glitchcityinfo_web_1 tail -f /var/log/php5-fpm.log`
### Dump test database
`docker-compose exec db mysqldump glitchcity -ptoor`

View File

@ -1,340 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
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
this service 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.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
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
convey 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 General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,93 +0,0 @@
#
# This java file is a part of the
#
# - Plouf's Java IRC Client -
#
# Copyright (C) 2004 Philippe Detournay
#
# This file is licensed under the GPL license
#
# All contacts : theplouf@yahoo.com
#
#
# Syntax :
# Comments begin with the # character. This character must be the first character of the line.
# A data line has three parts : the data id, the data id description, the data string.
# - Data id : An hexadecimal figure identifying the string.
# - Data description : Begins by [ and ends by ]. The description is not parsed and
# can be any string.
# - Data string : The string itself. Parameters are specified using the %i syntax.
#
# Trailing spaces can be added using the \s escape character.
0001 [INTERPRETOR_NOT_ON_CHANNEL] Not on a channel
0002 [INTERPRETOR_UNKNOWN_DCC] %1 : unknown dcc subcommand
0003 [INTERPRETOR_INSUFFICIENT_PARAMETERS] %1 : insufficient parameters
0004 [INTERPRETOR_BAD_CONTEXT] %1 : unable to perform in current context
0005 [INTERPRETOR_CANNOT_CTCP_IN_DCCCHAT] Cannot send CTCP codes via DCC Chat
0006 [INTERPRETOR_UNKNOWN_CONFIG] %1 : unknown config subcommand
0007 [INTERPRETOR_TIMESTAMP_ON] Timestamp enabled
0008 [INTERPRETOR_TIMESTAMP_OFF] Timestamp disabled
0009 [INTERPRETOR_SMILEYS_ON] Graphical smileys enabled
000a [INTERPRETOR_SMILEYS_OFF] Graphical smileys disabled
000b [INTERPRETOR_IGNORE_ON] Now ignoring %1
000c [INTERPRETOR_IGNORE_OFF] Not ignoring %1 anymore
000d [INTERPRETOR_MULTISERVER_DISABLED] Multiserver support is disabled
0101 [DCC_WAITING_INCOMING] Waiting for incoming connection...
0102 [DCC_UNABLE_TO_OPEN_CONNECTION] Unable to open connection : %1
0103 [DCC_CONNECTION_ESTABLISHED] DCC Connection established
0104 [DCC_CONNECTION_CLOSED] Connection closed
0105 [DCC_ERROR] Error : %1
0106 [DCC_UNABLE_TO_SEND_TO] %1 : unable to send to %2
0107 [DCC_BAD_CONTEXT] Unable to execute command from current context
0108 [DCC_NOT_CONNECTED] Not connected
0109 [DCC_UNABLE_PASSIVE_MODE] Unable to initialize passive mode
010a [CTCP_PING_REPLY] [%1 PING reply] : %2 seconds
010b [DCC_STREAM_CLOSED] Stream closed
0201 [IDENT_FAILED_LAUNCH] Failed to launch Ident server : %1
0202 [IDENT_REQUEST] Ident request from %1
0203 [IDENT_ERROR] Error occurred
0204 [IDENT_REPLIED] Replied %1
0205 [IDENT_DEFAULT_USER] default user
0206 [IDENT_NO_USER] No user for request
0207 [IDENT_RUNNING_ON_PORT] Ident server running on port %1
0208 [IDENT_LEAVING] Ident server leaving : %1
0209 [IDENT_NONE] none
020a [IDENT_UNKNOWN] unknown
020b [IDENT_UNDEFINED] Undefined result
0301 [FILE_SAVEAS] Save file as
0401 [ABOUT_ABOUT] About
0402 [ABOUT_PROGRAMMING] Programming
0403 [ABOUT_DESIGN] Design
0404 [ABOUT_THANKS] Thanks to
0405 [ABOUT_SUPPORT] for support, ideas and testing
0406 [ABOUT_GPL] This software is licensed under the GPL license
0501 [SERVER_UNABLE_TO_CONNECT] Unable to connect : %1
0502 [SERVER_UNABLE_TO_CONNECT_STILL] Unable to connect to %1 : currently trying to connect to %2
0503 [SERVER_DISCONNECTING] Disconnecting from %1
0504 [SERVER_CONNECTING] Connecting...
0505 [SERVER_NOT_CONNECTED] Not connected
0506 [SERVER_LOGIN] Logging in...
0507 [SERVER_DISCONNECTED] Disconnected from %1
0508 [SERVER_ERROR] Error : %1
0509 [SERVER_AUTOREJOIN_ATTEMPT] Attempting to rejoin channel %1...
050a [SERVER_AUTOREJOIN_FAILED] Unable to rejoin channel %1
071a [GUI_CHANGE_NICK] Change nick to
071b [GUI_COPY_WINDOW] Copy text
071c [GUI_DCC_CHAT_WARNING_TITLE] Warning
071d [GUI_DCC_CHAT_WARNING_TEXT] Do you want to accept DCC chat from %1?
0801 [ASL_MALE] Boy, %1 years old, %2
0802 [ASL_FEMALE] Girl, %1 years old, %2
0803 [ASL_UNKNOWN] %1 years old from %2
0901 [REPLY_IDLE] %1 has been idle for %2
0902 [REPLY_SIGNON] %1 connected on %2
ffff [ERROR_NOT_DEFINED] Undefined string

Binary file not shown.

Before

Width:  |  Height:  |  Size: 453 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 418 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 394 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 378 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 389 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 379 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 751 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 396 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 407 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 395 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 409 B

View File

@ -1,9 +0,0 @@
<?php
// Try to handle it with the upper level index.php. (it should know what to do.)
if (file_exists(dirname(dirname(__FILE__)) . '/index.php'))
include (dirname(dirname(__FILE__)) . '/index.php');
else
exit;
?>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 536 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 261 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 389 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 502 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 383 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 382 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 390 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 390 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 381 B

View File

@ -1,3 +0,0 @@
<?php
echo 'Now why would you need to access this directory...?';
?>

Binary file not shown.

Binary file not shown.

View File

@ -1,75 +0,0 @@
#
# This java file is a part of the
#
# - Plouf's Java IRC Client -
#
# Copyright (C) 2004 Philippe Detournay
#
# This file is licensed under the GPL license
#
# All contacts : theplouf@yahoo.com
#
#
# Syntax :
# Comments begin with the # character. This character must be the first character of the line.
# A data line has three parts : the data id, the data id description, the data string.
# - Data id : An hexadecimal figure identifying the string.
# - Data description : Begins by [ and ends by ]. The description is not parsed and
# can be any string.
# - Data string : The string itself. Parameters are specified using the %i syntax.
#
# Trailing spaces can be added using the \s escape character.
8601 [SOURCE_YOU_KICKED] You've been kicked out of %1 by %2
8602 [SOURCE_STATUS] Status
8603 [SOURCE_CHANLIST] Channels for %1
8604 [SOURCE_CHANLIST_RETREIVING] Retrieving channels...
8605 [SOURCE_HAS_JOINED] %1 has joined %2
8606 [SOURCE_HAS_LEFT] %1 has left %2
8607 [SOURCE_HAS_BEEN_KICKED_BY] %1 has been kicked by %2
8608 [SOURCE_HAS_QUIT] %1 has quit
8609 [SOURCE_TOPIC_IS] Topic is %1
860a [SOURCE_CHANGED_TOPIC] %1 changed topic to %2
860b [SOURCE_CHANNEL_MODE] %1 sets channel mode to %2
860c [SOURCE_CHANNEL_MODE_IS] Channel mode is %1
860d [SOURCE_USER_MODE] %1 sets mode %2 on %3
860e [SOURCE_KNOWN_AS] %1 is now known as %2
860f [SOURCE_YOUR_MODE] Mode changed to %1
8610 [SOURCE_YOUR_NICK] Your nick is now %1
8611 [SOURCE_INFO] Infos
8612 [SOURCE_AWAY] %1 is away
8613 [SOURCE_YOU_INVITED] %1 invites you to join %2
8614 [SOURCE_YOU_JOINED_AS] You're talking in %1 as %2
8701 [GUI_WHOIS] Whois
8702 [GUI_QUERY] Query
8703 [GUI_KICK] Kick
8704 [GUI_BAN] Ban
8705 [GUI_KICKBAN] Kick + Ban
8706 [GUI_OP] Op
8707 [GUI_DEOP] DeOp
8708 [GUI_VOICE] Voice
8709 [GUI_DEVOICE] DeVoice
870a [GUI_PING] Ping
870b [GUI_VERSION] Version
870c [GUI_TIME] Time
870d [GUI_FINGER] Finger
870e [GUI_RETREIVING_FILE] Receiving file (%1 bytes)
870f [GUI_SENDING_FILE] Sending file (%1 bytes)
8710 [GUI_TERMINATED] %1 terminated
8711 [GUI_FAILED] %1 failed
8712 [GUI_CLOSE] Close
8713 [GUI_DISCONNECT] Disconnect
8714 [GUI_CHANNELS] Channels
8715 [GUI_HELP] Help
8716 [GUI_PRIVATE] private
8717 [GUI_PUBLIC] public
8718 [GUI_CONNECT] Connect
8719 [GUI_ABOUT] About
871a [GUI_CHANGE_NICK] Change nick to
871c [GUI_FONT] Font
871d [GUI_FONT_WINDOW] Select font
871e [GUI_FONT_WINDOW_OK] Ok
871f [GUI_ENTER_TEXT_HERE] Enter text here...
ffff [ERROR_NOT_DEFINED] Undefined string

Binary file not shown.

Binary file not shown.

View File

@ -1,28 +0,0 @@
#
# This file is part of the
#
# - Plouf's Java IRC Client -
#
# Copyright (C) 2002 -- 2004 Philippe Detournay
#
# This file is licensed under the GPL license
#
# All contacts : plouf@pjirc.com
#
# Syntax :
# Comments begin with the # character. This character must be the first character of the line.
# A data line has two parts : the parameter name and the parameter value. These parts
# are separated by the '=' character. Any further '=' character is understood as being part
# of the parameter value.
# Mandatory parameters :
nick=Plouf
fullname=PJIRC user
host=www.diboo.net
gui=pixx
# Optional parameters :
asl=true
style:floatingasl=true
#coding=2

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.3 KiB

Binary file not shown.

View File

@ -1,5 +0,0 @@
<Files *>
Order Deny,Allow
Deny from all
Allow from localhost
</Files>

View File

@ -1,34 +0,0 @@
<?php
/* This file creates the new columns for the Redirection Boards mod. If you can't install through the
package manager, place this file in your main forum directory and run it (ie http://www.yoursite.com/smf/RedirectPdb.php) */
// If SSI.php is in the same place as this file, and SMF isn't defined, this is being run standalone.
if (file_exists(dirname(__FILE__) . '/SSI.php') && !defined('SMF'))
require_once(dirname(__FILE__) . '/SSI.php');
// Hmm... no SSI.php and no SMF?
elseif (!defined('SMF'))
die('<b>Error:</b> Cannot install - please verify you put this in the same place as SMF\'s index.php.');
// A new setting
// $newsetting = db_query("INSERT INTO {$db_prefix}settings VALUES ('redirect_hide_columns', '0')", __FILE__, __LINE__);
if(defined('SSI'))
{
echo '<span style="font-color:green">Successfully added new \'redirect_hide_columns\' setting!</span><br />';
}
// Lots of new columns to insert...
$columns = array(// 'is_redirect' => 'tinyint(4) unsigned NOT NULL default \'0\'',
// 'redirect_clicks' => 'mediumint(8) unsigned NOT NULL default \'0\'',
// 'redirect_count_clicks' => 'tinyint(4) unsigned NOT NULL default \'0\'',
// 'redirect_target' => 'tinytext NOT NULL',
// 'redirect_url' => 'tinytext NOT NULL');
foreach($columns AS $column => $definition)
{
$query = db_query("ALTER TABLE {$db_prefix}boards ADD {$column} {$definition}", __FILE__, __LINE__);
// If they're running this manually, let them know that everything worked...
if(defined('SSI'))
{
echo '<span style="font-color:green">Successfully created column \'' . $column . '\'</span><br />';
}
}
?>

File diff suppressed because it is too large Load Diff

View File

@ -1,999 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines
*
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0
*/
if (!defined('SMF'))
die('Hacking attempt...');
/* This file, unpredictable as this might be, handles basic administration.
void AdminMain()
- initialises all the basic context required for the admin center.
- passes execution onto the relevant admin section.
- if the passed section is not found it shows the admin home page.
void AdminHome()
- prepares all the data necessary for the administration front page.
- uses the Admin template along with the admin sub template.
- requires the moderate_forum, manage_membergroups, manage_bans,
admin_forum, manage_permissions, manage_attachments, manage_smileys,
manage_boards, edit_news, or send_mail permission.
- uses the index administrative area.
- can be found by going to ?action=admin.
void AdminSearch()
- allocates out all the search stuff.
void AdminSearchInternal()
- a complicated but relatively quick internal search.
void AdminSearchMember()
- pass through to manage members.
void DisplayAdminFile()
- get one of the admin information files from Simple Machines.
*/
// The main admin handling function.
function AdminMain()
{
global $txt, $context, $scripturl, $sc, $modSettings, $user_info, $settings, $sourcedir, $options, $smcFunc, $boarddir;
// Load the language and templates....
loadLanguage('Admin');
loadTemplate('Admin', 'admin');
// No indexing evil stuff.
$context['robot_no_index'] = true;
require_once($sourcedir . '/Subs-Menu.php');
// Some preferences.
$context['admin_preferences'] = !empty($options['admin_preferences']) ? unserialize($options['admin_preferences']) : array();
// Define all the menu structure - see Subs-Menu.php for details!
$admin_areas = array(
'forum' => array(
'title' => $txt['admin_main'],
'permission' => array('admin_forum', 'manage_permissions', 'moderate_forum', 'manage_membergroups', 'manage_bans', 'send_mail', 'edit_news', 'manage_boards', 'manage_smileys', 'manage_attachments'),
'areas' => array(
'index' => array(
'label' => $txt['admin_center'],
'function' => 'AdminHome',
'icon' => 'administration.gif',
),
'credits' => array(
'label' => $txt['support_credits_title'],
'function' => 'AdminHome',
'icon' => 'support.gif',
),
'news' => array(
'label' => $txt['news_title'],
'file' => 'ManageNews.php',
'function' => 'ManageNews',
'icon' => 'news.gif',
'permission' => array('edit_news', 'send_mail', 'admin_forum'),
'subsections' => array(
'editnews' => array($txt['admin_edit_news'], 'edit_news'),
'mailingmembers' => array($txt['admin_newsletters'], 'send_mail'),
'settings' => array($txt['settings'], 'admin_forum'),
),
),
'packages' => array(
'label' => $txt['package'],
'file' => 'Packages.php',
'function' => 'Packages',
'permission' => array('admin_forum'),
'icon' => 'packages.gif',
'subsections' => array(
'browse' => array($txt['browse_packages']),
'packageget' => array($txt['download_packages'], 'url' => $scripturl . '?action=admin;area=packages;sa=packageget;get'),
'installed' => array($txt['installed_packages']),
'perms' => array($txt['package_file_perms']),
'options' => array($txt['package_settings']),
),
),
'search' => array(
'function' => 'AdminSearch',
'permission' => array('admin_forum'),
'select' => 'index'
),
),
),
'config' => array(
'title' => $txt['admin_config'],
'permission' => array('admin_forum'),
'areas' => array(
'corefeatures' => array(
'label' => $txt['core_settings_title'],
'file' => 'ManageSettings.php',
'function' => 'ModifyCoreFeatures',
'icon' => 'corefeatures.gif',
),
'featuresettings' => array(
'label' => $txt['modSettings_title'],
'file' => 'ManageSettings.php',
'function' => 'ModifyFeatureSettings',
'icon' => 'features.gif',
'subsections' => array(
'basic' => array($txt['mods_cat_features']),
'layout' => array($txt['mods_cat_layout']),
'karma' => array($txt['karma'], 'enabled' => in_array('k', $context['admin_features'])),
'sig' => array($txt['signature_settings_short']),
'profile' => array($txt['custom_profile_shorttitle'], 'enabled' => in_array('cp', $context['admin_features'])),
),
),
'securitysettings' => array(
'label' => $txt['admin_security_moderation'],
'file' => 'ManageSettings.php',
'function' => 'ModifySecuritySettings',
'icon' => 'security.gif',
'subsections' => array(
'general' => array($txt['mods_cat_security_general']),
'spam' => array($txt['antispam_title']),
'moderation' => array($txt['moderation_settings_short'], 'enabled' => substr($modSettings['warning_settings'], 0, 1) == 1),
),
),
'languages' => array(
'label' => $txt['language_configuration'],
'file' => 'ManageServer.php',
'function' => 'ManageLanguages',
'icon' => 'languages.gif',
'subsections' => array(
'edit' => array($txt['language_edit']),
'add' => array($txt['language_add']),
'settings' => array($txt['language_settings']),
),
),
'serversettings' => array(
'label' => $txt['admin_server_settings'],
'file' => 'ManageServer.php',
'function' => 'ModifySettings',
'icon' => 'server.gif',
'subsections' => array(
'general' => array($txt['general_settings']),
'database' => array($txt['database_paths_settings']),
'cookie' => array($txt['cookies_sessions_settings']),
'cache' => array($txt['caching_settings']),
'loads' => array($txt['load_balancing_settings']),
),
),
'current_theme' => array(
'label' => $txt['theme_current_settings'],
'file' => 'Themes.php',
'function' => 'ThemesMain',
'custom_url' => $scripturl . '?action=admin;area=theme;sa=settings;th=' . $settings['theme_id'],
'icon' => 'current_theme.gif',
),
'theme' => array(
'label' => $txt['theme_admin'],
'file' => 'Themes.php',
'function' => 'ThemesMain',
'custom_url' => $scripturl . '?action=admin;area=theme;sa=admin',
'icon' => 'themes.gif',
'subsections' => array(
'admin' => array($txt['themeadmin_admin_title']),
'list' => array($txt['themeadmin_list_title']),
'reset' => array($txt['themeadmin_reset_title']),
'edit' => array($txt['themeadmin_edit_title']),
),
),
'modsettings' => array(
'label' => $txt['admin_modifications'],
'file' => 'ManageSettings.php',
'function' => 'ModifyModSettings',
'icon' => 'modifications.gif',
'subsections' => array(
'general' => array($txt['mods_cat_modifications_misc']),
// Mod Authors for a "ADD AFTER" on this line. Ensure you end your change with a comma. For example:
// 'shout' => array($txt['shout']),
// Note the comma!! The setting with automatically appear with the first mod to be added.
),
),
),
),
'layout' => array(
'title' => $txt['layout_controls'],
'permission' => array('manage_boards', 'admin_forum', 'manage_smileys', 'manage_attachments', 'moderate_forum'),
'areas' => array(
'manageboards' => array(
'label' => $txt['admin_boards'],
'file' => 'ManageBoards.php',
'function' => 'ManageBoards',
'icon' => 'boards.gif',
'permission' => array('manage_boards'),
'subsections' => array(
'main' => array($txt['boardsEdit']),
'newcat' => array($txt['mboards_new_cat']),
'settings' => array($txt['settings'], 'admin_forum'),
),
),
'postsettings' => array(
'label' => $txt['manageposts'],
'file' => 'ManagePosts.php',
'function' => 'ManagePostSettings',
'permission' => array('admin_forum'),
'icon' => 'posts.gif',
'subsections' => array(
'posts' => array($txt['manageposts_settings']),
'bbc' => array($txt['manageposts_bbc_settings']),
'censor' => array($txt['admin_censored_words']),
'topics' => array($txt['manageposts_topic_settings']),
),
),
'managecalendar' => array(
'label' => $txt['manage_calendar'],
'file' => 'ManageCalendar.php',
'function' => 'ManageCalendar',
'icon' => 'calendar.gif',
'permission' => array('admin_forum'),
'enabled' => in_array('cd', $context['admin_features']),
'subsections' => array(
'holidays' => array($txt['manage_holidays'], 'admin_forum', 'enabled' => !empty($modSettings['cal_enabled'])),
'settings' => array($txt['calendar_settings'], 'admin_forum'),
),
),
'managesearch' => array(
'label' => $txt['manage_search'],
'file' => 'ManageSearch.php',
'function' => 'ManageSearch',
'icon' => 'search.gif',
'permission' => array('admin_forum'),
'subsections' => array(
'weights' => array($txt['search_weights']),
'method' => array($txt['search_method']),
'settings' => array($txt['settings']),
),
),
'smileys' => array(
'label' => $txt['smileys_manage'],
'file' => 'ManageSmileys.php',
'function' => 'ManageSmileys',
'icon' => 'smiley.gif',
'permission' => array('manage_smileys'),
'subsections' => array(
'editsets' => array($txt['smiley_sets']),
'addsmiley' => array($txt['smileys_add'], 'enabled' => !empty($modSettings['smiley_enable'])),
'editsmileys' => array($txt['smileys_edit'], 'enabled' => !empty($modSettings['smiley_enable'])),
'setorder' => array($txt['smileys_set_order'], 'enabled' => !empty($modSettings['smiley_enable'])),
'editicons' => array($txt['icons_edit_message_icons'], 'enabled' => !empty($modSettings['messageIcons_enable'])),
'settings' => array($txt['settings']),
),
),
'manageattachments' => array(
'label' => $txt['attachments_avatars'],
'file' => 'ManageAttachments.php',
'function' => 'ManageAttachments',
'icon' => 'attachment.gif',
'permission' => array('manage_attachments'),
'subsections' => array(
'browse' => array($txt['attachment_manager_browse']),
'attachments' => array($txt['attachment_manager_settings']),
'avatars' => array($txt['attachment_manager_avatar_settings']),
'maintenance' => array($txt['attachment_manager_maintenance']),
),
),
),
),
'members' => array(
'title' => $txt['admin_manage_members'],
'permission' => array('moderate_forum', 'manage_membergroups', 'manage_bans', 'manage_permissions', 'admin_forum'),
'areas' => array(
'viewmembers' => array(
'label' => $txt['admin_users'],
'file' => 'ManageMembers.php',
'function' => 'ViewMembers',
'icon' => 'members.gif',
'permission' => array('moderate_forum'),
'subsections' => array(
'all' => array($txt['view_all_members']),
'search' => array($txt['mlist_search']),
),
),
'membergroups' => array(
'label' => $txt['admin_groups'],
'file' => 'ManageMembergroups.php',
'function' => 'ModifyMembergroups',
'icon' => 'membergroups.gif',
'permission' => array('manage_membergroups'),
'subsections' => array(
'index' => array($txt['membergroups_edit_groups'], 'manage_membergroups'),
'add' => array($txt['membergroups_new_group'], 'manage_membergroups'),
'settings' => array($txt['settings'], 'admin_forum'),
),
),
'permissions' => array(
'label' => $txt['edit_permissions'],
'file' => 'ManagePermissions.php',
'function' => 'ModifyPermissions',
'icon' => 'permissions.gif',
'permission' => array('manage_permissions'),
'subsections' => array(
'index' => array($txt['permissions_groups'], 'manage_permissions'),
'board' => array($txt['permissions_boards'], 'manage_permissions'),
'profiles' => array($txt['permissions_profiles'], 'manage_permissions'),
'postmod' => array($txt['permissions_post_moderation'], 'manage_permissions', 'enabled' => $modSettings['postmod_active']),
'settings' => array($txt['settings'], 'admin_forum'),
),
),
'regcenter' => array(
'label' => $txt['registration_center'],
'file' => 'ManageRegistration.php',
'function' => 'RegCenter',
'icon' => 'regcenter.gif',
'permission' => array('admin_forum', 'moderate_forum'),
'subsections' => array(
'register' => array($txt['admin_browse_register_new'], 'moderate_forum'),
'agreement' => array($txt['registration_agreement'], 'admin_forum'),
'reservednames' => array($txt['admin_reserved_set'], 'admin_forum'),
'settings' => array($txt['settings'], 'admin_forum'),
),
),
'ban' => array(
'label' => $txt['ban_title'],
'file' => 'ManageBans.php',
'function' => 'Ban',
'icon' => 'ban.gif',
'permission' => 'manage_bans',
'subsections' => array(
'list' => array($txt['ban_edit_list']),
'add' => array($txt['ban_add_new']),
'browse' => array($txt['ban_trigger_browse']),
'log' => array($txt['ban_log']),
),
),
'paidsubscribe' => array(
'label' => $txt['paid_subscriptions'],
'enabled' => in_array('ps', $context['admin_features']),
'file' => 'ManagePaid.php',
'icon' => 'paid.gif',
'function' => 'ManagePaidSubscriptions',
'permission' => 'admin_forum',
'subsections' => array(
'view' => array($txt['paid_subs_view']),
'settings' => array($txt['settings']),
),
),
'sengines' => array(
'label' => $txt['search_engines'],
'enabled' => in_array('sp', $context['admin_features']),
'file' => 'ManageSearchEngines.php',
'icon' => 'engines.gif',
'function' => 'SearchEngines',
'permission' => 'admin_forum',
'subsections' => array(
'stats' => array($txt['spider_stats']),
'logs' => array($txt['spider_logs']),
'spiders' => array($txt['spiders']),
'settings' => array($txt['settings']),
),
),
),
),
'maintenance' => array(
'title' => $txt['admin_maintenance'],
'permission' => array('admin_forum'),
'areas' => array(
'maintain' => array(
'label' => $txt['maintain_title'],
'file' => 'ManageMaintenance.php',
'icon' => 'maintain.gif',
'function' => 'ManageMaintenance',
'subsections' => array(
'routine' => array($txt['maintain_sub_routine'], 'admin_forum'),
'database' => array($txt['maintain_sub_database'], 'admin_forum'),
'members' => array($txt['maintain_sub_members'], 'admin_forum'),
'topics' => array($txt['maintain_sub_topics'], 'admin_forum'),
),
),
'scheduledtasks' => array(
'label' => $txt['maintain_tasks'],
'file' => 'ManageScheduledTasks.php',
'icon' => 'scheduled.gif',
'function' => 'ManageScheduledTasks',
'subsections' => array(
'tasks' => array($txt['maintain_tasks'], 'admin_forum'),
'tasklog' => array($txt['scheduled_log'], 'admin_forum'),
),
),
'mailqueue' => array(
'label' => $txt['mailqueue_title'],
'file' => 'ManageMail.php',
'function' => 'ManageMail',
'icon' => 'mail.gif',
'subsections' => array(
'browse' => array($txt['mailqueue_browse'], 'admin_forum'),
'settings' => array($txt['mailqueue_settings'], 'admin_forum'),
),
),
'reports' => array(
'enabled' => in_array('rg', $context['admin_features']),
'label' => $txt['generate_reports'],
'file' => 'Reports.php',
'function' => 'ReportsMain',
'icon' => 'reports.gif',
),
'logs' => array(
'label' => $txt['logs'],
'function' => 'AdminLogs',
'icon' => 'logs.gif',
'subsections' => array(
'errorlog' => array($txt['errlog'], 'admin_forum', 'enabled' => !empty($modSettings['enableErrorLogging']), 'url' => $scripturl . '?action=admin;area=logs;sa=errorlog;desc'),
'adminlog' => array($txt['admin_log'], 'admin_forum', 'enabled' => in_array('ml', $context['admin_features'])),
'modlog' => array($txt['moderation_log'], 'admin_forum', 'enabled' => in_array('ml', $context['admin_features'])),
'banlog' => array($txt['ban_log'], 'manage_bans'),
'spiderlog' => array($txt['spider_logs'], 'admin_forum', 'enabled' => in_array('sp', $context['admin_features'])),
'tasklog' => array($txt['scheduled_log'], 'admin_forum'),
'pruning' => array($txt['pruning_title'], 'admin_forum'),
),
),
'repairboards' => array(
'label' => $txt['admin_repair'],
'file' => 'RepairBoards.php',
'function' => 'RepairBoards',
'select' => 'maintain',
'hidden' => true,
),
),
),
);
// Any files to include for administration?
if (!empty($modSettings['integrate_admin_include']))
{
$admin_includes = explode(',', $modSettings['integrate_admin_include']);
foreach ($admin_includes as $include)
{
$include = strtr(trim($include), array('$boarddir' => $boarddir, '$sourcedir' => $sourcedir, '$themedir' => $settings['theme_dir']));
if (file_exists($include))
require_once($include);
}
}
// Let them modify admin areas easily.
call_integration_hook('integrate_admin_areas', array(&$admin_areas));
// Make sure the administrator has a valid session...
validateSession();
// Actually create the menu!
$admin_include_data = createMenu($admin_areas);
unset($admin_areas);
// Nothing valid?
if ($admin_include_data == false)
fatal_lang_error('no_access', false);
// Build the link tree.
$context['linktree'][] = array(
'url' => $scripturl . '?action=admin',
'name' => $txt['admin_center'],
);
if (isset($admin_include_data['current_area']) && $admin_include_data['current_area'] != 'index')
$context['linktree'][] = array(
'url' => $scripturl . '?action=admin;area=' . $admin_include_data['current_area'] . ';' . $context['session_var'] . '=' . $context['session_id'],
'name' => $admin_include_data['label'],
);
if (!empty($admin_include_data['current_subsection']) && $admin_include_data['subsections'][$admin_include_data['current_subsection']][0] != $admin_include_data['label'])
$context['linktree'][] = array(
'url' => $scripturl . '?action=admin;area=' . $admin_include_data['current_area'] . ';sa=' . $admin_include_data['current_subsection'] . ';' . $context['session_var'] . '=' . $context['session_id'],
'name' => $admin_include_data['subsections'][$admin_include_data['current_subsection']][0],
);
// Make a note of the Unique ID for this menu.
$context['admin_menu_id'] = $context['max_menu_id'];
$context['admin_menu_name'] = 'menu_data_' . $context['admin_menu_id'];
// Why on the admin are we?
$context['admin_area'] = $admin_include_data['current_area'];
// Now - finally - call the right place!
if (isset($admin_include_data['file']))
require_once($sourcedir . '/' . $admin_include_data['file']);
$admin_include_data['function']();
}
// The main administration section.
function AdminHome()
{
global $sourcedir, $forum_version, $txt, $scripturl, $context, $user_info, $boardurl, $modSettings, $smcFunc;
// You have to be able to do at least one of the below to see this page.
isAllowedTo(array('admin_forum', 'manage_permissions', 'moderate_forum', 'manage_membergroups', 'manage_bans', 'send_mail', 'edit_news', 'manage_boards', 'manage_smileys', 'manage_attachments'));
// Find all of this forum's administrators...
require_once($sourcedir . '/Subs-Membergroups.php');
if (listMembergroupMembers_Href($context['administrators'], 1, 32) && allowedTo('manage_membergroups'))
{
// Add a 'more'-link if there are more than 32.
$context['more_admins_link'] = '<a href="' . $scripturl . '?action=moderate;area=viewgroups;sa=members;group=1">' . $txt['more'] . '</a>';
}
// Load the credits stuff.
require_once($sourcedir . '/Who.php');
Credits(true);
// This makes it easier to get the latest news with your time format.
$context['time_format'] = urlencode($user_info['time_format']);
$context['current_versions'] = array(
'php' => array('title' => $txt['support_versions_php'], 'version' => PHP_VERSION),
'db' => array('title' => sprintf($txt['support_versions_db'], $smcFunc['db_title']), 'version' => ''),
'server' => array('title' => $txt['support_versions_server'], 'version' => $_SERVER['SERVER_SOFTWARE']),
);
$context['forum_version'] = $forum_version;
// Get a list of current server versions.
require_once($sourcedir . '/Subs-Admin.php');
$checkFor = array(
'gd',
'db_server',
'mmcache',
'eaccelerator',
'phpa',
'apc',
'memcache',
'xcache',
'php',
'server',
);
$context['current_versions'] = getServerVersions($checkFor);
$context['can_admin'] = allowedTo('admin_forum');
$context['sub_template'] = $context['admin_area'] == 'credits' ? 'credits' : 'admin';
$context['page_title'] = $context['admin_area'] == 'credits' ? $txt['support_credits_title'] : $txt['admin_center'];
// The format of this array is: permission, action, title, description, icon.
$quick_admin_tasks = array(
array('', 'credits', 'support_credits_title', 'support_credits_info', 'support_and_credits.png'),
array('admin_forum', 'featuresettings', 'modSettings_title', 'modSettings_info', 'features_and_options.png'),
array('admin_forum', 'maintain', 'maintain_title', 'maintain_info', 'forum_maintenance.png'),
array('manage_permissions', 'permissions', 'edit_permissions', 'edit_permissions_info', 'permissions.png'),
array('admin_forum', 'theme;sa=admin;' . $context['session_var'] . '=' . $context['session_id'], 'theme_admin', 'theme_admin_info', 'themes_and_layout.png'),
array('admin_forum', 'packages', 'package', 'package_info', 'packages.png'),
array('manage_smileys', 'smileys', 'smileys_manage', 'smileys_manage_info', 'smilies_and_messageicons.png'),
array('moderate_forum', 'viewmembers', 'admin_users', 'member_center_info', 'members.png'),
);
$context['quick_admin_tasks'] = array();
foreach ($quick_admin_tasks as $task)
{
if (!empty($task[0]) && !allowedTo($task[0]))
continue;
$context['quick_admin_tasks'][] = array(
'href' => $scripturl . '?action=admin;area=' . $task[1],
'link' => '<a href="' . $scripturl . '?action=admin;area=' . $task[1] . '">' . $txt[$task[2]] . '</a>',
'title' => $txt[$task[2]],
'description' => $txt[$task[3]],
'icon' => $task[4],
'is_last' => false
);
}
if (count($context['quick_admin_tasks']) % 2 == 1)
{
$context['quick_admin_tasks'][] = array(
'href' => '',
'link' => '',
'title' => '',
'description' => '',
'is_last' => true
);
$context['quick_admin_tasks'][count($context['quick_admin_tasks']) - 2]['is_last'] = true;
}
elseif (count($context['quick_admin_tasks']) != 0)
{
$context['quick_admin_tasks'][count($context['quick_admin_tasks']) - 1]['is_last'] = true;
$context['quick_admin_tasks'][count($context['quick_admin_tasks']) - 2]['is_last'] = true;
}
// Lastly, fill in the blanks in the support resources paragraphs.
$txt['support_resources_p1'] = sprintf($txt['support_resources_p1'],
'http://wiki.simplemachines.org/',
'http://wiki.simplemachines.org/smf/features2',
'http://wiki.simplemachines.org/smf/options2',
'http://wiki.simplemachines.org/smf/themes2',
'http://wiki.simplemachines.org/smf/packages2'
);
$txt['support_resources_p2'] = sprintf($txt['support_resources_p2'],
'http://www.simplemachines.org/community/',
'http://www.simplemachines.org/redirect/english_support',
'http://www.simplemachines.org/redirect/international_support_boards',
'http://www.simplemachines.org/redirect/smf_support',
'http://www.simplemachines.org/redirect/customize_support'
);
}
// Get one of the admin information files from Simple Machines.
function DisplayAdminFile()
{
global $context, $modSettings, $smcFunc;
@ini_set('memory_limit', '32M');
if (empty($_REQUEST['filename']) || !is_string($_REQUEST['filename']))
fatal_lang_error('no_access', false);
$request = $smcFunc['db_query']('', '
SELECT data, filetype
FROM {db_prefix}admin_info_files
WHERE filename = {string:current_filename}
LIMIT 1',
array(
'current_filename' => $_REQUEST['filename'],
)
);
if ($smcFunc['db_num_rows']($request) == 0)
fatal_lang_error('admin_file_not_found', true, array($_REQUEST['filename']));
list ($file_data, $filetype) = $smcFunc['db_fetch_row']($request);
$smcFunc['db_free_result']($request);
// !!! Temp.
// Figure out if sesc is still being used.
if (strpos($file_data, ';sesc=') !== false)
$file_data = '
if (!(\'smfForum_sessionvar\' in window))
window.smfForum_sessionvar = \'sesc\';
' . strtr($file_data, array(';sesc=' => ';\' + window.smfForum_sessionvar + \'='));
$context['template_layers'] = array();
// Lets make sure we aren't going to output anything nasty.
@ob_end_clean();
if (!empty($modSettings['enableCompressedOutput']))
@ob_start('ob_gzhandler');
else
@ob_start();
// Make sure they know what type of file we are.
header('Content-Type: ' . $filetype);
echo $file_data;
obExit(false);
}
// This allocates out all the search stuff.
function AdminSearch()
{
global $txt, $context, $smcFunc, $sourcedir;
isAllowedTo('admin_forum');
// What can we search for?
$subactions = array(
'internal' => 'AdminSearchInternal',
'online' => 'AdminSearchOM',
'member' => 'AdminSearchMember',
);
$context['search_type'] = !isset($_REQUEST['search_type']) || !isset($subactions[$_REQUEST['search_type']]) ? 'internal' : $_REQUEST['search_type'];
$context['search_term'] = isset($_REQUEST['search_term']) ? $smcFunc['htmlspecialchars']($_REQUEST['search_term'], ENT_QUOTES) : '';
$context['sub_template'] = 'admin_search_results';
$context['page_title'] = $txt['admin_search_results'];
// Keep track of what the admin wants.
if (empty($context['admin_preferences']['sb']) || $context['admin_preferences']['sb'] != $context['search_type'])
{
$context['admin_preferences']['sb'] = $context['search_type'];
// Update the preferences.
require_once($sourcedir . '/Subs-Admin.php');
updateAdminPreferences();
}
if (trim($context['search_term']) == '')
$context['search_results'] = array();
else
$subactions[$context['search_type']]();
}
// A complicated but relatively quick internal search.
function AdminSearchInternal()
{
global $context, $txt, $helptxt, $scripturl, $sourcedir;
// Try to get some more memory.
@ini_set('memory_limit', '128M');
// Load a lot of language files.
$language_files = array(
'Help', 'ManageMail', 'ManageSettings', 'ManageCalendar', 'ManageBoards', 'ManagePaid', 'ManagePermissions', 'Search',
'Login', 'ManageSmileys',
);
loadLanguage(implode('+', $language_files));
// All the files we need to include.
$include_files = array(
'ManageSettings', 'ManageBoards', 'ManageNews', 'ManageAttachments', 'ManageCalendar', 'ManageMail', 'ManagePaid', 'ManagePermissions',
'ManagePosts', 'ManageRegistration', 'ManageSearch', 'ManageSearchEngines', 'ManageServer', 'ManageSmileys',
);
foreach ($include_files as $file)
require_once($sourcedir . '/' . $file . '.php');
/* This is the huge array that defines everything... it's a huge array of items formatted as follows:
0 = Language index (Can be array of indexes) to search through for this setting.
1 = URL for this indexes page.
2 = Help index for help associated with this item (If different from 0)
*/
$search_data = array(
// All the major sections of the forum.
'sections' => array(
),
'settings' => array(
array('COPPA', 'area=regcenter;sa=settings'),
array('CAPTCHA', 'area=securitysettings;sa=spam'),
),
);
// Go through the admin menu structure trying to find suitably named areas!
foreach ($context[$context['admin_menu_name']]['sections'] as $section)
{
foreach ($section['areas'] as $menu_key => $menu_item)
{
$search_data['sections'][] = array($menu_item['label'], 'area=' . $menu_key);
if (!empty($menu_item['subsections']))
foreach ($menu_item['subsections'] as $key => $sublabel)
{
if (isset($sublabel['label']))
$search_data['sections'][] = array($sublabel['label'], 'area=' . $menu_key . ';sa=' . $key);
}
}
}
// This is a special array of functions that contain setting data - we query all these to simply pull all setting bits!
$settings_search = array(
array('ModifyCoreFeatures', 'area=corefeatures'),
array('ModifyBasicSettings', 'area=featuresettings;sa=basic'),
array('ModifyLayoutSettings', 'area=featuresettings;sa=layout'),
array('ModifyKarmaSettings', 'area=featuresettings;sa=karma'),
array('ModifySignatureSettings', 'area=featuresettings;sa=sig'),
array('ModifyGeneralSecuritySettings', 'area=securitysettings;sa=general'),
array('ModifySpamSettings', 'area=securitysettings;sa=spam'),
array('ModifyModerationSettings', 'area=securitysettings;sa=moderation'),
array('ModifyGeneralModSettings', 'area=modsettings;sa=general'),
// Mod authors if you want to be "real freaking good" then add any setting pages for your mod BELOW this line!
array('ManageAttachmentSettings', 'area=manageattachments;sa=attachments'),
array('ManageAvatarSettings', 'area=manageattachments;sa=avatars'),
array('ModifyCalendarSettings', 'area=managecalendar;sa=settings'),
array('EditBoardSettings', 'area=manageboards;sa=settings'),
array('ModifyMailSettings', 'area=mailqueue;sa=settings'),
array('ModifyNewsSettings', 'area=news;sa=settings'),
array('GeneralPermissionSettings', 'area=permissions;sa=settings'),
array('ModifyPostSettings', 'area=postsettings;sa=posts'),
array('ModifyBBCSettings', 'area=postsettings;sa=bbc'),
array('ModifyTopicSettings', 'area=postsettings;sa=topics'),
array('EditSearchSettings', 'area=managesearch;sa=settings'),
array('EditSmileySettings', 'area=smileys;sa=settings'),
array('ModifyGeneralSettings', 'area=serversettings;sa=general'),
array('ModifyDatabaseSettings', 'area=serversettings;sa=database'),
array('ModifyCookieSettings', 'area=serversettings;sa=cookie'),
array('ModifyCacheSettings', 'area=serversettings;sa=cache'),
array('ModifyLanguageSettings', 'area=languages;sa=settings'),
array('ModifyRegistrationSettings', 'area=regcenter;sa=settings'),
array('ManageSearchEngineSettings', 'area=sengines;sa=settings'),
array('ModifySubscriptionSettings', 'area=paidsubscribe;sa=settings'),
array('ModifyPruningSettings', 'area=logs;sa=pruning'),
);
foreach ($settings_search as $setting_area)
{
// Get a list of their variables.
$config_vars = $setting_area[0](true);
foreach ($config_vars as $var)
if (!empty($var[1]) && !in_array($var[0], array('permissions', 'switch')))
$search_data['settings'][] = array($var[(isset($var[2]) && in_array($var[2], array('file', 'db'))) ? 0 : 1], $setting_area[1]);
}
$context['page_title'] = $txt['admin_search_results'];
$context['search_results'] = array();
$search_term = strtolower($context['search_term']);
// Go through all the search data trying to find this text!
foreach ($search_data as $section => $data)
{
foreach ($data as $item)
{
$found = false;
if (!is_array($item[0]))
$item[0] = array($item[0]);
foreach ($item[0] as $term)
{
$lc_term = strtolower($term);
if (strpos($lc_term, $search_term) !== false || (isset($txt[$term]) && strpos(strtolower($txt[$term]), $search_term) !== false) || (isset($txt['setting_' . $term]) && strpos(strtolower($txt['setting_' . $term]), $search_term) !== false))
{
$found = $term;
break;
}
}
if ($found)
{
// Format the name - and remove any descriptions the entry may have.
$name = isset($txt[$found]) ? $txt[$found] : (isset($txt['setting_' . $found]) ? $txt['setting_' . $found] : $found);
$name = preg_replace('~<(?:div|span)\sclass="smalltext">.+?</(?:div|span)>~', '', $name);
$context['search_results'][] = array(
'url' => (substr($item[1], 0, 4) == 'area' ? $scripturl . '?action=admin;' . $item[1] : $item[1]) . ';' . $context['session_var'] . '=' . $context['session_id'] . ((substr($item[1], 0, 4) == 'area' && $section == 'settings' ? '#' . $item[0][0] : '')),
'name' => $name,
'type' => $section,
'help' => shorten_subject(isset($item[2]) ? strip_tags($helptxt[$item2]) : (isset($helptxt[$found]) ? strip_tags($helptxt[$found]) : ''), 255),
);
}
}
}
}
// All this does is pass through to manage members.
function AdminSearchMember()
{
global $context, $sourcedir;
require_once($sourcedir . '/ManageMembers.php');
$_REQUEST['sa'] = 'query';
$_POST['membername'] = $context['search_term'];
ViewMembers();
}
// This file allows the user to search the SM online manual for a little of help.
function AdminSearchOM()
{
global $context, $sourcedir;
$docsURL = 'docs.simplemachines.org';
$context['doc_scripturl'] = 'http://docs.simplemachines.org/index.php';
// Set all the parameters search might expect.
$postVars = array(
'search' => $context['search_term'],
);
// Encode the search data.
foreach ($postVars as $k => $v)
$postVars[$k] = urlencode($k) . '=' . urlencode($v);
// This is what we will send.
$postVars = implode('&', $postVars);
// Get the results from the doc site.
require_once($sourcedir . '/Subs-Package.php');
$search_results = fetch_web_data($context['doc_scripturl'] . '?action=search2&xml', $postVars);
// If we didn't get any xml back we are in trouble - perhaps the doc site is overloaded?
if (!$search_results || preg_match('~<' . '\?xml\sversion="\d+\.\d+"\sencoding=".+?"\?' . '>\s*(<smf>.+?</smf>)~is', $search_results, $matches) != true)
fatal_lang_error('cannot_connect_doc_site');
$search_results = $matches[1];
// Otherwise we simply walk through the XML and stick it in context for display.
$context['search_results'] = array();
loadClassFile('Class-Package.php');
// Get the results loaded into an array for processing!
$results = new xmlArray($search_results, false);
// Move through the smf layer.
if (!$results->exists('smf'))
fatal_lang_error('cannot_connect_doc_site');
$results = $results->path('smf[0]');
// Are there actually some results?
if (!$results->exists('noresults') && !$results->exists('results'))
fatal_lang_error('cannot_connect_doc_site');
elseif ($results->exists('results'))
{
foreach ($results->set('results/result') as $result)
{
if (!$result->exists('messages'))
continue;
$context['search_results'][$result->fetch('id')] = array(
'topic_id' => $result->fetch('id'),
'relevance' => $result->fetch('relevance'),
'board' => array(
'id' => $result->fetch('board/id'),
'name' => $result->fetch('board/name'),
'href' => $result->fetch('board/href'),
),
'category' => array(
'id' => $result->fetch('category/id'),
'name' => $result->fetch('category/name'),
'href' => $result->fetch('category/href'),
),
'messages' => array(),
);
// Add the messages.
foreach ($result->set('messages/message') as $message)
$context['search_results'][$result->fetch('id')]['messages'][] = array(
'id' => $message->fetch('id'),
'subject' => $message->fetch('subject'),
'body' => $message->fetch('body'),
'time' => $message->fetch('time'),
'timestamp' => $message->fetch('timestamp'),
'start' => $message->fetch('start'),
'author' => array(
'id' => $message->fetch('author/id'),
'name' => $message->fetch('author/name'),
'href' => $message->fetch('author/href'),
),
);
}
}
}
// This function decides which log to load.
function AdminLogs()
{
global $sourcedir, $context, $txt, $scripturl;
// These are the logs they can load.
$log_functions = array(
'errorlog' => array('ManageErrors.php', 'ViewErrorLog'),
'adminlog' => array('Modlog.php', 'ViewModlog'),
'modlog' => array('Modlog.php', 'ViewModlog'),
'banlog' => array('ManageBans.php', 'BanLog'),
'spiderlog' => array('ManageSearchEngines.php', 'SpiderLogs'),
'tasklog' => array('ManageScheduledTasks.php', 'TaskLog'),
'pruning' => array('ManageSettings.php', 'ModifyPruningSettings'),
);
$sub_action = isset($_REQUEST['sa']) && isset($log_functions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'errorlog';
// If it's not got a sa set it must have come here for first time, pretend error log should be reversed.
if (!isset($_REQUEST['sa']))
$_REQUEST['desc'] = true;
// Setup some tab stuff.
$context[$context['admin_menu_name']]['tab_data'] = array(
'title' => $txt['logs'],
'help' => '',
'description' => $txt['maintain_info'],
'tabs' => array(
'errorlog' => array(
'url' => $scripturl . '?action=admin;area=logs;sa=errorlog;desc',
'description' => sprintf($txt['errlog_desc'], $txt['remove']),
),
'adminlog' => array(
'description' => $txt['admin_log_desc'],
),
'modlog' => array(
'description' => $txt['moderation_log_desc'],
),
'banlog' => array(
'description' => $txt['ban_log_description'],
),
'spiderlog' => array(
'description' => $txt['spider_log_desc'],
),
'tasklog' => array(
'description' => $txt['scheduled_log_desc'],
),
'pruning' => array(
'description' => $txt['pruning_log_desc'],
),
),
);
require_once($sourcedir . '/' . $log_functions[$sub_action][0]);
$log_functions[$sub_action][1]();
}
?>

View File

@ -1,364 +0,0 @@
<?php
/******************************************************************************
* Ads.php *
*******************************************************************************
* SMF: Simple Machines Forum - Ad Management Mod *
* *
* =========================================================================== *
* Software Version: Ad mod: 2.3 *
* Software by: jerm *
* Copyright 2006-2007 by: jerm *
* Support site: www.smfads.com *
*******************************************************************************
* This mod is free software; you may redistribute it and/or modify it as long *
* as you credit me for the original mod. This mod is distributed in the hope *
* that it is and will be useful, but WITHOUT ANY WARRANTIES; without even any *
* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* *
* All SMF copyrights are still in effect. Anything not mine is theirs. Enjoy! *
* Some code found in here is copy written code by SMF, therefore it can not *
* be redistributed without official consent from myself or SMF. *
******************************************************************************/
if (!defined('SMF'))
die('Hacking attempt...');
function Ads()
{
global $context, $txt, $scripturl;
// You need to be an admin to edit settings!
isAllowedTo('admin_forum');
// All the admin bar, to make it right.
// adminIndex('edit_addmod');
loadTemplate('Ads');
loadLanguage('Ads');
// Will need the utility functions from here.
// require_once($sourcedir . '/ManageServer.php');
$context['page_title'] = $txt['ad_management'];
// Delegation makes the world... that is, the package manager go 'round.
$subActions = array(
'main' => array('mainAds','admin_forum'),
'add' => array('addAds','admin_forum'),
'edit' => array('editAds','admin_forum'),
'delete' => array('deleteAds','admin_forum'),
'reports' => array('reportsAds','admin_forum'),
'settings' => array('settingsAds','admin_forum'),
'credits' => array('creditsAds','admin_forum'),
'help' => array('helpAds','admin_forum'),
);
// By default do the basic settings.
$_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'main';
// Set up some tabs...
$context[$context['admin_menu_name']]['tab_data'] = array(
'title' => $txt['ad_management'],
'description' => $txt['ad_management_disc'],
'tabs' => array(
'main' => array(
'title' => $txt['ad_management_main'],
//'href' => $scripturl . '?action=ads',
),
'add' => array(
'title' => $txt['ad_management_add'],
//'href' => $scripturl . '?action=ads;sa=add',
),
'reports' => array(
'title' => $txt['ad_management_reports'],
//'href' => $scripturl . '?action=ads;sa=reports',
),
'settings' => array(
'title' => $txt['ad_management_settings'],
//'href' => $scripturl . '?action=ads;sa=settings',
),
'credits' => array(
'title' => $txt['ad_management_credits'],
//'href' => $scripturl . '?action=ads;sa=credits',
//'is_last' => true,
),
),
);
/*
// Tabs for browsing the different ban functions.
$context[$context['admin_menu_name']]['tab_data'] = array(
'title' => $txt['manageposts_title'],
'help' => 'posts_and_topics',
'description' => $txt['manageposts_description'],
'tabs' => array(
'posts' => array(
'description' => $txt['manageposts_settings_description'],
),
'bbc' => array(
'description' => $txt['manageposts_bbc_settings_description'],
),
'censor' => array(
'description' => $txt['admin_censored_desc'],
),
'topics' => array(
'description' => $txt['manageposts_topic_settings_description'],
),
),
);
*/
// Call the right function for this sub-acton.
$subActions[$_REQUEST['sa']][0]();
/*
// Attempt to automatically select the right tab.
if (isset($context['admin_tabs']['tabs'][$context['sub_action']]))
$context['admin_tabs']['tabs'][$context['sub_action']]['is_selected'] = true;
// Otherwise it's going to be the browse anyway...
else
$context['admin_tabs']['tabs']['main']['is_selected'] = true;
// Call the right function.
$subActions[$_REQUEST['sa']]();
*/
}
function mainAds()
{
global $context, $txt;
$context['sub_template'] = 'main';
$context['page_title'] = $txt['ad_management_main'];
}
function addAds()
{
global $context, $txt, $smcFunc;
// The delete this membergroup button was pressed.
if (isset($_POST['add']))
{
if(empty($_POST['name']) || empty($_POST['content']))
fatal_lang_error('error_ads_missing_info', false);
else
{
//Insert the basic info for the ads. Settings will come after this
$_POST = escapestring__recursive($_POST);
$smcFunc['db_query']('',"
INSERT INTO {db_prefix}ads
(NAME,CONTENT)
VALUES ('$_POST[name]', '$_POST[content]')");
$advertsid = $smcFunc['db_insert_id']("{db_prefix}ads", 'ADS_ID');;
//Settings for the ads
$adsUpdate = array();
//Which Boards should this add appear on? 0 for all boards
if (isset($_POST['boards']))
$adsUpdate[] = 'BOARDS = "' . $_POST['boards'] .'"';
//Which membergroups should see this add? 0 for all membergroups
//Should this add display in posts? If so which ones? 0 for no posts
if (isset($_POST['posts']))
$adsUpdate[] = 'POSTS = "' . $_POST['posts'] .'"';
//Display this ad between cateogires
if (isset($_POST['category']))
$adsUpdate[] = 'CATEGORY = "' . $_POST['category'] .'"';
//What type of ad is this? Html=0 PHP=1
if (isset($_POST['type']))
$adsUpdate[] = 'TYPE = ' . ($_POST['type'] ? '1' : '0');
//Display this ad under the Menu?
if (isset($_POST['show_index']))
$adsUpdate[] = 'show_index = ' . ($_POST['show_index'] ? '1' : '0');
//Display this ad on the boards
if (isset($_POST['show_board']))
$adsUpdate[] = 'show_board = ' . ($_POST['show_board'] ? '1' : '0');
//Display this ad on the thread index
if (isset($_POST['show_threadindex']))
$adsUpdate[] = 'show_threadindex = ' . ($_POST['show_threadindex'] ? '1' : '0');
//Display this ad on the thread
if (isset($_POST['show_thread']))
$adsUpdate[] = 'show_thread = ' . ($_POST['show_thread'] ? '1' : '0');
//Display this ad after the last post
if (isset($_POST['show_lastpost']))
$adsUpdate[] = 'show_lastpost = ' . ($_POST['show_lastpost'] ? '1' : '0');
//Display this ad on the bottom of the page
if (isset($_POST['show_bottom']))
$adsUpdate[] = 'show_bottom = ' . ($_POST['show_bottom'] ? '1' : '0');
//Display this ad in the welcome area
if (isset($_POST['show_welcome']))
$adsUpdate[] = 'show_welcome = ' . ($_POST['show_welcome'] ? '1' : '0');
//Display this ad on the top of the page
if (isset($_POST['show_topofpage']))
$adsUpdate[] = 'show_topofpage = ' . ($_POST['show_topofpage'] ? '1' : '0');
//Display this ad tower right
if (isset($_POST['show_towerright']))
$adsUpdate[] = 'show_towerright = ' . ($_POST['show_towerright'] ? '1' : '0');
//Display this ad tower left
if (isset($_POST['show_towerleft']))
$adsUpdate[] = 'show_towerleft = ' . ($_POST['show_towerleft'] ? '1' : '0');
//Display this ad under child boards
if (isset($_POST['show_underchildren']))
$adsUpdate[] = 'show_underchildren = ' . ($_POST['show_underchildren'] ? '1' : '0');
// Do the updates (if any).
if (!empty($adsUpdate))
$smcFunc['db_query']('',"
UPDATE {db_prefix}ads
SET
" . implode(',
', $adsUpdate) . "
WHERE ADS_ID = $advertsid
LIMIT 1");
redirectexit('action=admin;area=ads');
}
}
$context['sub_template'] = 'addAds';
$context['page_title'] = $txt['ad_management_add'];
}
function reportsAds()
{
global $context, $txt;
$context['sub_template'] = 'reportsAds';
$context['page_title'] = $txt['ad_management_reports'];
}
function settingsAds()
{
global $context, $txt;
if (isset($_POST['save']))
{
updateSettings(array(
'ads_displayAdsAdmin' => isset($_POST['ads_displayAdsAdmin']) ? '1' : '0',
'ads_updateReports' => isset($_POST['ads_updateReports']) ? '1' : '0',
'ads_quickDisable' => isset($_POST['ads_quickDisable']) ? '1' : '0',
'ads_lookLikePosts' => isset($_POST['ads_lookLikePosts']) ? '1' : '0',
), true);
redirectexit('action=admin;area=ads;sa=settings');
}
$context['sub_template'] = 'settingsAds';
$context['page_title'] = $txt['ad_management_settings'];
}
function editAds()
{
global $context, $txt, $adverts, $advertsEdit, $smcFunc;
// Make sure this group is editable.
if (empty($_REQUEST['ad']) || (int) $_REQUEST['ad'] < 1)
fatal_lang_error('membergroup_does_not_exist', false);
$_REQUEST['ad'] = (int) $_REQUEST['ad'];
//Deletes the Ad
if (isset($_POST['delete']))
{
//Delete the ad
$smcFunc['db_query']('',"
DELETE FROM {db_prefix}ads
WHERE ADS_ID = '$_REQUEST[ad]'");
redirectexit('action=admin;area=ads');
}
// Updates the info for the ad
elseif (isset($_POST['save']))
{
if(empty($_POST['name']) || empty($_POST['content']))
fatal_lang_error('error_ads_missing_info', false);
else
{
$_POST = escapestring__recursive($_POST);
//Insert the basic info for the ads. Settings will come after this
$adsUpdate = array();
//Fill the array with all the information about ads
$adsUpdate[] = 'BOARDS = "' . $_POST['boards'] .'"';
$adsUpdate[] = 'POSTS = "' . $_POST['posts'] . '"';
$adsUpdate[] = 'CATEGORY = "' . $_POST['category'] . '"';
$adsUpdate[] = 'TYPE = ' . $_POST['type'];
$adsUpdate[] = 'show_index = ' . (empty($_POST['show_index']) ? '0' : '1');
$adsUpdate[] = 'show_board = ' . (empty($_POST['show_board']) ? '0' : '1');
$adsUpdate[] = 'show_threadindex = ' . (empty($_POST['show_threadindex']) ? '0' : '1');
$adsUpdate[] = 'show_thread = ' . (empty($_POST['show_thread']) ? '0' : '1');
$adsUpdate[] = 'show_lastpost = ' . (empty($_POST['show_lastpost']) ? '0' : '1');
$adsUpdate[] = 'show_bottom = ' . (empty($_POST['show_bottom']) ? '0' : '1');
$adsUpdate[] = 'show_welcome = ' . (empty($_POST['show_welcome']) ? '0' : '1');
$adsUpdate[] = 'show_topofpage = ' . (empty($_POST['show_topofpage']) ? '0' : '1');
$adsUpdate[] = 'show_towerright = ' . (empty($_POST['show_towerright']) ? '0' : '1');
$adsUpdate[] = 'show_towerleft = ' . (empty($_POST['show_towerleft']) ? '0' : '1');
$adsUpdate[] = 'show_underchildren = ' . (empty($_POST['show_underchildren']) ? '0' : '1');
$smcFunc['db_query']('',"
UPDATE {db_prefix}ads
SET NAME = '$_POST[name]', CONTENT = '$_POST[content]'
WHERE ADS_ID = '$_REQUEST[ad]'");
$smcFunc['db_query']('',"
UPDATE {db_prefix}ads
SET " . implode(',', $adsUpdate) . "
WHERE ADS_ID = '$_REQUEST[ad]'");
}
redirectexit('action=admin;area=ads');
}
//If nothing is set, then just display the ad.
for ($i=0;$i<count($adverts);$i++)
if($adverts[$i]['id'] == $_REQUEST['ad'])
$advertsEdit = $adverts[$i];
$context['sub_template'] = 'editAds';
$context['page_title'] = $txt['ad_management_main'];
}
function creditsAds()
{
global $context, $txt;
$context['sub_template'] = 'creditsAds';
$context['page_title'] = $txt['ad_management_credits'];
}
function helpAds()
{
global $txt, $helptxt, $context;
// What help string should be used?
if (isset($helptxt[$_GET['help']]))
$context['help_text'] = &$helptxt[$_GET['help']];
elseif (isset($txt[$_GET['help']]))
$context['help_text'] = &$txt[$_GET['help']];
else
$context['help_text'] = $_GET['help'];
// Set the page title to something relevant.
$context['page_title'] = $helptxt['ad_manage_help'];
// Don't show any template layers, just the popup sub template.
$context['template_layers'] = array();
$context['sub_template'] = 'helpAds';
}
?>

View File

@ -1,338 +0,0 @@
<?php
/*******************************************************************************
* SMF Arcade 2.0.11 (http://www.smfarcade.info) *
* Copyright (C) 2004-2007 Niko Pahajoki (http://www.madjoki.com) *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
********************************************************************************
* Arcade.php *
********************************************************************************/
if (!defined('SMF'))
die('Hacking attempt...');
/* This file handles Arcade and loads required files.
void Arcade()
- Initialzes Arcade
- Loads langauge files
- Loads Template
- Loads Arcade
void ArcadeLoad([mode = normal])
- Initializes Arcade
string PermissionQuery()
- Returns permission query to use in WHERE
*/
function Arcade()
{
global $scripturl, $txt, $context, $sourcedir, $ID_MEMBER, $modSettings;
// Is Arcade enabled?
if (empty($modSettings['arcadeEnabled']))
fatal_lang_error('arcade_disabled');
// Do we have permission?
isAllowedTo('arcade_view');
// Information for actions (file, function, [permission])
$subActions = array(
// ArcadeList.php
'rate' => array('ArcadeList.php', 'ArcadeRate', 'arcade_rate'),
'list' => array('ArcadeList.php', 'ArcadeList'),
'favorite' => array('ArcadeList.php', 'ArcadeFavorite', 'arcade_favorite'),
'search' => array('ArcadeList.php', 'ArcadeSearch'),
// ArcadePlay.php
'play' => array('ArcadePlay.php', 'ArcadePlay', 'arcade_play'),
'submit' => array('ArcadePlay.php', 'ArcadeSubmit'),
'highscore' => array('ArcadePlay.php', 'ArcadeHighscore'),
'comment' => array('ArcadePlay.php', 'ArcadeComment'),
// ArcadeStats.php
'stats' => array('ArcadeStats.php', 'ArcadeStats'),
// IBP Arcade
'ibpverify' => array('ArcadePlay.php', 'ArcadeVerifyIBP'),
'ibpsubmit' => array('ArcadePlay.php', 'ArcadeSubmitIBP'),
);
// Fix for broken games which doesn't send sa/do=submit
if (isset($_POST['game']) && isset($_POST['score']) && !isset($_REQUEST['sa']))
$_REQUEST['sa'] = 'submit';
// Short urls like index.php?game=1 or index.php/game,1.html
elseif (isset($_REQUEST['game']) && is_numeric($_REQUEST['game']) && !isset($_REQUEST['sa']))
$_REQUEST['sa'] = 'play';
$_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'list';
if (!in_array($_REQUEST['sa'], array('highscore', 'comment')) && isset($_SESSION['arcade']['highscore']))
unset($_SESSION['arcade']['highscore']);
// Load Arcade
ArcadeLoad('normal');
// Check permission if needed
if (isset($actions[$_REQUEST['sa']][2]))
isAllowedTo($subActions[$_REQUEST['sa']][2]);
require_once($sourcedir . '/' . $subActions[$_REQUEST['sa']][0]);
$subActions[$_REQUEST['sa']][1]();
}
function ArcadeLoad($mode = 'normal', $index = '')
{
global $db_prefix, $scripturl, $txt, $modSettings, $context, $settings, $sourcedir, $user_info, $arcade_version, $ID_MEMBER, $user_profile, $boarddir;
$context['arcade'] = array();
// Version information
$arcade_version = '2.0.11';
$user_info['query_see_game'] = PermissionQuery();
require_once($sourcedir . '/Subs-Arcade.php');
loadLanguage('Arcade');
// Arcade javascript
$context['html_headers'] .= '
<script language="JavaScript" type="text/javascript" src="' . $settings['default_theme_url'] . '/arcade.js"></script>';
// Normal mode
if ($mode == 'normal')
{
loadTemplate('Arcade');
loadTemplate('ArcadeMenu');
// Title
$context['page_title'] = $txt['arcade'];
// Add Arcade to link tree
$context['linktree'][] = array(
'url' => $scripturl . '?action=arcade',
'name' => $txt['arcade'],
);
$context['arcade_tabs'] = array(
'title' => $txt['arcade'],
);
// Tabs to show in every Arcade page
$context['arcade_tabs']['tabs'] = array(
array(
'href' => $scripturl . '?action=arcade',
'title' => $txt['arcade'],
'is_selected' => in_array($_REQUEST['sa'], array('play', 'list', 'highscore', 'submit')),
),
array(
'href' => $scripturl . '?action=arcade;sa=stats',
'title' => $txt['arcade_stats'],
'is_selected' => in_array($_REQUEST['sa'], array('stats')),
)
);
// What I can do?
$context['arcade']['can_play'] = allowedTo('arcade_play');
$context['arcade']['can_favorite'] = allowedTo('arcade_favorite');
$context['arcade']['can_rate'] = allowedTo('arcade_rate');
$context['arcade']['can_submit'] = allowedTo('arcade_submit');
$context['arcade']['can_comment_own'] = allowedTo('arcade_comment_own');
$context['arcade']['can_comment_any'] = allowedTo('arcade_comment_any');
$context['arcade']['can_admin'] = allowedTo('arcade_admin');
// Or can I (do I have enought posts etc.)
if (!empty($modSettings['arcadePostPermission']) && !$context['arcade']['can_admin'])
{
if (!$user_info['is_guest'])
{
loadMemberData($ID_MEMBER, false, 'minimal');
$days = ceil(time() - $user_profile[$ID_MEMBER]['dateRegistered'] / 86400);
// Who didn't syncronise clock?
if ($days < 1)
$days = 1;
$post = $user_profile[$ID_MEMBER]['posts'];
$from = time() - 86400;
$result = db_query("
SELECT COUNT(*)
FROM {$db_prefix}messages AS ms
WHERE ms.modifiedTime > $from
AND ID_MEMBER = $ID_MEMBER", __FILE__, __LINE__);
list ($postPerDay) = mysql_fetch_row($result);
mysql_free_result($result);
}
// Guest cannot have posts
else
{
$post = 0;
$postPerDay = 0;
}
if (!empty($modSettings['arcadePostsPlay']))
$post2 = $post >= $modSettings['arcadePostsPlay'];
else
$post2 = true;
if (!empty($modSettings['arcadePostsPlayPerDay']))
$postPerDay2 = $postPerDay >= $modSettings['arcadePostsPlayPerDay'];
else
$postPerDay2 = true;
if ($user_info['is_guest'])
{
if (!empty($modSettings['arcadePostsPlay']) && !empty($modSettings['arcadePostsPlayPerDay']))
$context['arcade']['notice'] = sprintf($txt['arcade_notice_post_both'], $modSettings['arcadePostsPlay'], $modSettings['arcadePostsPlayPerDay']);
elseif (!empty($modSettings['arcadePostsPlay']))
$context['arcade']['notice'] = sprintf($txt['arcade_notice_post_cumulative'], $modSettings['arcadePostsPlay']);
elseif (!empty($modSettings['arcadePostsPlayPerDay']))
$context['arcade']['notice'] = sprintf($txt['arcade_notice_post_perday'], $modSettings['arcadePostsPlayPerDay']);
}
else
{
$context['arcade']['can_play'] = $post2 && $postPerDay2;
// Should we display notice, and what kind of notice?
if (!$post2 || !$postPerDay2)
{
$p1 = !$post2 ? '<span style="color: red">' . $modSettings['arcadePostsPlay'] . '</span>' : $modSettings['arcadePostsPlay'];
$p2 = !$postPerDay2 ? '<span style="color: red">' . $modSettings['arcadePostsPlayPerDay'] . '</span>' : $modSettings['arcadePostsPlayPerDay'];
if (!empty($modSettings['arcadePostsPlay']) && !empty($modSettings['arcadePostsPlayPerDay']))
$context['arcade']['notice'] = sprintf($txt['arcade_notice_post_both'], $p1, $p2);
elseif (!empty($modSettings['arcadePostsPlay']))
$context['arcade']['notice'] = sprintf($txt['arcade_notice_post_cumulative'], $p1);
elseif (!empty($modSettings['arcadePostsPlayPerDay']))
$context['arcade']['notice'] = sprintf($txt['arcade_notice_post_perday'], $p2);
}
}
}
$context['arcade']['stats'] = array();
// How many games?
$result = db_query("
SELECT count(ID_GAME) AS games
FROM {$db_prefix}arcade_games", __FILE__, __LINE__);
$context['arcade']['stats'] += mysql_fetch_assoc($result);
mysql_free_result($result);
require_once($sourcedir . '/ArcadeStats.php');
$context['arcade']['best_player'] = ArcadeStats_BestPlayers(1);
$context['arcade']['longest_champion'] = ArcadeStats_LongestChampions(1, 'current');
$context['arcade']['most_played'] = ArcadeStats_MostPlayed(1);
// Menu
$context['arcade']['menu'] = array(
array(
'data' => ArcadeGameOfDay(0),
'template' => 'ArcadeMenu_GameOfDay'
),
array(
'data' => array(),
'template' => 'ArcadeMenu_QuickSearch',
),
);
$context['arcade']['latest_scores'] = ArcadeLatestScores(5, 0);
if (!isset($_REQUEST['xml']))
{
$context['template_layers'][] = 'Arcade';
$context['template_layers'][] = 'ArcadeMenu';
}
}
// Admin mode
elseif ($mode == 'admin')
{
loadTemplate('ArcadeAdmin');
loadLanguage('ArcadeAdmin');
if (file_exists($boarddir . '/installArcade.php') && @!unlink($boarddir . '/installArcade.php'))
fatal_lang_error('arcade_arcade_installer_not_removed');
if (!empty($index))
adminIndex($index);
$context['template_layers'][] = 'ArcadeAdmin';
$context['page_title'] = $txt['arcade_admin_title'];
}
}
function PermissionQuery()
{
global $scripturl, $txt, $modSettings, $context, $settings, $sourcedir, $user_info;
// Build permission query
if (!isset($modSettings['arcadePermissionMode']))
$modSettings['arcadePermissionMode'] = 1;
if ($modSettings['arcadePermissionMode'] >= 2)
{
// Can see game?
if ($user_info['is_guest'])
$see_game = 'FIND_IN_SET(-1, game.memberGroups)';
// Administrators can see all games.
elseif ($user_info['is_admin'])
$see_game = '1';
// Registered user.... just the groups in $user_info['groups'].
else
$see_game = '(FIND_IN_SET(' . implode(', game.memberGroups) OR FIND_IN_SET(', $user_info['groups']) . ', game.memberGroups))';
}
if ($modSettings['arcadePermissionMode'] == 1 || $modSettings['arcadePermissionMode'] >= 3)
{
// Can see category?
if ($user_info['is_guest'])
$see_category = 'FIND_IN_SET(-1, category.memberGroups)';
// Administrators can see all games.
elseif ($user_info['is_admin'])
$see_category = '1';
// Registered user.... just the groups in $user_info['groups'].
else
$see_category = '(FIND_IN_SET(' . implode(', category.memberGroups) OR FIND_IN_SET(', $user_info['groups']) . ', category.memberGroups))';
}
// Build final query
if ($modSettings['arcadePermissionMode'] == 0) // No game/category permissions used
return '1';
elseif ($modSettings['arcadePermissionMode'] == 1) // Only category used
return $see_category;
elseif ($modSettings['arcadePermissionMode'] == 2) // Only category used
return $see_game;
elseif ($modSettings['arcadePermissionMode'] == 3) // Required to have permssion to game and category
return "($see_category AND $see_game)";
elseif ($modSettings['arcadePermissionMode'] == 4) // Required to have permssion to game OR category
return "($see_category OR $see_game)";
else // Default
return $see_category;
}
?>

View File

@ -1,793 +0,0 @@
<?php
/**
* Arcade2.php *
*
* SMF Arcade: Simple Machines Forum Arcade Mod *
* ============================================================================= *
* Software Version: SMF Arcade 1.2.4 *
* Software by: Niko Pahajoki (http://www.madjoki.com) *
* Support, News, Updates at: http://www.madjoki.com *
*
*/
function do_init()
{
global $boardurl, $txt, $scripturl, $db_prefix, $boarddir;
global $ID_MEMBER, $sourcedir,$language;
global $context, $user_info, $db_prefix, $modSettings;
$version = 0;
// 0 - 'retail'
// 1 - beta
// 2 - cvs
$context['arcade']['version'] = '1.2.4b'; // Set Version to display (Dont change)
$context['arcade']['version2'] = '1.2.4b'; // Internal Version (Dont change)
$context['arcade']['db_version'] = '1.0.0'; // Database version (Dont change)
if ($version == 2)
{
$context['arcade']['version'] .= " CVS";
}
elseif ($version == 1)
{
$context['arcade']['version'] .= " BETA";
}
return true;
}
function do_checks()
{
global $boardurl, $txt, $scripturl, $db_prefix, $boarddir;
global $ID_MEMBER, $sourcedir,$language;
global $context, $user_info, $db_prefix, $modSettings;
/*
if($modSettings['arcade_version'] != $context['arcade']['db_version'])
{
if(allowedTo('admin_arcade'))
{
header("location: {$boardurl}/arcade_install.php");
}
else
{
fatal_error($txt['arcade_121']);
}
}*/
if($modSettings['arcade_enabled'] == 0)
{
if(!allowedTo('admin_arcade'))
{
fatal_error($txt['arcade_170'] . "<br />" . $modSettings['arcade_message']);
}
else
{
redirectexit('action=arcadeadmin');
}
}
return true;
}
function load_category()
{
global $boardurl, $txt, $scripturl, $db_prefix, $boarddir;
global $ID_MEMBER, $sourcedir,$language;
global $context, $user_info, $db_prefix, $modSettings;
$query = "SELECT * FROM {$db_prefix}games_category";
$result = db_query($query, __FILE__, __LINE__);
while ($cat = mysql_fetch_array($result))
{
// Loop thought all caterogies in database
$q2 = "SELECT count(*) FROM {$db_prefix}games WHERE category='{$cat['id']}' ";
$res = db_query($q2, __FILE__, __LINE__);
$num = mysql_fetch_array($res);
$context['arcade']['category'][$cat['id']] = $cat;
$context['arcade']['category'][$cat['id']]['games'] = $num[0];
}
mysql_free_result($result);
return true;
}
function challenge_count($user, $complete = false)
{
global $boardurl, $txt, $scripturl, $db_prefix, $boarddir;
global $ID_MEMBER, $sourcedir,$language;
global $context, $user_info, $db_prefix, $modSettings;
if($complete_only == false)
{
$query = "SELECT count(*) FROM {$db_prefix}games_challenge WHERE (player1 = '$user' or player2 = '$user') AND complete='0'";
}
else
{
$query = "SELECT count(*) FROM {$db_prefix}games_challenge WHERE (player1 = '$user' or player2 = '$user') AND complete='1'";
}
$res = db_query($query,__FILE__,__LINE__);
$maara = mysql_fetch_array($res);
mysql_free_result($res);
return $maara;
}
function chllange_new($from, $to, $game2, $message)
{
global $boardurl, $txt, $scripturl, $db_prefix, $boarddir;
global $ID_MEMBER, $sourcedir,$language;
global $context, $user_info, $db_prefix, $modSettings;
isAllowedTo('challenge_send');
$context['arcade']['sub'] = "send";
$time = time();
$query7 = "INSERT INTO {$db_prefix}games_challenge SET player1='{$ID_MEMBER}', player2='{$_POST['to']}', game='{$_POST['game']}', message='{$_POST['message']}', time='{$time}'";
db_query($query7,__FILE__,__LINE__);
$cid = db_insert_id();
require_once($sourcedir . '/Subs-Post.php');
$query2 = "SELECT * FROM {$db_prefix}members where ID_MEMBER='{$_POST['to']}'";
$results2 = db_query($query2, __FILE__, __LINE__);
$to = mysql_fetch_array($results2);
if($to['lngfile'] != '' && $to['lngfile'] != null)
{
loadLanguage('Arcade',$to['lngfile']);
}
else
{
loadLanguage('Arcade',$language);
}
$query = "SELECT * FROM {$db_prefix}games where id='{$_POST['game']}'";
$results = db_query($query, __FILE__, __LINE__);
$game = mysql_fetch_array($results);
$subject = $txt['arcade_141'].' '.$game['name'];
$link = "[url={$scripturl}?action=arcade;do=play;challenge={$cid}]{$txt['arcade_94']}[/url] {$txt['arcade_95']} [url={$scripturl}?action=arcade;do=challenge;delete={$cid}]{$txt['arcade_96']}[/url] ";
$message = $txt['arcade_141']."\n".$txt['arcade_142']."\n".$message."\n\n".$link;
mysql_free_result($results2);
mysql_free_result($results);
$recipients = array(
'to' => array($_POST['to']),
'bcc' => array()
);
sendpm($recipients,$subject,$message,false,null);
loadLanguage('Arcade');
}
function challenge_load_results()
{
global $boardurl, $txt, $scripturl, $db_prefix, $boarddir;
global $ID_MEMBER, $sourcedir,$language;
global $context, $user_info, $db_prefix, $modSettings;
$context['arcade']['challenge'] = array();
$per_sivu = $modSettings['arcade_challenge_per_page'];
if(isset($_GET['start'])) $limit = "LIMIT {$_GET['start']},{$per_sivu}";
else $limit = "LIMIT 0,{$per_sivu}";
$query_c = "SELECT * FROM {$db_prefix}games_challenge AS Challenge, {$db_prefix}games AS Games WHERE (Challenge.player2='{$ID_MEMBER}' OR Challenge.player1='{$ID_MEMBER}') AND Challenge.game = Games.id ORDER by time DESC $limit";
$result_c = db_query($query_c, __FILE__, __LINE__);
$i = 0;
$query = "SELECT count(*) FROM {$db_prefix}games_challenge WHERE complete='1'";
$res = db_query($query,__FILE__,__LINE__);
$maara2 = mysql_fetch_array($res);
$per_sivu = $modSettings['arcade_results_per_page'];
$context['arcade']['page_index2'] = str_replace("start","start2",constructPageIndex($scripturl."?action=arcade;do=challenge",$_GET['start2'],$maara2[0],$per_sivu));
mysql_free_result($res);
if(isset($_GET['start2'])) $limit = "LIMIT {$_GET['start2']},{$per_sivu}";
else $limit = "LIMIT 0,{$per_sivu}";
$query_c = "SELECT * FROM {$db_prefix}games_challenge AS Challenge, {$db_prefix}games AS Games WHERE Challenge.game = Games.id AND Challenge.complete='1' ORDER by time DESC $limit";
$result_c = db_query($query_c, __FILE__, __LINE__);
$context['arcade']['challenge2'] = array();
$i = 0;
/* List challenges*/
while ($challenge = mysql_fetch_array($result_c))
{
$context['arcade']['challenge2'][$i] = $challenge;
/* Get data for members */
// Temporary solution
if(!isset($member_temp[$challenge['player1']]))
{
$query_mem = "SELECT * FROM {$db_prefix}members WHERE ID_MEMBER={$challenge['player1']}";
$result_mem = db_query($query_mem, __FILE__, __LINE__);
$member_temp[$challenge['player1']] = mysql_fetch_array($result_mem);
mysql_free_result($result_mem);
}
if(!isset($member_temp[$challenge['player2']]))
{
$query_mem = "SELECT * FROM {$db_prefix}members WHERE ID_MEMBER={$challenge['player2']}";
$result_mem = db_query($query_mem, __FILE__, __LINE__);
$member_temp[$challenge['player2']] = mysql_fetch_array($result_mem);
mysql_free_result($result_mem);
}
$context['arcade']['challenge2'][$i]['player1_info'] = $member_temp[$challenge['player1']];
$context['arcade']['challenge2'][$i]['player2_info'] = $member_temp[$challenge['player2']];
$i++;
}
mysql_free_result($result_c); // Free memory :)
}
function favorite($game,$remove = false)
{
global $boardurl, $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $modSettings;
if($remove == false)
{
$query = "INSERT INTO {$db_prefix}games_favorite SET member='{$ID_MEMBER}', game='{$game['game']}'";
}
else
{
$query = "DELETE FROM {$db_prefix}games_favorite WHERE member='{$ID_MEMBER}' AND game='{$game['game']}'";
}
db_query($query,__FILE__,__LINE__);
}
function get_game_info($game_id)
{
global $boardurl, $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $modSettings;
if(is_numeric($game_id))
{
$query = "SELECT * FROM {$db_prefix}games WHERE id='{$game_id}' LIMIT 0,1";
}
else
{
$query = "SELECT * FROM {$db_prefix}games WHERE game='{$game_id}' LIMIT 0,1";
}
$res = db_query($query,__FILE__,__LINE__);
$game = mysql_fetch_array($res);
mysql_free_result($res);
return $game;
}
function highscore($game_id, $type, $limit = "0,15", $cutoff = 0)
{
global $txt, $scripturl, $db_prefix;
global $ID_MEMBER,$user_profile;
global $context, $user_info, $db_prefix;
if ($type == 0)
{
$type2 = "DESC";
} else
{
$type2 = "ASC";
}
$query = "SELECT * FROM {$db_prefix}games_high WHERE {$db_prefix}games_high.game='{$game_id}' AND {$db_prefix}games_high.stime >= $cutoff ORDER BY {$db_prefix}games_high.score {$type2} limit {$limit}";
$results = db_query($query, __FILE__, __LINE__);
$i = 0;
$pos = -1;
$top10 = array();
while ($score = mysql_fetch_array($results))
{
loadMemberData($score['member']);
if(isset($user_profile[$score['member']]))
{
$top10[$i]['member'] = $user_profile[$score['member']];
}
$top10[$i]['memberid'] = $score['member'];
$top10[$i]['score'] = (float)$score['score'];
$top10[$i]['time'] = $score['stime'];
if($pos = -1)
{
$pos = get_position($game_id,$score['score'],$type,$cutoff);
$top10[$i]['position'] = $pos;
}
else
{
$top10[$i]['position'] = $pos + $i + 1;
}
$top10[$i]['warning'] = $score['warning'];
$top10[$i]['timef'] = timeformat($score['stime'], true);
if ($score['comment'] == null)
{
$top10[$i]['comment'] = doUBBC("[i]{$txt['arcade_25']}[/i]");
}
else
{
$top10[$i]['comment'] = censorText(doUBBC(stripslashes($score['comment'])));
}
$i++;
}
mysql_free_result($results);
return $top10;
}
function arcade_load_us($member)
{
global $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix;
/*
$q = "SELECT member,settings FROM {$db_prefix}games_settings WHERE member='{$member}'";
$r = db_query($q,__FILE__,__LINE__);
$x = mysql_fetch_array($r);
$context['arcade']['user'] = unserialize($x['settings']);
mysql_free_result($r);
*/
return true;
}
function tournament_update($tid = 0)
{
global $txt, $scripturl, $db_prefix;
global $ID_MEMBER,$sourcedir;
global $context, $user_info, $db_prefix;
if($tid == 0) fatal_error("err");
$query = "SELECT * FROM {$db_prefix}games_tournament WHERE tid='{$tid}'";
$res1 = db_query($query,__FILE__,__LINE__);
$tourney = mysql_fetch_array($res1);
mysql_free_result($res1);
$query2 = "SELECT count(member) As pelaajat,round FROM {$db_prefix}games_tournament_results WHERE tid='{$tid}' GROUP BY round";
$res2 = db_query($query2,__FILE__,__LINE__);
//$arr = array();
while($ax = mysql_fetch_array($res2))
{
//$arr[] = $ax;
if($ax['pelaajat'] == $tourney['players']) $cr = $ax['round'] + 1;
}
if($cr > $arr['current_round'])
{
$query2 = "SELECT * FROM {$db_prefix}games_tournament_results WHERE tid='{$tid}' ORDER BY round,score";
$res3 = db_query($query2,__FILE__,__LINE__);
$scores = array();
$max = 100;
$step = 10;
$tama = $max;
$penalty = false;
$edellinen = -1;
while($rr = mysql_fetch_array($res3))
{
if($rr['round'] != $edellinen)
{
$tama = $max;
$edellinen = $rr['round'];
}
if($penalty == true || $tama > 0)
{
$scores[$rr['member']] = $scores[$rr['member']] + $tama;
$tama = $tama - $step;
}
}
$q = "DELETE FROM {$db_prefix}games_tournament_scores WHERE tid='$tid'";
mysql_query($q);
foreach($scores as $member => $score)
{
$q = "INSERT INTO {$db_prefix}games_tournament_scores SET tid='$tid',member='$member',score='$score'";
mysql_query($q);
}
$query3 = "UPDATE {$db_prefix}games_tournament SET current_round='{$cr}' WHERE tid='{$tid}'";
mysql_query($query3);
include_once $sourcedir."/Subs-Post.php";
$q3 = "SELECT * FROM {$db_prefix}games_tournament_players WHERE tid='$tid'";
$res = db_query($q3,__FILE__,__LINE__);
$users = array();
while($data = mysql_fetch_array($res))
{
$users['to'][] = $data['member'];
}
$users['bcc'] = array();
mysql_free_result($res);
sendpm($users,$txt['arcade_250'],$txt['arcade_251']."[url=$scripturl?action=arcade;sa=tournament;id=$tid]".$tourney['name']."[/url]",false);
// PM USERS THAT NEW ROUND HAS STARTED
}
mysql_free_result($res2);
}
function tjoin($tid)
{
global $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix;
if($ID_MEMBER != 0)
{
$q = "INSERT INTO {$db_prefix}games_tournament_players SET tid='$tid', member='{$ID_MEMBER}'";
db_query($q,__FILE__,__LINE__);
}
else
{
fatal_error($txt['arcade_208']);
}
}
function highscore_user($game_id, $type, $member, $limit = "0,1")
{
if ($type == 0)
{
$type2 = "DESC";
}
else
{
$type2 = "ASC";
}
global $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix;
// global $board, $modSettings, $options, $settings
$query = "SELECT * FROM {$db_prefix}games_high,{$db_prefix}members WHERE {$db_prefix}games_high.game='{$game_id}' AND {$db_prefix}members.ID_MEMBER={$db_prefix}games_high.member AND {$db_prefix}games_high.member='{$member}' ORDER BY {$db_prefix}games_high.score {$type2} limit {$limit}";
$results = db_query($query, __FILE__, __LINE__);
$i = 0;
$top10 = array();
while ($score = mysql_fetch_array($results))
{
$top10[$i]['member'] = $score['realName'];
$top10[$i]['memberid'] = $score['member'];
$top10[$i]['score'] = (float)$score['score'];
$top10[$i]['time'] = $score['stime'];
$top10[$i]['timef'] = timeformat($score['stime'], true);
if ($score['comment'] == null)
{
$top10[$i]['comment'] = doUBBC("[i]{$txt['arcade_25']}[/i]");
}
else
{
$top10[$i]['comment'] = doUBBC($score['comment']);
}
// $top10[$i]['comment'] = parsecode($score['comment']);
$i++;
}
mysql_free_result($results);
return $top10;
}
function update_champ($game = "NULL")
{
global $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings;
if ( $modSettings['arcade_months_in_champ'] >= 1 )
{
$cutoff = $modSettings['arcade_months_in_champ'] * (60 * 60 * 24 * 30);
date("",$cutoff);
$cutoff2 = mktime(0,0,0,date("n",$cutoff),1,date("Y",$cutoff));
}
else
{
$cutoff2 = 0;
}
/*
if($game != "NULL") $x = "DELETE FROM {$db_prefix}games_champ WHERE game='{$game}'";
else $x = "DELETE FROM {$db_prefix}games_champ";
$b = db_query($x,__FILE__,__LINE__);
if(!$b)
{
return false;
}*/
if($game != "NULL")$pa = "SELECT * FROM {$db_prefix}games WHERE game='{$game}'";
else $pa = "SELECT * FROM {$db_prefix}games";
$res = db_query($pa,__FILE__,__LINE__);
if(!$res)
{
return false;
}
while($arr = mysql_fetch_array($res))
{
$top = highscore($arr['game'],$arr['highscore'],"0,1",$cutoff2);
$x = "UPDATE {$db_prefix}games SET champion_member='{$top[0]['memberid']}', champion_time='{$top[0]['time']}', champion_score='{$top[0]['score']}' WHERE game='{$arr['game']}'";
$b = db_query($x,__FILE__,__LINE__);
if(!$b)
{
return false;
}
}
return true;
}
function latestscore($count = 3, $pos = false)
{
global $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix;
// global $board, $modSettings, $options, $settings
$query = "SELECT * FROM {$db_prefix}games_high,{$db_prefix}members,{$db_prefix}games WHERE {$db_prefix}games_high.game={$db_prefix}games.game AND {$db_prefix}members.ID_MEMBER={$db_prefix}games_high.member ORDER BY {$db_prefix}games_high.stime DESC LIMIT {$count}";
$results = db_query($query, __FILE__, __LINE__);
$i = 0;
$top10 = array();
while ($score = mysql_fetch_array($results))
{
$latest[$i]['member'] = $score['realName'];
$latest[$i]['memberid'] = $score['member'];
(float)$latest[$i]['score'] = (float)$score['score'];
$latest[$i]['time'] = $score['stime'];
$latest[$i]['timef'] = timeformat($score['stime'], true);
$latest[$i]['game_name'] = $score['name'];
if($pos == true)
$latest[$i]['position'] = get_position($score['game'], $score['score'], $score['highscore']);
if ($score['comment'] == null)
{
$def = "[i]{$txt['arcade_25']}[/i]";
$top10[$i]['comment'] = doUBBC($def);
}
else
{
$top10[$i]['comment'] = doUBBC($score['comment']);
}
$i++;
}
mysql_free_result($results);
return $latest;
}
function get_position($game = "NULL", $score = 0, $type = 0, $cutoff = 0) // Return position where user got
{
global $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix;
$score = round($score);
if ($type == 0) $query = "SELECT count(*) from {$db_prefix}games_high WHERE score > {$score} AND game='{$game}' AND stime >= $cutoff AND member > 0";
else $query = "SELECT count(*) from {$db_prefix}games_high WHERE score < {$score} AND game='{$game}' AND stime >= $cutoff AND member > 0";
$res = db_query($query, __FILE__, __LINE__);
$pos = mysql_fetch_array($res);
mysql_free_result($res);
return $pos[0] + 1;
}
function fhtml($file, $width, $height, $bgcolor)
{
global $scripturl;
$html = '
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="' . $width . '" height="' . $height . '" id="' . $file . '" align="middle">
<param name="allowScriptAccess" value="sameDomain">
<param name="movie" value="'. $scripturl."?action=arcade;sa=download;file=swf" .'">
<param name="quality" value="high">
<param name="bgcolor" value="' . $bgcolor . '">
<embed src="'.$scripturl."?action=arcade;sa=download;file=swf" . '" quality="high" bgcolor="' . $bgcolor . '" width="' . $width . '" height="' . $height . '" id="' . $file . '" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">
</object>
';
return $html;
}
function ArcadePopup($title,$content)
{
global $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix;
$context['template_layers'] = array();
$context['arcade']['popup']['title'] = $title;
$context['arcade']['popup']['content'] = $content;
$context['sub_template'] = 'apopup';
}
function update_rate($game)
{
global $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix;
//$gamx = get_game_info($game);
$q = "SELECT * FROM {$db_prefix}games_rate WHERE game={$game}";
$qa = db_query($q,__FILE__,__LINE__);
$arvo = 0;
$yhteensa = 0;
while($row = mysql_fetch_array($qa))
{
$yhteensa++;
$arvo = $arvo + $row['rate'];
}
$arvo2 = $arvo / $yhteensa;
//$arvo2 = ($arvo) ;
$q = "UPDATE {$db_prefix}games SET rating='{$arvo2}' WHERE id='{$game}'";
db_query($q,__FIlE__,__LINE__);
return true;
}
Function RateGame($game, $rating)
{
global $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix;
$q = 'DELETE FROM '.$db_prefix.'games_rate WHERE game=\''.$game.'\' AND member=\''.$ID_MEMBER.'\'';
db_query($q,__FILE__,__LINE__);
$q = 'INSERT INTO '.$db_prefix.'games_rate SET game=\''.$game.'\', member=\''.$ID_MEMBER.'\', rate=\''.$rating.'\'';
db_query($q,__FILE__,__LINE__);
}
Function UpdateGameInfo()
{
global $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix;
$url = 'http://38.119.119.60/game.info.ini';
$ini = file($url);
if(!$ini){
fatal_error('Game info update failed... ');
}
return parse_ini_array($ini);
}
Function parse_ini_array($d)
{
// Parses ini read with file() into array
$new = array();
$section = 'Default';
foreach ($d as $line)
{
$line = trim($line);
if (substr($line,0,1) == "[" && substr($line,-1,1) == "]")
{
$section = substr($line,1,strlen($line) - 2);
}
else
{
$arr = explode("=",$line,2);
$arr[0] = trim($arr[0]);
$arr[1] = trim($arr[1]);
if(is_numeric($arr[0]))
{
$new[$section][] = explode("|",$arr[1]);
}
else
{
$new[$section][$arr[0]] = explode("|",$arr[1]);
}
}
}
return $new;
}
class custom_game
{
var $session;
var $data;
function save_score($score,$game,$method = 'new')
{
global $boardurl, $txt, $scripturl, $db_prefix, $boarddir;
global $ID_MEMBER, $sourcedir,$language,$user_profile;
global $context, $user_info, $db_prefix, $modSettings;
$time = time();
if($method == 'new')
{
$q = "INSERT INTO {$db_prefix}games_high SET game='{$game}', member='{$ID_MEMBER}', stime='{$time}', score='{$score}'";
db_query($q,__FILE__,__LINE__);
}
elseif($method == 'replace')
{
$q = "DELETE FROM {$db_prefix}games_high WHERE game='{$game}' AND member='{$ID_MEMBER}'";
$q2 = "INSERT INTO {$db_prefix}games_high SET game='{$game}', member='{$ID_MEMBER}', stime='{$time}', score='{$score}'";
db_query($q,__FILE__,__LINE__);
db_query($q2,__FILE__,__LINE__);
}
elseif($method == 'add')
{
$q = "SELECT * FROM {$db_prefix}games_high WHERE game='{$game}' AND member='{$ID_MEMBER}'";
$x = db_query($q,__FILE__,__LINE__);
mysql_free_result($x);
if(db_affected_rows() == 1)
{
$q2 = "UPDATE {$db_prefix}games_high SET score=score+{$score}, stime='{$time}' WHERE game='{$game}' AND member='{$ID_MEMBER}'";
}
else
{
$q2 = "INSERT INTO {$db_prefix}games_high SET game='{$game}', member='{$ID_MEMBER}', stime='{$time}', score='{$score}'";
}
//fatal_error($q2);
db_query($q2,__FILE__,__LINE__);
}
}
}
?>

View File

@ -1,825 +0,0 @@
<?php
/**
* ArcadeAdmin.php *
*
* SMF Arcade: Simple Machines Forum Arcade Mod *
* ============================================================================= *
* Software Version: SMF Arcade 1.2.4 *
* Software by: Niko Pahajoki (http://www.madjoki.com) *
* Support, News, Updates at: http://www.madjoki.com *
*
*/
Function ArcadeAdmin()
{
global $boardurl, $txt, $scripturl, $db_prefix,$sourcedir;
global $ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings,$sourcedir;
require_once($sourcedir."/Arcade2.php");
do_init();
adminIndex('admin_arcade');
$context['page_title'] = "Arcade Admin";
loadTemplate('ArcadeAdmin');
$a = loadLanguage('Arcade');
isAllowedTo('admin_arcade');
$context['template_layers'][] = 'ArcadeAdmin';
$context['arcade_admin']['action'] = "";
$context['arcade']['sub_action'] = "";
$arr = array(
'home' => array(
'name' => &$txt['arcade_115'],
'selected' => false,
'link' => $scripturl.'?action=arcadeadmin',
'last' => false,
),
'games' => array(
'name' => &$txt['arcade_27'],
'selected' => false,
'link' => $scripturl.'?action=arcadeadmin;sa=games',
'last' => false,
),
'install' => array(
'name' => &$txt['arcade_236'],
'selected' => false,
'link' => $scripturl.'?action=arcadeadmin;sa=install',
'last' => false,
),
'settings' => array(
'name' => &$txt['arcade_35'],
'selected' => false,
'link' => $scripturl.'?action=arcadeadmin;sa=settings',
'last' => false,
),
'category' => array(
'name' => &$txt['arcade_144'],
'selected' => false,
'link' => $scripturl.'?action=arcadeadmin;sa=category',
'last' => false,
),
'highscore' => array(
'name' => &$txt['arcade_20'],
'selected' => false,
'link' => $scripturl.'?action=arcadeadmin;sa=highscore',
'last' => true,
),
);
$parents = array(
'game_edit' => 'games',
'install_game' => 'install',
'child' => 'parent',
);
if(!isset($_GET['sa']))
{
$arr['home']['selected'] = true;
$action = 'home';
}
else
{
if(isset($arr[$_GET['sa']]) && is_array($arr[$_GET['sa']]))
{
$arr[$_GET['sa']]['selected'] = true;
}
else
{
if(isset($parents[$_GET['sa']]))
$arr[$parents[$_GET['sa']]]['selected'] = true;
}
$action = $_GET['sa'];
}
$context['arcade_admin']['valinnat'] = $arr;
$context['sub_template'] = "ArcadeAdmin_".$action;
$func = "ArcadeAdmin_".$action;
// if(function_exists($func))
// {
$func();
// }
}
Function ArcadeAdmin_home()
{
// Updated 1.2.4
global $boardurl, $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings;
$context['arcade_admin']['action'] = "main";
}
Function ArcadeAdmin_category()
{
global $boardurl, $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings;
$query = "SELECT * FROM {$db_prefix}games_category";
$result = db_query($query, __FILE__, __LINE__);
while ($cat = mysql_fetch_array($result))
{
// Loop thought all caterogies in database
$context['arcade']['category'][$cat['id']] = $cat['name'];
}
if(!isset($_GET['do']))
{
$context['arcade_admin']['action'] = "cate";
}
elseif($_GET['do'] == "submit")
{
$context['arcade_admin']['action'] = "cate2";
$sql = array();
if(@is_array($_POST['name']))
{
foreach($_POST['name'] as $id => $new_name)
{
if($new_name != $context['arcade']['category'][$id])
{
$sql[] = "UPDATE {$db_prefix}games_category SET name='{$new_name}' WHERE id='{$id}'";
}
if(@$_POST['remove'][$id] == 1)
{
$sql[] = "DELETE FROM {$db_prefix}games_category WHERE id='{$id}'";
}
}
}
if(@is_array($_POST['new']))
{
foreach($_POST['new'] as $id => $cre)
{
if($cre == 1)
{
$sql[] = "INSERT INTO {$db_prefix}games_category SET name='{$_POST['names_new'][$id]}'";
}
}
}
foreach($sql as $temp)
{
db_query($temp,__FILE__,__LINE__);
}
$query = "SELECT * FROM {$db_prefix}games_category";
$result = db_query($query, __FILE__, __LINE__);
$context['arcade']['category'] = array();
while ($cat = mysql_fetch_array($result))
{
// Loop thought all caterogies in database
$context['arcade']['category'][$cat['id']] = $cat['name'];
}
$context['arcade_admin']['action'] = "cate";
}
}
Function ArcadeAdmin_games()
{
global $boardurl, $txt, $scripturl, $db_prefix;
global $boarddir,$ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings,$sourcedir;
$query = "SELECT * FROM {$db_prefix}games_category";
$result = db_query($query, __FILE__, __LINE__);
$context['arcade']['category'][0] = $txt['arcade_67']; // First (0) is reversed for 'No category'
while ($cat = mysql_fetch_array($result))
{
// Loop thought all caterogies in database
$context['arcade']['category'][$cat['id']] = $cat['name'];
}
mysql_free_result($result); // Free memory :)
if(@!$_GET['start'])
{
$_GET['start'] = 0;
}
$limits = $_GET['start'];
$limite = $modSettings['arcade_games_per_page'];
$query = "SELECT * FROM {$db_prefix}games ORDER BY 'name' LIMIT {$limits},{$limite}";
$results = db_query($query, __FILE__, __LINE__);
while ($game = mysql_fetch_array($results))
{
$game['edit_url'] = $scripturl . '?action=arcadeadmin;sa=game_edit;id='. $game['id'];
$game['remove_url'] = $scripturl . '?action=arcadeadmin;sa=game_remove;id='. $game['id'];
$game['highscore_url'] = $scripturl . '?action=arcadeadmin;sa=highscore;id='. $game['id'];
$context['arcade']['admin_games'][] = $game;
}
$query2 = "SELECT count(*) FROM {$db_prefix}games ORDER BY 'name'";
$results2 = db_query($query2, __FILE__, __LINE__);
$num = mysql_fetch_array($results2);
$context['arcade']['pageindex'] = constructPageIndex($scripturl."?action=arcadeadmin;sa=games",$_GET['start'],$num[0],$modSettings['arcade_games_per_page']);
mysql_free_result($results);
}
Function ArcadeAdmin_game_remove()
{
global $boardurl, $txt, $scripturl, $db_prefix;
global $boarddir,$ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings,$sourcedir;
if (isset($_GET['id']))
{
$query = "DELETE FROM {$db_prefix}games WHERE id={$_GET['id']} LIMIT 1";
db_query($query,__FILE__,__LINE__);
redirectexit($scripturl.'?action=arcadeadmin;sa=games');
}
}
Function ArcadeAdmin_game_edit()
{
global $boardurl, $txt, $scripturl, $db_prefix;
global $boarddir,$ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings,$sourcedir;
$context['sub_template'] = "ArcadeAdmin_install_edit";
load_category();
if (isset($_GET['id']))
{
$query = "SELECT * FROM {$db_prefix}games WHERE id={$_GET['id']} LIMIT 0,1";
$results = db_query($query, __FILE__, __LINE__);
$context['arcade']['game'] = mysql_fetch_array($results); // We need only one not reason to loop :)
$context['arcade']['game']['submit_url'] = $scripturl.'?action=arcadeadmin;sa=game_edit2';
}
else
{
fatal_error("No ID");
}
}
Function ArcadeAdmin_game_edit2()
{
global $boardurl, $txt, $scripturl, $db_prefix;
global $boarddir,$ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings,$sourcedir;
$to_check = array('game','bgcolor','name','highscore','category','width','height','type','file');
$context['sub_template'] = "ArcadeAdmin_install_edit";
load_category();
$errors = false;
$err[] = array();
$context['arcade']['game'] = array();
$context['arcade']['game']['submit_url'] = $scripturl.'?action=arcadeadmin;sa=game_edit2';
foreach($to_check as $tmp)
{
if(!isset($_POST[$tmp]) || $_POST[$tmp] == '')
{
$errors = true;
$err[] = $txt['arcade_248'].$txt['arcade_247_'.$tmp];
}
else
{
$context['arcade']['game'][$tmp] = $_POST[$tmp];
}
}
$to_copy = array('help','desc');
foreach($to_copy as $tmp)
{
if(!isset($_POST[$tmp]) || $_POST[$tmp] == '')
{
// $errors = true;
// $err[] = $txt['arcade_248'].$txt['arcade_247_'.$tmp];
}
else
{
$context['arcade']['game'][$tmp] = $_POST[$tmp];
}
}
if($errors)
{
$context['arcade']['game']['errors'] = $err;
}
else
{
$sql = "UPDATE {$db_prefix}games SET game='{$_POST['game']}', bgcolor='{$_POST['bgcolor']}', name='{$_POST['name']}', help='{$_POST['help']}', dsc='{$_POST['desc']}', highscore='{$_POST['highscore']}', category='{$_POST['category']}', width='{$_POST['width']}', height='{$_POST['height']}', type='{$_POST['type']}', file='{$_POST['file']}' WHERE id={$_POST['id']}";
$results2 = db_query($sql, __FILE__, __LINE__);
redirectexit($scripturl.'?action=arcadeadmin;sa=games');
}
}
Function ArcadeAdmin_install_game()
{
global $boardurl, $txt, $scripturl, $db_prefix;
global $boarddir,$ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings,$sourcedir;
$context['sub_template'] = "ArcadeAdmin_install_edit";
$query = "SELECT * FROM {$db_prefix}games_category";
$result = db_query($query, __FILE__, __LINE__);
//$context['arcade']['category'][0] = $txt['arcade_67']; // First (0) is reversed for 'No category'
/* while ($cat = mysql_fetch_array($result))
{
// Loop thought all caterogies in database
$context['arcade']['category'][$cat['id']] = $cat['name'];
}*/
load_category();
$context['arcade']['install_notice'] = "";
if(isset($_GET['multi']))
{
$multi = true;
$_GET['file'] = $_SESSION['arcade']['admin']['install'][ $_SESSION['arcade']['admin']['current'] ];
$context['arcade']['install_notice'] = sprintf($txt['arcade_installg'],$_SESSION['arcade']['admin']['current']+1,$_SESSION['arcade']['admin']['total']);
}
else
{
$multi = false;
}
mysql_free_result($result); // Free memory :)
if(!isset($_GET['save']))
{
if (isset($_GET['file']))
{
// Make sure that file is set
$context['arcade']['game']['file'] = $_GET['file'];
$file = $_GET['file'];
require_once($boarddir.'/getid3/getid3.php');
$type = substr($file, -3, 4);
$context['arcade']['game']['submit_url'] = $scripturl.'?action=arcadeadmin;sa=install_game;save=true';
$context['arcade']['game']['submit_url'] .= ($multi==true) ? ';multi=true' : '';
if($type == "swf")
{
$swf = new getID3;
$swf->analyze($modSettings['arcade_games_dir']."/" . $_GET['file']);
$context['arcade']['game']['game'] = str_replace(".swf", "", $_GET['file']); // Take out that .swf
if(isset($swf->info['video']['resolution_x']))
{
$context['arcade']['game']['width'] = $swf->info['video']['resolution_x'];
}
if(isset($swf->info['video']['resolution_y']))
{
$context['arcade']['game']['height'] = $swf->info['video']['resolution_y'];
}
if(isset($swf->info['swf']['bgcolor']))
{
$context['arcade']['game']['bgcolor'] = "#".$swf->info['swf']['bgcolor'];
}
if(isset($swf->info['error']))
{
$context['arcade']['game']['errors'] = "Auto detect failed: ".$swf->info['error'];
}
$context['arcade']['game']['type'] = 0;
}
elseif($type == "php")
{
$context['arcade']['game']['game'] = str_replace(".php", "", $_GET['file']); // Take out that .php
$context['arcade']['game']['width'] = 0;
$context['arcade']['game']['height'] = 0;
$context['arcade']['game']['type'] = 1;
$context['arcade']['game']['bgcolor'] = "#000000";
}
}
else
{
fatal_error('No File');
}
}
else
{
$to_check = array('game','bgcolor','name','highscore','category','width','height','type','file');
$context['arcade']['game'] = array();
$context['arcade']['game']['submit_url'] = $scripturl.'?action=arcadeadmin;sa=install_game;save=true;';
$context['arcade']['game']['submit_url'] .= ($multi==true) ? ';multi=true' : '';
foreach($to_check as $tmp)
{
if(!isset($_POST[$tmp]) || $_POST[$tmp] == "")
{
$errors = true;
$err[] = $txt['arcade_248'].$txt['arcade_247_'.$tmp];
}
else
{
$context['arcade']['game'][$tmp] = $_POST[$tmp];
}
}
$to_copy = array('help','desc');
foreach($to_copy as $tmp)
{
if(!isset($_POST[$tmp]) || $_POST[$tmp] == "")
{
// $errors = true;
// $err[] = $txt['arcade_248'].$txt['arcade_247_'.$tmp];
}
else
{
$context['arcade']['game'][$tmp] = $_POST[$tmp];
}
}
if($errors)
{
$context['arcade']['game']['errors'] = $err;
}
else
{
if($_POST['type'] == 1)
{
include $modSettings['arcade_games_dir']."/".$_POST['file'];
$class = $_POST['game'];
$gam = new $class($scripturl);
$gam->install;
}
$sql = "INSERT INTO {$db_prefix}games SET game='{$_POST['game']}',bgcolor='{$_POST['bgcolor']}', name='{$_POST['name']}', help='{$_POST['help']}', `dsc`='{$_POST['desc']}', highscore={$_POST['highscore']}, category={$_POST['category']}, width={$_POST['width']}, height={$_POST['height']}, type={$_POST['type']}, file='{$_POST['file']}'";
db_query($sql,__FILE__,__LINE__);
if(!isset($_GET['multi']))
{
redirectexit($scripturl.'?action=arcadeadmin;sa=install');
}
else
{
$_SESSION['arcade']['admin']['current'] += 1;
if($_SESSION['arcade']['admin']['current'] >= $_SESSION['arcade']['admin']['total'])
{
redirectexit($scripturl.'?action=arcadeadmin;sa=install');
}
else
{
redirectexit($scripturl."?action=arcadeadmin;sa=install_game;multi=true");
}
}
}
}
}
Function ArcadeAdmin_gameinfo()
{
global $boardurl, $txt, $scripturl, $db_prefix;
global $boarddir,$ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings,$sourcedir;
if(isset($_GET['update']))
{
ArcadePopup("Game info update",print_r(UpdateGameInfo(),true));
}
}
Function ArcadeAdmin_maintance()
{
global $boardurl, $txt, $scripturl, $db_prefix;
global $boarddir,$ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings,$sourcedir;
if(isset($_GET['champions']))
{
update_champ();
ArcadePopup("Champions update","Done");
}
}
Function ArcadeAdmin_install()
{
// Updated to 1.2.4
global $boardurl, $txt, $scripturl, $db_prefix;
global $boarddir,$ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings,$sourcedir;
$context['arcade_admin']['action'] = "games2";
$query = "SELECT * FROM {$db_prefix}games ORDER BY 'name'";
$results = db_query($query, __FILE__, __LINE__);
if(is_dir($modSettings['arcade_games_dir']))
{
// Check that Games Directory is corrent
if ($games = opendir($modSettings['arcade_games_dir']."/"))
{
// Open it
while (($file = readdir($games)) !== false)
{
// Read every file
$type = (substr($file, -3, 4)); // last 3 characters
if ($type == "swf" || $type == "php")
{
// php and swf to be shown
// Make data array
$context['arcade']['admin_games'][$file]['installed'] = false;
$context['arcade']['admin_games'][$file]['filename'] = $file;
$context['arcade']['admin_games'][$file]['file_satus'] = true;
$context['arcade']['admin_games'][$file]['install_url'] = $scripturl."?action=arcadeadmin;sa=install_game;file=".$file;
$context['arcade']['admin_games'][$file]['install_multi_url'] = $scripturl."?action=arcadeadmin;sa=install_multi;file=".$file;
$context['arcade']['admin_games'][$file]['delete_url'] = $scripturl."?action=arcadeadmin;sa=delete;file=".$file;
$context['arcade']['admin_games'][$file]['ch'] = is_writable($modSettings['arcade_games_dir']."/".$file);
}
}
}
}
else
{
fatal_error($txt['arcade_games_dir_invalid']);
}
// Check for insalled games
while ($game = mysql_fetch_array($results))
{
unset($context['arcade']['admin_games'][$game['file']]);
}
$context['arcade']['valikko'] = '<a href="#" onclick="document.frmins.submit();">'.$txt['arcade_installselected'].'</a>';
// $num = count($context['arcade']['admin_games']);
// $context['arcade']['pageindex'] = constructPageIndex($scripturl."?action=arcadeadmin;sa=install",$_GET['start'],$num,$modSettings['arcade_games_per_page']);
mysql_free_result($results);
}
Function ArcadeAdmin_install_multi()
{
global $boardurl, $txt, $scripturl, $db_prefix, $boarddir,$ID_MEMBER, $context, $user_info, $db_prefix, $modSettings,$sourcedir;
$context['template_layers'] = array();
if(!isset($_POST['files']) || count($_POST['files']) == 0)
{
redirectexit($scripturl.'?action=arcadeadmin;sa=install');
}
else
{
$_SESSION['arcade']['admin']['multi'] = true;
$_SESSION['arcade']['admin']['current'] = 0;
$_SESSION['arcade']['admin']['total'] = count($_POST['files']);
$_SESSION['arcade']['admin']['install'] = $_POST['files'];
redirectexit($scripturl.'?action=arcadeadmin;sa=install_game;multi=true');
}
}
Function ArcadeAdmin_delete()
{
global $boardurl, $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings;
if(isset($_GET['file']))
{
unlink($modSettings['arcade_games_dir']."/".$_GET['file']);
redirectexit($scripturl.'?action=arcadeadmin;sa=install');
}
}
Function ArcadeAdmin_settings()
{
global $boardurl, $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings;
$context['arcade_admin']['action'] = "settings";
if(!isset($_GET['sub']))
{
// Not saving
$context['arcade']['submit_url'] = $scripturl.'?action=arcadeadmin;sa=settings;sub=save';
$context['arcade']['valid_game'] = is_dir($modSettings['arcade_games_dir']);
}
elseif($_GET['sub'] == "save")
{
// Saving
$settings = array(
'arcade_games_per_page' => $_POST['arcade_games_per_page'],
'arcade_challenge_per_page' => $_POST['arcade_challenge_per_page'],
'arcade_results_per_page' => $_POST['arcade_results_per_page'],
'arcade_highscores_per_page' => $_POST['arcade_highscores_per_page'],
'arcade_games_dir' => $_POST['arcade_games_dir'],
'arcade_games_url' => $_POST['arcade_games_url'],
'arcade_enabled' => $_POST['arcade_enable'],
'arcade_months_in_champ' => $_POST['arcade_months_in_champ'],
'arcade_message' => $_POST['arcade_message'],
);
foreach ($settings as $var => $value)
{
$sql = "SELECT * FROM {$db_prefix}settings WHERE variable='{$var}'";
$res = db_query($sql,__FILE__,__LINE__);
if(db_affected_rows() > 0)
{
$query = "UPDATE {$db_prefix}settings SET value='{$value}' WHERE variable='{$var}'";
}
else
{
$query = 'INSERT INTO '.$db_prefix."settings SET value='".$value."', variable='".$var."'";
}
$res = db_query($query,__FILE__,__LINE__);
}
header('location: '.$scripturl.'?action=arcadeadmin;sa=settings');
die();
}
}
Function ArcadeAdmin_highscore()
{
global $boardurl, $txt, $scripturl, $db_prefix;
global $ID_MEMBER;
global $context, $user_info, $db_prefix, $modSettings;
if(!isset($_GET['sub']))
{
$context['arcade']['sub_action'] = "highscore";
if(isset($_GET['id']))
{
$query = 'SELECT * FROM '.$db_prefix.'games WHERE id=\''.$_GET['id'].'\'';
$res = db_query($query,__FILE__,__LINE__);
$game = mysql_fetch_array($res);
if($game['highscore'] == 0)
{
$query = "SELECT high.score,member.realName,member.ID_MEMBER FROM {$db_prefix}games_high As high,{$db_prefix}members As member WHERE high.game='{$game['game']}' AND high.member=member.ID_MEMBER ORDER BY high.score DESC";
}
elseif($game['highscore'] == 1)
{
$query = "SELECT high.score,member.realName,member.ID_MEMBER FROM {$db_prefix}games_high As high,{$db_prefix}members As member WHERE high.game='{$game['game']}' AND high.member=member.ID_MEMBER ORDER BY high.score ASC";
}
else
{
fatal_error("NO SCORING");
}
$res = db_query($query,__FILE__,__LINE__);
$scores = array();
$users = array();
while($score = mysql_fetch_array($res))
{
$scores[] = $score;
$users[] = serialize(array($score['ID_MEMBER'],$score['realName'])); // Serialize because array_unigue hates arrays ^_^
}
$users = array_unique($users);
$context['arcade']['users'] = array();
foreach ($users as $temp)
{
$context['arcade']['users'][] = unserialize($temp); // Now we have to unserialize
}
$context['arcade']['score_c'] = count($scores);
$context['arcade']['score'] = $scores;
$context['arcade']['game'] = $game;
}
else
{
fatal_error($txt['arcade_148']);
}
}
elseif($_GET['sub'] == "submit")
{
$query = "SELECT * FROM {$db_prefix}games WHERE id='{$_GET['id']}'";
$res = db_query($query,__FILE__,__LINE__);
$context['arcade']['sub_action'] = "highscore2";
$game = mysql_fetch_array($res);
$sql = array();
$actions = $_POST['act'];
$values = $_POST['value'];
foreach($_POST['sel'] as $id => $temp)
{
if($actions[$id] == 0)
{
// Do nothing
}
elseif($actions[$id] == 1)
{
// Remove ALL scores from this game
$sql[] = "DELETE FROM {$db_prefix}games_high WHERE game='{$game['game']}' AND member='{$id}'";
}
elseif($actions[$id] == 2)
{
// Remove ALL scores from this game expect best
$best = highscore_user($game['game'],$game['highscore'],$id);
if($game['highscore'] == 0)
{
$sql[] = "DELETE FROM {$db_prefix}games_high WHERE game='{$game['game']}' AND member='{$id}' AND score < {$best[0]['score']}";
}
elseif($game['highscore'] == 1)
{
$sql[] = "DELETE FROM {$db_prefix}games_high WHERE game='{$game['game']}' AND member='{$id}' AND score > {$best[0]['score']}";
}
}
elseif($actions[$id] == 3)
{
// Remove scores lower/higher than
if($values[$id] != "" && is_numeric($values[$id]))
{
if($game['highscore'] == 0)
{
$sql[] = "DELETE FROM {$db_prefix}games_high WHERE game='{$game['game']}' AND member='{$id}' AND score < {$values[$id]}";
}
elseif($game['highscore'] == 1)
{
$sql[] = "DELETE FROM {$db_prefix}games_high WHERE game='{$game['game']}' AND member='{$id}' AND score > {$values[$id]}";
}
}
}
elseif($actions[$id] == 4)
{
// Remove So score count is
}
}
foreach($sql as $temp)
{
db_query($temp,__FILE__,__LINE__);
}
header("Location: ".$scripturl.'?action='.$_GET['action'].';sa='.$_GET['sa'].';id='.$_GET['id']);
}
}
?>

View File

@ -1,489 +0,0 @@
<?php
/*******************************************************************************
* SMF Arcade 2.0.8 (http://www.smfarcade.info) *
* Copyright (C) 2004-2007 Niko Pahajoki (http://www.madjoki.com) *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
********************************************************************************
* ArcadeInstall.php *
********************************************************************************/
if (!defined('SMF'))
die('Hacking attempt...');
/* This file contains functions and data for installer */
$version = '2.0.0';
$database_version = 3;
$ArcadeSettings = array(
'gamesPerPage' => array(25, false),
'scoresPerPage' => array(50, false),
'gamesDirectory' => array(addslashes($boarddir . '/Games'), false),
'gamesUrl' => array($boardurl . '/Games', false),
'arcadeEnabled' => array(true, false),
'arcadeCheckLevel' => array(1, false),
'arcadeDefaultCategory' => array(1, false),
'arcadeGameInformationSide' => array(0, false),
'arcadeMaxScores' => array(0, false),
'arcadePermissionMode' => array(1, false),
'arcadePostPermission' => array(0, false),
'arcadePostsPlay' => array(0, false),
'arcadePostsPlayPerDay' => array(0, false),
// Version
'arcadeVersion' => array($version, true),
'arcadeDatabaseVersion' => array($database_version, true),
);
$Permissions = array(
'arcade_view' => array(-1, 0, 2), // Everyone
'arcade_play' => array(-1, 0, 2), // Everyone
'arcade_favorite' => array(0, 2), // Regular members
'arcade_submit' => array(0, 2), // Regular members
'arcade_admin' => array(), // Only admins will get this
'arcade_comment_own' => array(0, 2), // Regular members
'arcade_comment_any' => array(), // Only admins
'arcade_rate' => array(0, 2), // Regular members
);
// Table data
$Tables = array(
'arcade_games' => array(
'fields' => array(
'ID_GAME' => 'INT unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY',
'internalName' => 'VARCHAR( 255 ) NOT NULL',
'gameName' => 'VARCHAR( 255 ) NOT NULL',
'thumbnail' => 'VARCHAR( 255 ) NOT NULL',
'thumbnailSmall' => 'VARCHAR( 255 ) NOT NULL',
'description' => 'TEXT NOT NULL',
'help' => 'TEXT NOT NULL',
'ID_CAT' => 'INT unsigned NOT NULL',
'gameWidth' => 'INT unsigned NOT NULL',
'gameHeight' => 'INT unsigned NOT NULL',
'enabled' => 'INT NOT NULL DEFAULT 0',
'gameFile' => 'VARCHAR( 255 ) NOT NULL',
'gameDirectory' => 'TINYTEXT NOT NULL',
'gameType' => 'TINYINT NOT NULL',
'scoreType' => 'TINYINT NOT NULL',
'memberGroups' => 'VARCHAR( 255 ) NOT NULL',
'gameBackgroundColor' => 'VARCHAR( 6 ) NOT NULL',
'gameRating' => 'TINYINT NOT NULL default 0',
'ID_MEMBER_CHAMPION' => 'INT unsigned NOT NULL default 0',
'ID_CHAMPION_SCORE' => 'INT unsigned NOT NULL default 0',
'gameExtraData' => 'TEXT NOT NULL',
'numPlays' => 'INT unsigned NOT NULL default 0',
'numRates' => 'INT unsigned NOT NULL default 0',
'maxScores' => 'INT NOT NULL default 0',
),
'index' => array(
'ID_GAME' => 'PRIMARY',
'internalName' => 'unique',
'gameFile' => 'unique',
),
),
'arcade_personalbest' => array(
'fields' => array(
'ID_PB' => 'INT unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY',
'ID_GAME' => 'INT unsigned NOT NULL',
'ID_MEMBER' => 'INT unsigned NOT NULL',
'score' => 'FLOAT NOT NULL',
),
'index' => array(
'ID_GAME' => 'index',
'ID_MEMBER' => 'index',
),
),
'arcade_gameofday' => array(
'fields' => array(
'ID_DAY' => 'INT unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY',
'ID_GAME' => 'INT unsigned NOT NULL',
'day' => 'INT unsigned NOT NULL',
),
'index' => array(
),
),
'arcade_scores' => array(
'fields' => array(
'ID_SCORE' => 'INT unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY',
'ID_GAME' => 'INT unsigned NOT NULL',
'ID_MEMBER' => 'INT unsigned NOT NULL',
'score' => 'FLOAT NOT NULL',
'startTime' => 'INT unsigned NOT NULL',
'endTime' => 'INT unsigned NOT NULL',
'championFrom' => 'INT unsigned NOT NULL',
'championTo' => 'INT unsigned NOT NULL',
'position' => 'INT unsigned NOT NULL',
'gameDuration' => 'INT unsigned NOT NULL',
'memberIp' => 'VARCHAR( 15 ) NOT NULL',
'comment' => 'VARCHAR( 255 ) NOT NULL',
'scoreStatus' => 'TINYINT unsigned NOT NULL',
),
'index' => array(
'ID_GAME' => 'index',
'ID_MEMBER' => 'index',
),
),
'arcade_categories' => array(
'fields' => array(
'ID_CAT' => 'INT unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY',
'catName' => 'VARCHAR( 20 ) NOT NULL',
'numGames' => 'INT unsigned NOT NULL default 0',
'numPlays' => 'INT unsigned NOT NULL default 0',
'numRates' => 'INT unsigned NOT NULL default 0',
'gameRate' => 'INT unsigned NOT NULL default 0',
'catOrder' => 'INT unsigned NOT NULL default 0',
'special' => 'INT unsigned NOT NULL default 0',
'memberGroups' => 'VARCHAR( 255 ) NOT NULL',
),
'index' => array(
),
),
'arcade_favorite' => array(
'fields' => array(
'ID_FAVORITE' => 'INT unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY',
'ID_MEMBER' => 'INT unsigned NOT NULL',
'ID_GAME' => 'INT unsigned NOT NULL',
),
'index' => array(
),
),
'arcade_rates' => array(
'fields' => array(
'ID_RATE' => 'INT unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY',
'ID_MEMBER' => 'INT unsigned NOT NULL',
'ID_GAME' => 'INT unsigned NOT NULL',
'rating' => 'TINYINT unsigned NOT NULL',
'rateTime' => 'INT unsigned NOT NULL',
),
'index' => array(
),
),
/*'arcade_settings' => array(
'fields' => array(
'ID_MEMBER' => 'INT unsigned NOT NULL PRIMARY KEY',
'variable' => 'VARCHAR( 20 )',
'value' => 'TEXT NOT NULL',
),
'index' => array(
),
),*/
);
function CreateTables($tables)
{
//global $db_prefix;
$errors = array();
foreach ($tables as $name => $data)
if (!mysql_query(CreateTable($name, $data)))
$errors[] = mysql_error();
return $errors;
}
function CreateTable($name, $data)
{
global $db_prefix;
$fields = array();
foreach ($data['fields'] as $field => $type)
$fields[] = "`$field` $type";
foreach ($data['index'] as $key => $type)
{
if ($type == 'unique')
$fields[] = "UNIQUE $key ($key)";
if ($type == 'index')
$fields[] = "KEY $key ($key)";
}
return "CREATE TABLE {$db_prefix}{$name}(" . implode(',', $fields) . ");";
}
function PopulateTables()
{
global $db_prefix;
$errors = array();
$sql[] = "INSERT INTO {$db_prefix}arcade_categories SET catName = 'Default', special = 1, memberGroups = '-1,0,2';";
foreach ($sql as $query)
if (!mysql_query($query))
$errors[] = mysql_error();
return $errors;
}
function CheckTables($tables)
{
global $db_prefix;
$res = mysql_query('SHOW TABLES');
$tables2 = array();
while($row = mysql_fetch_array($res))
foreach($tables as $name)
{
if(substr($row[0], -strlen($name)) == $name)
$tables2[] = $name;
}
$ctab = 0;
foreach($tables2 as $name)
$ctab++;
return $ctab;
}
function UpdateTables(&$tables, $full = false)
{
global $db_prefix;
$errors = array();
foreach ($tables as $name => $data)
{
$res = mysql_query("DESCRIBE {$db_prefix}{$name}");
if (!$res)
{
$errors[] = mysql_error();
$sql = CreateTable($name, $data);
if (!mysql_query($sql))
$errors[] = mysql_error() . 'Query: <tt>' . $sql . '</tt>';
}
else
{
while ($field = mysql_fetch_assoc($res))
{
if ($full)
{
if (isset($data['fields'][ $field['Field'] ]))
{
$fname = $field['Field'];
$type = $data['fields'][ $field['Field'] ];
$sql = "ALTER TABLE {$db_prefix}{$name} CHANGE $fname $fname $type";
if (!mysql_query($sql))
$errors[] = mysql_error() . 'Query: <tt>' . $sql . '</tt>';
}
else
{
$fname = $field['Field'];
//$type = $data['fields'][ $field['Field'] ];
$sql = "ALTER TABLE {$db_prefix}{$name} DROP $fname";
if (!mysql_query($sql))
$errors[] = mysql_error() . 'Query: <tt>' . $sql . '</tt>';
}
}
unset($data['fields'][ $field['Field'] ]);
}
foreach ($data['fields'] as $field => $type)
{
if (!mysql_query("ALTER TABLE {$db_prefix}{$name} ADD $field $type"))
$errors[] = mysql_error();
}
// Now lets check indexes
if ($full)
{
$indexes = mysql_query("SHOW INDEX FROM {$db_prefix}{$name}");
while ($index = mysql_fetch_assoc($indexes))
{
if (!isset($data['index'][$index['Key_name']]))
{
if (!mysql_query("ALTER TABLE {$db_prefix}{$name} DROP INDEX $index[Key_name]"))
$errors[] = mysql_error();
}
else
{
if ($index['Non_unique'] == 1 && $data['index'][$index['Key_name']] == 'unique')
if (!mysql_query("ALTER TABLE {$db_prefix}{$name} DROP INDEX $index[Key_name]"))
$errors[] = mysql_error();
elseif ($index['Non_unique'] == 0 && $data['index'][$index['Key_name']] != 'unique')
if (!mysql_query("ALTER TABLE {$db_prefix}{$name} DROP INDEX $index[Key_name]"))
$errors[] = mysql_error();
else
unset($data['index'][$index['Key_name']]);
}
}
foreach ($data['index'] as $name => $type)
{
if ($type == 'index')
{
if (!mysql_query("ALTER TABLE {$db_prefix}{$name} ADD INDEX ($name)"))
$errors[] = mysql_error();
}
elseif ($type == 'unique')
{
if (!mysql_query("ALTER TABLE {$db_prefix}{$name} ADD UNUQUE $name"))
$errors[] = mysql_error();
}
}
}
}
}
return $errors;
}
function ResetPermissions(&$permissions)
{
global $db_prefix;
$errors = array();
foreach ($permissions as $permission => $groups)
{
if (!mysql_query("DELETE FROM {$db_prefix}permissions WHERE permission = '$permission'"))
$errors[] = mysql_error();
foreach ($groups as $ID_GROUP)
{
if (!mysql_query("INSERT INTO {$db_prefix}permissions SET ID_GROUP = $ID_GROUP, permission = '$permission'"))
$errors[] = mysql_error();
}
}
return $errors;
}
function ResetSettings(&$settings, $update = false)
{
global $db_prefix;
$errors = array();
foreach ($settings as $var => $temp)
{
if (!$update || $temp[1] == true)
{
if (!mysql_query("REPLACE INTO {$db_prefix}settings SET variable='{$var}', value='{$temp[0]}'"))
$errors[] = mysql_error();
}
else
{
$res = mysql_query("SELECT variable FROM {$db_prefix}settings WHERE variable='{$var}'");
if (!$res)
$errors[] = mysql_error();
if (mysql_num_rows($res) == 0)
{
if (!mysql_query("INSERT INTO {$db_prefix}settings SET variable='{$var}', value='{$temp[0]}'"))
$errors[] = mysql_error();
}
}
}
return $errors;
}
function ImportGames()
{
global $db_prefix;
set_time_limit(0);
$res = mysql_query("SELECT * FROM {$db_prefix}games") or die(mysql_error());
$games = array();
while ($game = mysql_fetch_assoc($res))
{
$set = array(
'internalName' => mysql_real_escape_string($game['game']),
'gameName' => mysql_real_escape_string($game['name']),
'description' => mysql_real_escape_string($game['dsc']),
'help' => mysql_real_escape_string($game['help']),
'ID_CAT' => 1,
'gameWidth' => $game['width'],
'gameFile' => $game['file'],
'gameHeight' => $game['height'],
'memberGroups' => '-1,0,2',
'enabled' => 1,
'gameBackgroundColor' => substr($game['bgcolor'], 1),
);
$fields = array();
foreach($set as $x => $y)
$fields[] = "$x = '$y'";
if (!mysql_query("INSERT INTO {$db_prefix}arcade_games SET " . implode(',', $fields)))
$errors[] = mysql_error();
$games[$game['game']] = mysql_insert_id();
}
mysql_free_result($res);
$res = mysql_query("SELECT * FROM {$db_prefix}games_high") or die(mysql_error());
while ($score = mysql_fetch_assoc($res))
if (!isset($games[$score['game']]))
echo 'Game not installed: ', $score['game'], ' -> socre not imported<br />';
else
{
$set = array(
'ID_GAME' => $games[$score['game']],
'ID_MEMBER' => $score['member'],
'endTime' => $score['stime'],
'score' => $score['score'],
'memberIp' => '0.0.0.0',
'comment' => mysql_real_escape_string($score['comment']),
'scoreStatus' => $score['warning'],
'gameDuration' => $score['duration'],
);
$fields = array();
foreach($set as $x => $y)
$fields[] = "$x = '$y'";
if (!mysql_query("INSERT INTO {$db_prefix}arcade_scores SET " . implode(',', $fields)))
$errors[] = mysql_error();
}
mysql_free_result($res);
return $errors;
}
?>

View File

@ -1,349 +0,0 @@
<?php
/*******************************************************************************
* SMF Arcade 2.0.10 (http://www.smfarcade.info) *
* Copyright (C) 2004-2007 Niko Pahajoki (http://www.madjoki.com) *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
********************************************************************************
* ArcadeList.php *
********************************************************************************/
if (!defined('SMF'))
die('Hacking attempt...');
/* This file handles Arcade and loads required files.
void ArcadeList()
- ???
void ArcadeRate()
- ???
void ArcadeFavorite()
- ???
void ArcadeSearch()
- ???
void ArcadeSearchXML()
- ???
*/
function ArcadeList()
{
global $scripturl, $txt, $db_prefix, $modSettings, $context, $user_info, $ID_MEMBER;
// How many games per page?
$gamesPerPage = isset($modSettings['gamesPerPage']) ? $modSettings['gamesPerPage'] : 25;
$_REQUEST['start'] = (int) $_REQUEST['start'];
$where = "enabled = 1 AND $user_info[query_see_game]";
$search = false;
if (isset($_REQUEST['category']))
{
$search = true;
$category = (int) $_REQUEST['category'];
$where .= " AND game.ID_CAT= $category";
}
if (isset($_REQUEST['name']))
{
$search = true;
$name = $_REQUEST['name'];
$where .= " AND game.gameName LIKE '%$name%'";
}
if (isset($_REQUEST['favorites']))
{
$search = true;
$favorite = true;
$favorite_join = "INNER JOIN";
}
else
$favorite_join = "LEFT JOIN";
// How many games there are
if (isset($favorite) && $favorite)
$result_count = db_query("
SELECT count(*) AS gc
FROM ({$db_prefix}arcade_games AS game, {$db_prefix}arcade_favorite AS favorite)
LEFT JOIN {$db_prefix}arcade_categories AS category ON (category.ID_CAT = game.ID_CAT)
WHERE favorite.ID_GAME = game.ID_GAME
AND favorite.ID_MEMBER = $ID_MEMBER
AND $where", __FILE__, __LINE__);
else
$result_count = db_query("
SELECT count(*) AS gc
FROM {$db_prefix}arcade_games AS game
LEFT JOIN {$db_prefix}arcade_categories AS category ON (category.ID_CAT = game.ID_CAT)
WHERE $where", __FILE__, __LINE__);
$gameCount = mysql_fetch_assoc($result_count);
mysql_free_result($result_count);
$parts = array(
$scripturl . '?action=arcade'
);
// Sorting methods
$sort_methods = array(
'name' => 'game.gameName',
'plays' => 'game.numPlays',
'champion' => 'IFNULL(mem.realName, mem.memberName)',
'myscore' => 'IFNULL(pb.score, 0)',
'category' => 'category.catName',
'favorite' => 'IF(favorite.ID_FAVORITE = null, 0, 1)'
);
if (isset($_REQUEST['sort']) && isset($sort_methods[$_REQUEST['sort']]))
$parts[] = 'sort=' . $_REQUEST['sort'];
if (isset($_REQUEST['desc']))
$parts[] = 'desc';
if ($search)
{
if (isset($category))
$parts[] = 'category=' . $category;
if (isset($name))
$parts[] = 'name=' . urlencode($name);
if (isset($favorite))
$parts[] = 'favorites';
}
$context['arcade']['pageIndex'] = constructPageIndex(implode(';', $parts) , $_REQUEST['start'], $gameCount['gc'] , $gamesPerPage, false );
// How user wants to sort games?
if (!isset($_REQUEST['sort']) || !isset($sort_methods[$_REQUEST['sort']]))
{
$context['sort_by'] = 'name';
$_REQUEST['sort'] = 'game.gameName';
}
else
{
$context['sort_by'] = $_REQUEST['sort'];
$_REQUEST['sort'] = $sort_methods[$_REQUEST['sort']];
}
$ascending = !isset($_REQUEST['desc']);
$context['sort_direction'] = $ascending ? 'up' : 'down';
$result_games = db_query("
SELECT
game.ID_GAME, game.gameName, game.description, game.gameRating, game.numPlays, game.gameFile,
game.gameDirectory, game.gameType, game.internalName, game.gameWidth, game.gameHeight,
game.gameBackgroundColor AS bgcolor, game.scoreType, game.maxScores,game.thumbnail,
game.thumbnailSmall, game.help, IFNULL(score.ID_SCORE,0) AS ID_SCORE, IFNULL(score.score,0) AS champScore,
IFNULL(score.endTime, 0) AS champTime, IFNULL(mem.ID_MEMBER, 0) AS ID_MEMBER, IFNULL(mem.realName, '') AS realName,
IFNULL(score.endTime, 0) AS championTime, IFNULL(favorite.ID_FAVORITE, 0) AS isFavorite, IFNULL(category.ID_CAT, 0) AS ID_CAT,
IFNULL(category.catName, '') As catName, IFNULL(pb.ID_PB, 0) AS ID_PB, IFNULL(pb.score, 0) AS personalBest
FROM {$db_prefix}arcade_games as game
$favorite_join {$db_prefix}arcade_favorite AS favorite ON (favorite.ID_GAME = game.ID_GAME AND favorite.ID_MEMBER = $ID_MEMBER)
LEFT JOIN {$db_prefix}arcade_scores AS score ON (score.ID_SCORE = game.ID_CHAMPION_SCORE)
LEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = game.ID_MEMBER_CHAMPION)
LEFT JOIN {$db_prefix}arcade_personalbest AS pb ON (pb.ID_GAME = game.ID_GAME AND pb.ID_MEMBER = $ID_MEMBER)
LEFT JOIN {$db_prefix}arcade_categories AS category ON (category.ID_CAT = game.ID_CAT)
WHERE $where
ORDER BY $_REQUEST[sort]" . ($ascending ? '' : ' DESC') . "
LIMIT $_REQUEST[start], $gamesPerPage", __FILE__, __LINE__);
$context['arcade']['games'] = array();
$context['arcade']['search'] = $search;
while ($game = mysql_fetch_assoc($result_games))
{
if ($gameCount['gc'] == 1 && $search && !$favorite) // Redirect to game if only one result in search and not favorites search
redirectexit('action=arcade;sa=play;game=' . $game['ID_GAME']);
$context['arcade']['games'][] = BuildGameArray($game);
}
// Free results since we don't want to use too much memory
mysql_free_result($result_games);
$context['sub_template'] = 'arcade_list';
$context['page_title'] = $txt['arcade_game_list'];
}
function ArcadeRate()
{
global $txt, $db_prefix, $modSettings, $context, $user_info, $ID_MEMBER;
$xml = isset($_REQUEST['xml']);
$game = ArcadeGameInfo((int) $_REQUEST['game']); // Get game info
if ($game === false)
fatal_lang_error('arcade_game_not_found'); // Game was not found
$rate = (int) $_REQUEST['rate'];
if ($rate < 0 || $rate > 5)
fatal_lang_error('arcade_rate_error'); // Don't allow invalid rates
// We may need time ;)
$time = time();
// To ensure there will be no doubles
db_query("
DELETE FROM {$db_prefix}arcade_rates
WHERE ID_MEMBER = $ID_MEMBER AND ID_GAME = $game[id]", __FILE__ ,__LINE__);
// Insert rating
if ($rate > 0)
{
db_query("
INSERT INTO {$db_prefix}arcade_rates
SET ID_MEMBER = $ID_MEMBER, ID_GAME = $game[id], rating = $rate, rateTime = $time", __FILE__ ,__LINE__);
}
// Update rating
$res = db_query("
SELECT SUM(rating) AS rating, COUNT(rating) AS rates
FROM {$db_prefix}arcade_rates
WHERE ID_GAME = $game[id]
GROUP BY ID_GAME", __FILE__ ,__LINE__);
$new_rating = mysql_fetch_assoc($res);
$rate2 = $new_rating['rating'] / $new_rating['rates'];
UpdateGame($game['id'], array('gameRating' => $rate2));
if (!$xml)
{
// Go to reffering page (or highscore page)
if (!isset($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] == '')
redirectexit('action=arcade;sa=highscore;game=' . $game['id']);
else
redirectexit($_SERVER['HTTP_REFERER']);
}
else
{
$context['sub_template'] = 'xml';
$context['arcade']['message'] = 'arcade_rating_saved';
$context['arcade']['extra'] = '<rating>' . floor($rate2) . '</rating>';
}
}
function ArcadeFavorite()
{
global $txt, $db_prefix, $modSettings, $context, $user_info, $ID_MEMBER;
$xml = isset($_REQUEST['xml']) ? true : false;
if ($user_info['is_guest'])
fatal_lang_error('arcade_not_for_guest');
$game = ArcadeGameInfo((int) $_REQUEST['game']);
if ($game === false)
fatal_lang_error('arcade_game_not_found'); // Game was not found
// It's favorite so we can remove it
if ($game['isFavorite'])
{
$remove = true;
db_query("
DELETE FROM {$db_prefix}arcade_favorite
WHERE ID_MEMBER = $ID_MEMBER AND ID_GAME = $game[id]",__FILE__,__LINE__);
}
// It's not favorite, let's add it
else
{
$remove = false;
db_query("
INSERT INTO {$db_prefix}arcade_favorite
SET ID_MEMBER = $ID_MEMBER, ID_GAME = $game[id]",__FILE__,__LINE__);
}
if (!$xml)
{
if (!isset($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] == '')
redirectexit('?action=arcade');
else
redirectexit($_SERVER['HTTP_REFERER']);
}
else
{
$state = $remove ? 0 : 1;
$context['sub_template'] = 'xml';
$context['arcade']['message'] = $remove ? 'aracde_favorite_removed' : 'aracde_favorite_added';
$context['arcade']['extra'] = '<state>' . $state . '</state>';
}
}
function ArcadeSearch()
{
// global $scripturl, $txt, $db_prefix, $modSettings, $context, $settings, $options, $sourcedir, $user_info, $ID_MEMBER;
if (isset($_REQUEST['xml']))
ArcadeSearchXML();
}
function ArcadeSearchXML()
{
global $scripturl, $txt, $db_prefix, $modSettings, $context, $user_info, $ID_MEMBER;
$limit = 5;
$search = mysql_real_escape_string($_REQUEST['name']);
$result_count = db_query("
SELECT count(*) AS games
FROM {$db_prefix}arcade_games as game
LEFT JOIN {$db_prefix}arcade_categories AS category ON (category.ID_CAT = game.ID_CAT)
WHERE game.gameName LIKE '%$search%' AND $user_info[query_see_game]
ORDER BY gameName", __FILE__, __LINE__);
$how_many = mysql_fetch_assoc($result_count);
mysql_free_result($result_count);
$result_games = db_query("
SELECT
game.ID_GAME, game.gameName
FROM {$db_prefix}arcade_games AS game
LEFT JOIN {$db_prefix}arcade_categories AS category ON (category.ID_CAT = game.ID_CAT)
WHERE game.gameName LIKE '%$search%' AND $user_info[query_see_game]
ORDER BY gameName
LIMIT 0, $limit", __FILE__, __LINE__);
$context['arcade']['search'] = array();
$context['arcade']['search']['games'] = array();
$context['arcade']['search']['more'] = $how_many['games'] > $limit ? 1 : 0;
$context['arcade']['search']['more_url'] = $scripturl . '?action=arcade;name=' . urlencode($_REQUEST['name']);
while ($game = mysql_fetch_assoc($result_games))
$context['arcade']['search']['games'][] = array(
'name' => $game['gameName'],
'id' => $game['ID_GAME'],
'url' => $scripturl . '?action=arcade;game=' . $game['ID_GAME']
);
mysql_free_result($result_games);
$context['sub_template'] = 'xml_list';
}
?>

View File

@ -1,689 +0,0 @@
<?php
/*******************************************************************************
* SMF Arcade 2.0.10 (http://www.smfarcade.info) *
* Copyright (C) 2004-2007 Niko Pahajoki (http://www.madjoki.com) *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
********************************************************************************
* ArcadePlay.php *
********************************************************************************/
if (!defined('SMF'))
die('Hacking attempt...');
/*
void ArcadePlay()
- ...
void ArcadeComment()
- ...
void ArcadeHighscore()
- ...
void ArcadeSubmit()
- Handles score submits
void ArcadeSubmitIBP()
- ...
void ArcadeVerifyIBP()
- ...
boolean CheatingCheck(&allowFail, &checkPassed)
- Does basic cheating check
void ClearSession(&game)
- ...
*/
function ArcadePlay()
{
global $scripturl, $txt, $db_prefix, $context;
if (!$context['arcade']['can_play'])
fatal_lang_error('cannot_arcade_play');
$xml = isset($_REQUEST['xml']);
if (isset($_REQUEST['random']) && !isset($_REQUEST['game']) && !$xml) // Get random game if it is requested and there isn't game set
$id = 0;
elseif (!empty($_REQUEST['game']))
$id = (int) $_REQUEST['game'];
else
fatal_lang_error('arcade_game_not_found');
$game = ArcadeGameInfo($id); // Fetch gameinfo from database (function defined in Arcademain.php)
// Was game found
if ($game == false)
fatal_lang_error('arcade_game_not_found');
if (isset($_REQUEST['delete']))
{
checkSession('get');
unset($_SESSION['arcade']['play'][$game['internalName']]);
unset($_SESSION['arcade']['ibp']['game']);
}
if ($xml)
{
// XML request
$context['sub_template'] = 'xml';
$context['arcade']['message'] = 'arcade_session_check_ok';
$_SESSION['arcade']['play'][$game['internalName']] = array(
'game' => $game['internalName'],
'id' => $game['id'],
'startTime' => time(),
'done' => false,
'score' => 0,
'endTime' => 0,
);
$_SESSION['arcade']['ibp']['game'] = $game['id'];
// Increase plays by one (this is done here because xml request is sent even on first play so it won't be counted as two plays)
db_query("
UPDATE {$db_prefix}arcade_games
SET numPlays = numPlays + 1
WHERE ID_GAME = $game[id]", __FILE__, __LINE__);
return true;
}
$message = $txt['arcade_no_javascript'];
$context['arcade']['game'] = &$game;
// Generate html-code for game
if ($game['gameType'] == 0)
$context['arcade']['game']['html'] = ArcadeFlashHtml($game, true, $message);
// Layout start
$context['template_layers'][] = 'ArcadeGame';
$context['sub_template'] = 'arcade_game_play';
$context['page_title'] = $txt['arcade_game_play'];
$context['arcade']['play'] = true;
$context['arcade']['menu'][] = array(
'data' => array(),
'template' => 'ArcadeMenu_GameInformation'
);
$context['linktree'][] = array(
'url' => $scripturl . '?action=arcade;sa=play;game=' . $game['id'],
'name' => $game['name'],
);
// We store this session to check cheating later
$_SESSION['arcade']['play'][$game['internalName']] = array(
'game' => $context['arcade']['game']['internalName'],
'id' => $context['arcade']['game']['id'],
'startTime' => time(),
'done' => false,
'score' => 0,
'endTime' => 0,
);
$_SESSION['arcade']['ibp']['game'] = $game['id'];
}
function ArcadeComment()
{
global $scripturl, $txt, $db_prefix, $context, $ID_MEMBER;
global $func;
$xml = isset($_REQUEST['xml']);
if ($context['arcade']['can_comment_any'] || $context['arcade']['can_comment_own'])
$any = $context['arcade']['can_comment_any'];
else
{
// Normal mode
if (!$xml)
fatal_lang_error('cannot_arcade_comment_own');
// Ajax
else
{
$context['sub_template'] = 'xml';
$context['arcade']['message'] = 'cannot_arcade_comment_own';
return false;
}
}
if ($any)
$where = '1';
else
$where = "ID_MEMBER = $ID_MEMBER";
$comment = $func['htmlspecialchars']($_REQUEST['comment'], ENT_QUOTES);
$score = (int) $_REQUEST['score'];
db_query("
UPDATE {$db_prefix}arcade_scores
SET comment = '$comment'
WHERE ID_SCORE = $score AND $where", __FILE__, __LINE__);
$_SESSION['arcade']['highscore']['saved'] = true;
if ($xml)
{
$context['sub_template'] = 'xml';
$context['arcade']['message'] = parse_bbc(stripcslashes($comment));
}
else
redirectexit('action=arcade;sa=highscore;game=' . (int) $_REQUEST['game']);
}
function ArcadeHighscore()
{
global $scripturl, $txt, $db_prefix, $modSettings, $context, $ID_MEMBER;
// Is game set
if (!isset($_REQUEST['game']))
fatal_lang_error('arcade_game_not_found');
// Get game info
$game = ArcadeGameInfo((int) $_REQUEST['game']);
if ($game === false || !$game['highscoreSupport'])
fatal_lang_error('arcade_game_not_found'); // Game was not found
$context['arcade']['menu']['game_information'] = array(
'data' => array(),
'template' => 'ArcadeMenu_GameInformation'
);
// Do we show remove score functions?
$context['arcade']['show_editor'] = $context['arcade']['can_admin'];
// Do we have scores to delete?
if ($context['arcade']['can_admin'] && isset($_REQUEST['delete']))
{
checkSession('request');
$_REQUEST['score'] = (int) $_REQUEST['score'];
db_query("
DELETE FROM {$db_prefix}arcade_scores
WHERE ID_SCORE = $_REQUEST[score]", __FILE__, __LINE__);
ArcadeFixPositions($game['id']);
}
$context['template_layers'][] = 'ArcadeGame';
$context['sub_template'] = 'arcade_game_highscore';
$context['page_title'] = $txt['arcade_view_highscore'];
// We don't play :)
$context['arcade']['play'] = false;
$context['linktree'][] = array(
'url' => $scripturl . '?action=arcade;sa=play;game=' . $game['id'],
'name' => $game['name'],
);
$context['linktree'][] = array(
'url' => $scripturl . '?action=arcade;sa=highscore;game=' . $game['id'],
'name' => $txt['arcade_viewscore'],
);
$scoresPerPage = isset($modSettings['scoresPerPage']) ? $modSettings['scoresPerPage'] : 50;
// Did we just play
if (isset($_SESSION['arcade']['highscore']))
{
if ($_SESSION['arcade']['highscore']['gameid'] == $game['id'])
{
// For highlight
$newScore = $_SESSION['arcade']['highscore']['saved'];
$newScore_id = $_SESSION['arcade']['highscore']['id'];
$context['arcade']['new_score'] = array(
'id' => $_SESSION['arcade']['highscore']['id'],
'saved' => $_SESSION['arcade']['highscore']['saved'],
'error' => isset($_SESSION['arcade']['highscore']['error']) ? $_SESSION['arcade']['highscore']['error'] : '',
'score' => comma_format($_SESSION['arcade']['highscore']['score']),
'position' => $_SESSION['arcade']['highscore']['position'],
'can_comment' => $context['arcade']['can_comment_own'] || $context['arcade']['can_comment_any'],
'is_new_champion' => isset($_SESSION['arcade']['highscore']['champion']) ? $_SESSION['arcade']['highscore']['champion'] : false,
'is_personal_best' => isset($_SESSION['arcade']['highscore']['best']) ? $_SESSION['arcade']['highscore']['best'] : false,
);
if (!isset($_GET['start']) && !isset($_POST['start']))
$_REQUEST['start'] = $_SESSION['arcade']['highscore']['start'];
}
else
{
$newScore = false;
unset($_SESSION['arcade']['highscore']);
}
}
else
$newScore = false;
// How many scores there are
$result_count = db_query("
SELECT count(*) AS sc
FROM {$db_prefix}arcade_scores
WHERE ID_GAME = $game[id]", __FILE__, __LINE__);
$score_sort = $game['scoreType'] == 0 ? 'DESC' : 'ASC';
// Actual query
$result_scores = db_query("
SELECT
a.ID_SCORE, a.score, a.endTime AS time, a.gameDuration AS duration, a.comment,
a.position, a.scoreStatus, IFNULL(mem.ID_MEMBER, 0) AS ID_MEMBER, IFNULL(mem.realName, '') AS realName
FROM {$db_prefix}arcade_scores AS a
LEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = a.ID_MEMBER)
WHERE ID_GAME = $game[id]
ORDER BY position
LIMIT $_REQUEST[start], $scoresPerPage", __FILE__, __LINE__);
$context['arcade']['scores'] = array();
$context['arcade']['game'] = $game;
while ($score = mysql_fetch_assoc($result_scores))
{
censorText($score['comment']);
$own = $ID_MEMBER == $score['ID_MEMBER'];
$context['arcade']['scores'][] = array(
'id' => $score['ID_SCORE'],
'own' => $own,
'memberLink' => !empty($score['realName']) ? '<a href="' . $scripturl . '?action=profile;u=' . $score['ID_MEMBER'] . '">' . $score['realName'] . '</a>' : $txt['arcade_guest'],
'score' => comma_format($score['score']),
'time' => timeformat($score['time']),
'duration' => $score['duration'],
'position' => $score['position'],
'score_status' => $score['scoreStatus'],
'comment' => parse_bbc(!empty($score['comment']) ? $score['comment'] : $txt['arcade_no_comment']),
'raw_comment' => $score['comment'],
'highlight' => $newScore ? $score['ID_SCORE'] == $newScore_id : false,
'can_edit' => $newScore ? false : $own ? ($context['arcade']['can_comment_own'] || $context['arcade']['can_comment_any']) : $context['arcade']['can_comment_any'],
'edit' => isset($_REQUEST['edit']) && isset($_REQUEST['score']) && (int) $_REQUEST['score'] == $score['ID_SCORE'],
);
}
$scoreCount = mysql_fetch_assoc($result_count);
// Free results since we don't want to use too much memory
mysql_free_result($result_scores);
mysql_free_result($result_count);
$context['arcade']['pageIndex'] = constructPageIndex($scripturl . '?action=arcade;sa=highscore;game=' . $game['id'], $_REQUEST['start'], $scoreCount['sc'] , $scoresPerPage, false );
}
function CheatingCheck(&$allowFail, &$checkPassed)
{
global $scripturl, $modSettings;
// Default check level is 1
if (!isset($modSettings['arcadeCheckLevel']))
$modSettings['arcadeCheckLevel'] = 1;
if (!empty($_SERVER['HTTP_REFERER']))
$referer = parse_url($_SERVER['HTTP_REFERER']);
$real = parse_url($scripturl);
// Level 1 Check
// Checks also HTTP_REFERER if it not is empty
if ($modSettings['arcadeCheckLevel'] == 1)
{
if (isset($referer) && $real['host'] == $referer['host'] && $real['scheme'] == $referer['scheme'])
$checkPassed = true;
elseif (isset($referer))
$checkPassed = false;
else
$checkPassed = true;
}
// Level 2 Check
// Doesn't allow HTTP_REFERER to be empty
elseif ($modSettings['arcadeCheckLevel'] == 2)
{
if (isset($referer) && $real['host'] == $referer['host'] && $real['scheme'] == $referer['scheme'])
$checkPassed = true;
else
$checkPassed = false;
}
// Level 0 check
else
{
$checkPassed = true;
$allowFail = true;
}
if ($allowFail || $checkPassed)
return true;
else
return false;
}
function ArcadeSubmit()
{
global $scripturl, $txt, $db_prefix, $modSettings, $context;
// Has game session been started, if not then it's probably cheater
if (isset($_SESSION['arcade']['play'][$_POST['game']]))
{
$session_info = &$_SESSION['arcade']['play'][ $_POST['game'] ];
$game = ArcadeGameInfo(0, $session_info['game']);
// Is game installed
if ($game === false)
{
// Not needed anymore
unset($session_info);
fatal_lang_error('arcade_game_not_found');
}
// Was score even submitted
if (isset($_POST['score']) && is_numeric($_POST['score']))
$score = (float) $_POST['score'];
else
{
ClearSession($game);
fatal_lang_error('aracde_submit_error');
}
// Preset these
$checkPassed = false;
$allowFail = false;
if (!CheatingCheck($allowFail, $checkPassed))
{
ClearSession($game);
fatal_lang_error('aracde_submit_error_check_failed');
}
if (allowedTo('arcade_submit'))
{
// Save score
$start = $session_info['startTime'];
$save = ArcadeSaveScore($game, $score, $start, time(), $checkPassed);
ClearSession($game);
// Saving failed
if ($save === false || $save['ID_SCORE'] === false)
$_SESSION['arcade']['highscore'] = array(
'id' => false,
'game' => $game['internalName'],
'score' => $score,
'gameid' => $game['id'],
'position' => 0,
'start' => 0,
'saved' => false,
'error' => isset($save['error']) ? $save['error'] : 'arcade_no_permission'
);
// Save succesful
else
$_SESSION['arcade']['highscore'] = array(
'id' => $save['ID_SCORE'],
'game' => $game['internalName'],
'score' => $score,
'gameid' => $game['id'],
'position' => $save['position'],
'start' => $save['start'],
'champion' => $save['new_champion'],
'best' => $save['ownbest'],
'saved' => true,
);
// Go to scores list
redirectexit('action=arcade;sa=highscore;game=' . $game['id']);
}
else
{
// Too bad no permission to submit score, this isn't fun :(
$_SESSION['arcade']['highscore'] = array(
'id' => false,
'game' => $game['internalName'],
'score' => $score,
'gameid' => $game['id'],
'position' => 0,
'start' => 0,
'saved' => false,
'error' => 'arcade_no_permission',
);
// Not needed anymore
ClearSession($game);
// Go to scores list
redirectexit('action=arcade;sa=highscore;game=' . $game['id']);
}
}
elseif (isset($_SESSION['arcade']['highscore']))
redirectexit('action=arcade;sa=highscore;game=' . $_SESSION['arcade']['highscore']['gameid']);
else
fatal_lang_error('aracde_submit_error_session');
}
function ArcadeSubmitIBP()
{
global $scripturl, $txt, $db_prefix, $modSettings, $context;
if (isset($_SESSION['arcade']['ibp']) && isset($_REQUEST['ibpa']) && $_REQUEST['ibpa'] == 3)
{
$game = ArcadeGameInfo($_SESSION['arcade']['ibp']['game']);
if ($game === false)
fatal_lang_error('arcade_game_not_found');
$session_info = &$_SESSION['arcade']['play'][$game['internalName']];
$time_taken = microtime_float() - $_SESSION['arcade']['ibp']['verify'][2];
if ($time_taken < 0 || $time_taken > 7)
fatal_lang_error('aracde_submit_error_session');
// Was score even submitted
if (isset($_POST['gscore']) && is_numeric($_POST['gscore']))
$score = (float) $_POST['gscore'];
else
{
unset($session_info); // Not needed anymore
fatal_lang_error('aracde_submit_error');
}
$score_check = $score * $_SESSION['arcade']['ibp']['verify'][0] ^ $_SESSION['arcade']['ibp']['verify'][1];
$score_check2 = $_POST['enscore'];
if ($score_check != $score_check2)
fatal_lang_error('aracde_submit_error_session');
if (allowedTo('arcade_submit'))
{
$save = ArcadeSaveScore($game, $score, $session_info['startTime'], round($_SESSION['arcade']['ibp']['verify'][2], 0), true);
ClearSession($game);
if ($save === false || $save['ID_SCORE'] === false)
$_SESSION['arcade']['highscore'] = array(
'id' => false,
'game' => $game['internalName'],
'score' => $score,
'gameid' => $game['id'],
'position' => 0,
'start' => 0,
'saved' => false,
'error' => isset($save['error']) ? $save['error'] : 'arcade_no_permission'
);
// Save succesful
else
$_SESSION['arcade']['highscore'] = array(
'id' => $save['ID_SCORE'],
'game' => $game['internalName'],
'score' => $score,
'gameid' => $game['id'],
'position' => $save['position'],
'start' => $save['start'],
'champion' => $save['new_champion'],
'best' => $save['ownbest'],
'saved' => true,
);
// Go to scores list
redirectexit('action=arcade;sa=highscore;game=' . $game['id']);
}
else
{
// Too bad no permission to submit score, this isn't fun :(
$_SESSION['arcade']['highscore'] = array(
'id' => false,
'game' => $game['internalName'],
'score' => $score,
'gameid' => $game['id'],
'position' => 0,
'start' => 0,
'saved' => false,
'error' => 'arcade_no_permission'
);
ClearSession($game);
// Go to scores list
redirectexit('action=arcade;sa=highscore;game=' . $game['id']);
}
}
elseif (isset($_REQUEST['ibpa']) && $_REQUEST['ibpa'] == 2)
{
$game = ArcadeGameInfo(null, $_POST['gname']);
if ($game === false)
fatal_lang_error('arcade_game_not_found');
// Was score even submitted
if (isset($_POST['gscore']) && is_numeric($_POST['gscore']))
$score = (float) $_POST['gscore'];
else
{
ClearSession($game);
fatal_lang_error('aracde_submit_error');
}
$session_info = &$_SESSION['arcade']['play'][$game['internalName']];
// Preset these
$checkPassed = false;
$allowFail = false;
if (!CheatingCheck($allowFail, $checkPassed))
{
ClearSession($game);
fatal_lang_error('aracde_submit_error_check_failed');
}
if (allowedTo('arcade_submit'))
{
$save = ArcadeSaveScore($game, $score, $session_info['startTime'], time(), true);
ClearSession($game);
if ($save === false || $save['ID_SCORE'] === false)
$_SESSION['arcade']['highscore'] = array(
'id' => false,
'game' => $game['internalName'],
'score' => $score,
'gameid' => $game['id'],
'position' => 0,
'start' => 0,
'saved' => false,
'error' => isset($save['error']) ? $save['error'] : 'arcade_no_permission'
);
// Save succesful
else
$_SESSION['arcade']['highscore'] = array(
'id' => $save['ID_SCORE'],
'game' => $game['internalName'],
'score' => $score,
'gameid' => $game['id'],
'position' => $save['position'],
'start' => $save['start'],
'champion' => $save['new_champion'],
'best' => $save['ownbest'],
'saved' => true,
);
// Go to scores list
redirectexit('action=arcade;sa=highscore;game=' . $game['id']);
}
else
{
// Too bad no permission to submit score, this isn't fun :(
$_SESSION['arcade']['highscore'] = array(
'id' => false,
'game' => $game['internalName'],
'score' => $score,
'gameid' => $game['id'],
'position' => 0,
'start' => 0,
'saved' => false,
'error' => 'arcade_no_permission'
);
ClearSession($game);
// Go to scores list
redirectexit('action=arcade;sa=highscore;game=' . $game['id']);
}
}
else
fatal_lang_error('aracde_submit_error_session');
}
function ClearSession(&$game)
{
global $context;
unset($_SESSION['arcade']['play'][$game['internalName']]);
if ($_SESSION['arcade']['ibp']['game'] == $game['id'])
unset($_SESSION['arcade']['ibp']);
}
function ArcadeVerifyIBP()
{
global $scripturl, $txt, $db_prefix, $modSettings, $context;
$randomchar = rand(1, 200);
$randomchar2 = rand(1, 200);
$_SESSION['arcade']['ibp']['verify'] = array($randomchar, $randomchar2, microtime_float());
// We output flash vars no need for anything that might output something before or after this
ob_end_clean();
if (!empty($modSettings['enableCompressedOutput']))
@ob_start('ob_gzhandler');
else
ob_start();
echo '&randchar=', $randomchar, '&randchar2=', $randomchar2, '&savescore=1&blah=OK';
obExit(false);
}
?>

View File

@ -1,186 +0,0 @@
<?php
/*******************************************************************************
* SMF Arcade 2.0.8 (http://www.smfarcade.info) *
* Copyright (C) 2004-2007 Niko Pahajoki (http://www.madjoki.com) *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
********************************************************************************
* ArcadeSettings.php *
********************************************************************************/
if (!defined('SMF'))
die('Hacking attempt...');
/*
void ArcadeSettings()
- ...
void ArcadeSettingsEdit()
- ...
void ArcadeCategory()
- ...
*/
function ArcadeSettings()
{
global $sourcedir;
require_once($sourcedir . '/Arcade.php');
ArcadeLoad('admin', 'arcade_settings');
$subActions = array(
'edit' => array('ArcadeSettingsEdit', 'arcade_admin'),
'save' => array('ArcadeSettingsSave', 'arcade_admin'),
);
$_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'edit';
isAllowedTo($subActions[$_REQUEST['sa']][1]);
$subActions[$_REQUEST['sa']][0]();
}
function ArcadeSettingsEdit()
{
global $context;
$context['sub_template'] = 'arcadeadmin_settings';
}
function ArcadeSettingsSave()
{
// Validate session
checkSession('post');
// This is array for updateSettings
$settings = array(
'arcadeEnabled' => isset($_REQUEST['enabled']) ? true : false,
'gamesPerPage' => (int) $_REQUEST['gamesPerPage'],
'scoresPerPage' => (int) $_REQUEST['scoresPerPage'],
'arcadeCheckLevel' => (int) $_REQUEST['arcadeCheckLevel'],
'gamesDirectory' => $_REQUEST['gamesDirectory'],
'gamesUrl' => $_REQUEST['gamesUrl'],
'arcadeGameInformationSide' => (int) $_REQUEST['arcadeGameInformationSide'],
'arcadeMaxScores' => (int) $_REQUEST['arcadeMaxScores'],
'arcadePermissionMode' => (int) $_REQUEST['arcadePermissionMode'],
'arcadePostPermission' => isset($_REQUEST['arcadePostPermission']) ? true : false,
'arcadePostsPlay' => (int) $_REQUEST['arcadePostsPlay'],
'arcadePostsPlayPerDay' => (int) $_REQUEST['arcadePostsPlayPerDay']
);
updateSettings($settings);
redirectexit('action=arcadesettings');
}
function ArcadeCategory()
{
global $context, $sourcedir;
require_once($sourcedir . '/Arcade.php');
ArcadeLoad('admin', 'manage_category');
$subActions = array(
'edit' => array('ArcadeCategoryEdit', 'arcade_admin'),
'save' => array('ArcadeCategorySave', 'arcade_admin'),
);
$_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'edit';
isAllowedTo($subActions[$_REQUEST['sa']][1]);
$subActions[$_REQUEST['sa']][0]();
}
function ArcadeCategoryEdit()
{
global $context;
$context['sub_template'] = 'arcadeadmin_category';
prepareMemberGroups();
$context['arcade']['category'] = prepareCategories();
}
function ArcadeCategorySave()
{
global $db_prefix, $modSettings, $context, $sourcedir;
checkSession('post', '',true);
$categories = prepareCategories();
// Create new categories
if (isset($_REQUEST['new']) && is_array($_REQUEST['new']))
foreach ($_REQUEST['new'] as $new)
{
$new = trim($new);
if (!empty($new))
db_query("
INSERT INTO {$db_prefix}arcade_categories
SET catName = '$new', memberGroups = '-1,0,2'",__FILE__,__LINE__);
}
// Handle modifying old ones
if (isset($_REQUEST['category']) && is_array($_REQUEST['category']))
foreach ($_REQUEST['category'] as $id => $category)
{
// Handle name changes
$name = trim($category['name']);
if ($category['name'] == '' && !isset($category['delete']))
continue;
if (isset($category['delete']) && $categories[$id]['canRemove'])
{
db_query("
DELETE FROM {$db_prefix}arcade_categories
WHERE ID_CAT = $id", __FILE__, __LINE__);
db_query("
UPDATE {$db_prefix}arcade_games
SET ID_CAT = $modSettings[arcadeDefaultCategory]
WHERE ID_CAT = $id", __FILE__, __LINE__);
continue;
}
elseif (isset($category['delete']))
fatal_lang_error('arcade_unable_to_remove', false, array($name));
$groups = implode(',', $category['memberGroups']);
$special = '';
if (isset($category['default']) && !$categories[$id]['default'])
{
$special = ', special = 1';
$change['arcadeDefaultCategory'] = $id;
updateSettings($change);
db_query("
UPDATE {$db_prefix}arcade_categories
SET special = 0
WHERE special = 1", __FILE__, __LINE__); // To make sure thre won't be double defaults
}
db_query("
UPDATE {$db_prefix}arcade_categories
SET catName = '$name', memberGroups = '$groups' $special
WHERE ID_CAT = $id", __FILE__, __LINE__);
}
redirectexit('action=arcadecategory');
}
?>

View File

@ -1,298 +0,0 @@
<?php
/*******************************************************************************
* SMF Arcade 2.0.8 (http://www.smfarcade.info) *
* Copyright (C) 2004-2007 Niko Pahajoki (http://www.madjoki.com) *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
********************************************************************************
* ArcadeStats.php *
********************************************************************************/
if (!defined('SMF'))
die('Hacking attempt...');
/*
void ArcadeStats()
- ...
array ArcadeStats_BestPlayers([count = 10])
- ...
array ArcadeStats_LongestChampions([count = 10], [time])
- ...
array ArcadeStats_MostActive([count = 10], [time])
- ...
array ArcadeStats_MostPlayed([count = 10], [time])
- ...
array ArcadeStats_Rating([count = 10])
- ...
string format_time_ago(timestamp)
- Formats time to xxx ago
*/
function ArcadeStats()
{
global $txt, $context;
$context['sub_template'] = 'arcade_statistics';
$context['page_title'] = $txt['arcade_stats_title'];
// Load data using functions
$context['arcade']['statistics']['play'] = ArcadeStats_MostPlayed();
$context['arcade']['statistics']['active'] = ArcadeStats_MostActive();
$context['arcade']['statistics']['rating'] = ArcadeStats_Rating();
$context['arcade']['statistics']['champions'] = ArcadeStats_BestPlayers();
$context['arcade']['statistics']['longest'] = ArcadeStats_LongestChampions();
}
function ArcadeStats_MostPlayed($count = 10)
{
// Returns most playd games
global $db_prefix, $scripturl;
$results = db_query("
SELECT game.ID_GAME, game.gameName, game.gameRating, game.numPlays
FROM {$db_prefix}arcade_games AS game
ORDER BY game.numPlays DESC
LIMIT 0,$count", __FILE__, __LINE__);
$top = array();
$max = -1;
while ($score = mysql_fetch_assoc($results))
{
if ($max == -1)
$max = $score['numPlays'];
if ($max == 0)
return false; // No one has played games yet0
$top[] = array(
'id' => $score['ID_GAME'],
'name' => $score['gameName'],
'link' => '<a href="' . $scripturl . '?action=arcade;sa=play;game=' . $score['ID_GAME'] . '">' . $score['gameName'] . '</a>',
'rating' => $score['gameRating'],
'plays' => $score['numPlays'],
'precent' => ($score['numPlays'] / $max) * 100,
);
}
if (count($top) == 0)
return false;
elseif ($count > 1)
return $top;
else
return $top[0];
}
function ArcadeStats_Rating($count = 10)
{
global $db_prefix, $scripturl;
$results = db_query("
SELECT game.ID_GAME, game.gameName, game.gameRating, game.numPlays
FROM {$db_prefix}arcade_games AS game
WHERE gameRating > 0
ORDER BY game.gameRating DESC
LIMIT 0,$count", __FILE__, __LINE__);
$top = array();
$max = -1;
while ($score = mysql_fetch_assoc($results))
{
if ($max == -1)
$max = $score['gameRating'];
$top[] = array(
'id' => $score['ID_GAME'],
'name' => $score['gameName'],
'link' => '<a href="' . $scripturl . '?action=arcade;sa=play;game=' . $score['ID_GAME'] . '">' . $score['gameName'] . '</a>',
'rating' => $score['gameRating'],
'plays' => $score['numPlays'],
'precent' => ($score['gameRating'] / $max) * 100,
);
}
if (count($top) == 0)
return false;
elseif ($count > 1)
return $top;
else
return $top[0];
}
function ArcadeStats_BestPlayers($count = 10)
{
// Returns best players by count of champions
global $db_prefix, $scripturl, $txt;
$results = db_query("
SELECT count(*) AS champions, IFNULL(mem.ID_MEMBER, 0) AS ID_MEMBER, IFNULL(mem.realName, '') AS realName
FROM {$db_prefix}arcade_games AS game
LEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = game.ID_MEMBER_CHAMPION)
WHERE ID_CHAMPION_SCORE > 0
GROUP BY game.ID_MEMBER_CHAMPION
ORDER BY champions DESC
LIMIT 0,$count", __FILE__, __LINE__);
$top = array();
$max = -1;
while ($score = mysql_fetch_assoc($results))
{
if ($max == -1)
$max = $score['champions'];
$top[] = array(
'name' => $score['realName'],
'link' => !empty($score['realName']) ? '<a href="' . $scripturl . '?action=profile;u=' . $score['ID_MEMBER'] . '">' . $score['realName'] . '</a>' : $txt['arcade_guest'],
'champions' => $score['champions'],
'precent' => ($score['champions'] / $max) * 100,
);
}
if (count($top) == 0)
return false;
elseif ($count > 1)
return $top;
else
return $top[0];
}
function ArcadeStats_MostActive($count = 10, $time = -1)
{
// Returns most active players
global $db_prefix, $scripturl, $txt;
$results = db_query("
SELECT count(*) AS scores, IFNULL(mem.ID_MEMBER, 0) AS ID_MEMBER, IFNULL(mem.realName, '') AS realName
FROM {$db_prefix}arcade_scores AS score
LEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = score.ID_MEMBER)
GROUP BY score.ID_MEMBER
ORDER BY scores DESC
LIMIT 0,$count", __FILE__, __LINE__);
$top = array();
$max = -1;
while ($score = mysql_fetch_assoc($results))
{
if ($max == -1)
$max = $score['scores'];
$top[] = array(
'name' => $score['realName'],
'link' => !empty($score['realName']) ? '<a href="' . $scripturl . '?action=profile;u=' . $score['ID_MEMBER'] . '">' . $score['realName'] . '</a>' : $txt['arcade_guest'],
'scores' => $score['scores'],
'precent' => ($score['scores'] / $max) * 100,
);
}
if (count($top) == 0 || $count == 1)
return false;
elseif ($count > 1)
return $top;
else
return $top[0];
}
function ArcadeStats_LongestChampions($count = 10, $time = - 1)
{
global $db_prefix, $scripturl, $txt;
if ($time == 'current')
$where = '
AND championTo = 0';
elseif ($time != -1)
$where = "
AND championFrom > $time";
$results = db_query("
SELECT game.ID_GAME, game.gameName,
IF(championFrom > 0, (IF(championTo = 0, UNIX_TIMESTAMP(), championTo) - championFrom), 0) AS championDuration,
IFNULL(mem.ID_MEMBER, 0) AS ID_MEMBER, IFNULL(mem.realName, '') AS realName, IF(championTo = 0, 1, 0) AS current
FROM ({$db_prefix}arcade_scores AS score, {$db_prefix}arcade_games AS game)
LEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = score.ID_MEMBER)
WHERE game.ID_GAME = score.ID_GAME{$where}
HAVING championDuration > 0
ORDER BY IF(championFrom > 0, (IF(championTo = 0, UNIX_TIMESTAMP(), championTo) - championFrom), 0) DESC
LIMIT $count", __FILE__, __LINE__);
$top = array();
$max = -1;
while ($score = mysql_fetch_assoc($results))
{
if ($max == -1)
$max = $score['championDuration'];
$top[] = array(
'game_name' => $score['gameName'],
'game_link' => '<a href="' . $scripturl . '?action=arcade;sa=play;game=' . $score['ID_GAME'] . '">' . $score['gameName'] . '</a>',
'member_name' => $score['realName'],
'member_link' => !empty($score['realName']) ? '<a href="' . $scripturl . '?action=profile;u=' . $score['ID_MEMBER'] . '">' . $score['realName'] . '</a>' : $txt['arcade_guest'],
'duration' => format_time_ago($score['championDuration']),
'precent' => ($score['championDuration'] / $max) * 100,
'current' => $score['current'] == 1,
);
}
if (count($top) == 0)
return false;
elseif ($count > 1)
return $top;
else
return $top[0];
}
function format_time_ago($timestamp)
{
global $txt;
// Returns formated string
$yksikot = array(
array(604800, $txt['arcade_weeks']), // Seconds in week
array(86400, $txt['arcade_days']), // Seconds in day
array(3600, $txt['arcade_hours']), // Seconds in hour
array(60, $txt['arcade_mins']), // Seconds in minute
);
if ($timestamp < 60)
return $txt['arcade_under_minute_ago'];
$text = '';
foreach( $yksikot as $t )
{
$tassa = floor($timestamp / $t[0]);
if ( $tassa > 1 )
{
$text .= $tassa . ' '. $t[1];
$text .= ' ';
$timestamp = $timestamp - ($t[0] * $tassa);
}
}
return trim($text);
}
?>

View File

@ -1,143 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0
*/
if (!defined('SMF'))
die('Hacking attempt...');
/* The single function this file contains is used to display the main
board index. It uses just the following functions:
void BoardIndex()
- shows the board index.
- uses the BoardIndex template, and main sub template.
- may use the boardindex subtemplate for wireless support.
- updates the most online statistics.
- is accessed by ?action=boardindex.
void CollapseCategory()
- collapse or expand a category
*/
// Show the board index!
function BoardIndex()
{
global $txt, $user_info, $sourcedir, $modSettings, $context, $settings, $scripturl;
// For wireless, we use the Wireless template...
if (WIRELESS)
$context['sub_template'] = WIRELESS_PROTOCOL . '_boardindex';
else
loadTemplate('BoardIndex');
// Set a canonical URL for this page.
$context['canonical_url'] = $scripturl;
// Do not let search engines index anything if there is a random thing in $_GET.
if (!empty($_GET))
$context['robot_no_index'] = true;
// Retrieve the categories and boards.
require_once($sourcedir . '/Subs-BoardIndex.php');
$boardIndexOptions = array(
'include_categories' => true,
'base_level' => 0,
'parent_id' => 0,
'set_latest_post' => true,
'countChildPosts' => !empty($modSettings['countChildPosts']),
);
$context['categories'] = getBoardIndex($boardIndexOptions);
// Get the user online list.
require_once($sourcedir . '/Subs-MembersOnline.php');
$membersOnlineOptions = array(
'show_hidden' => allowedTo('moderate_forum'),
'sort' => 'log_time',
'reverse_sort' => true,
);
$context += getMembersOnlineStats($membersOnlineOptions);
$context['show_buddies'] = !empty($user_info['buddies']);
// Are we showing all membergroups on the board index?
if (!empty($settings['show_group_key']))
$context['membergroups'] = cache_quick_get('membergroup_list', 'Subs-Membergroups.php', 'cache_getMembergroupList', array());
// Track most online statistics? (Subs-MembersOnline.php)
if (!empty($modSettings['trackStats']))
trackStatsUsersOnline($context['num_guests'] + $context['num_spiders'] + $context['num_users_online']);
// Retrieve the latest posts if the theme settings require it.
if (isset($settings['number_recent_posts']) && $settings['number_recent_posts'] > 1)
{
$latestPostOptions = array(
'number_posts' => $settings['number_recent_posts'],
);
$context['latest_posts'] = cache_quick_get('boardindex-latest_posts:' . md5($user_info['query_wanna_see_board'] . $user_info['language']), 'Subs-Recent.php', 'cache_getLastPosts', array($latestPostOptions));
}
$settings['display_recent_bar'] = !empty($settings['number_recent_posts']) ? $settings['number_recent_posts'] : 0;
$settings['show_member_bar'] &= allowedTo('view_mlist');
$context['show_stats'] = allowedTo('view_stats') && !empty($modSettings['trackStats']);
$context['show_member_list'] = allowedTo('view_mlist');
$context['show_who'] = allowedTo('who_view') && !empty($modSettings['who_enabled']);
// Load the calendar?
if (!empty($modSettings['cal_enabled']) && allowedTo('calendar_view'))
{
// Retrieve the calendar data (events, birthdays, holidays).
$eventOptions = array(
'include_holidays' => $modSettings['cal_showholidays'] > 1,
'include_birthdays' => $modSettings['cal_showbdays'] > 1,
'include_events' => $modSettings['cal_showevents'] > 1,
'num_days_shown' => empty($modSettings['cal_days_for_index']) || $modSettings['cal_days_for_index'] < 1 ? 1 : $modSettings['cal_days_for_index'],
);
$context += cache_quick_get('calendar_index_offset_' . ($user_info['time_offset'] + $modSettings['time_offset']), 'Subs-Calendar.php', 'cache_getRecentEvents', array($eventOptions));
// Whether one or multiple days are shown on the board index.
$context['calendar_only_today'] = $modSettings['cal_days_for_index'] == 1;
// This is used to show the "how-do-I-edit" help.
$context['calendar_can_edit'] = allowedTo('calendar_edit_any');
}
else
$context['show_calendar'] = false;
$context['page_title'] = sprintf($txt['forum_index'], $context['forum_name']);
}
// Collapse or expand a category
function CollapseCategory()
{
global $user_info, $sourcedir, $context;
// Just in case, no need, no need.
$context['robot_no_index'] = true;
checkSession('request');
if (!isset($_GET['sa']))
fatal_lang_error('no_access', false);
// Check if the input values are correct.
if (in_array($_REQUEST['sa'], array('expand', 'collapse', 'toggle')) && isset($_REQUEST['c']))
{
// And collapse/expand/toggle the category.
require_once($sourcedir . '/Subs-Categories.php');
collapseCategories(array((int) $_REQUEST['c']), $_REQUEST['sa'], array($user_info['id']));
}
// And go back to the board index.
BoardIndex();
}
?>

View File

@ -1,408 +0,0 @@
<?php
/**********************************************************************************
* Buddies.php *
***********************************************************************************
* Version: 0.9
* This file is a part of Ultimate Profile mod
* Author: Jovan Turanjanin *
**********************************************************************************/
if (!defined('SMF'))
die('Hacking attempt...');
function BuddiesMain()
{
isAllowedTo('profile_extra_own');
loadTemplate('Buddies');
loadLanguage('UltimateProfile');
switch (@$_GET['sa']) {
case 'add': BuddyAdd(); break;
case 'remove': BuddyRemove(); break;
case 'approve': BuddyApprove(); break;
case 'order': BuddyOrder(); break;
default: Buddies();
}
}
function Buddies()
{
global $smcFunc, $context, $user_profile, $memberContext, $txt;
// approved buddies
$buddies = array();
$request = $smcFunc['db_query']('', '
SELECT buddy_id
FROM {db_prefix}buddies
WHERE id_member = {int:id_member}
AND approved = 1
ORDER BY position ASC, time_updated DESC',
array(
'id_member' => $context['user']['id'],
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
$buddies[] = $row['buddy_id'];
$smcFunc['db_free_result']($request);
// Load all the members up.
loadMemberData($buddies, false, 'profile');
$context['buddies'] = array();
foreach ($buddies as $buddy)
{
loadMemberContext($buddy);
$context['buddies'][$buddy] = $memberContext[$buddy];
}
// unapproved buddies
$buddies = array();
$request = $smcFunc['db_query']('', '
SELECT buddy_id
FROM {db_prefix}buddies
WHERE id_member = {int:id_member}
AND approved = 0
AND requested <> {int:requested}
ORDER BY position ASC, time_updated DESC',
array(
'id_member' => $context['user']['id'],
'requested' => $context['user']['id'],
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
$buddies[] = $row['buddy_id'];
$smcFunc['db_free_result']($request);
if (count($buddies) > 0) {
// Load all the members up.
loadMemberData($buddies, false, 'profile');
$context['unapproved'] = array();
foreach ($buddies as $buddy)
{
loadMemberContext($buddy);
$context['unapproved'][$buddy] = $memberContext[$buddy];
}
}
// pending buddies
$buddies = array();
$request = $smcFunc['db_query']('', '
SELECT id_member
FROM {db_prefix}buddies
WHERE buddy_id = {int:buddy_id}
AND approved = 0
AND requested = {int:requested}
ORDER BY position ASC, time_updated DESC',
array(
'buddy_id' => $context['user']['id'],
'requested' => $context['user']['id'],
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
$buddies[] = $row['id_member'];
$smcFunc['db_free_result']($request);
if (count($buddies) > 0) {
// Load all the members up.
loadMemberData($buddies, false, 'profile');
$context['pending'] = array();
foreach ($buddies as $buddy)
{
loadMemberContext($buddy);
$context['pending'][$buddy] = $memberContext[$buddy];
}
}
$_GET['action'] = 'profile'; // <20>ust for the tab...
$context['page_title'] = $txt['buddy_center'];
$context['sub_template'] = 'buddy_center';
}
function BuddyOrder()
{
global $smcFunc, $context;
checkSession('get');
$_GET['u'] = (int)$_GET['u'];
$request = $smcFunc['db_query']('', '
SELECT position
FROM {db_prefix}buddies
WHERE buddy_id = {int:buddy_id}
AND id_member = {int:id_member}',
array(
'buddy_id' => $_GET['u'],
'id_member' => $context['user']['id'],
)
);
list($old_position) = $smcFunc['db_fetch_row']($request);
if ($_GET['dir'] == 'up')
$request = $smcFunc['db_query']('', '
SELECT buddy_id, position
FROM {db_prefix}buddies
WHERE id_member = {int:id_member}
AND position < {int:position}
ORDER BY time_updated DESC LIMIT 1',
array(
'id_member' => $context['user']['id'],
'position' => $old_position,
)
);
else
$request = $smcFunc['db_query']('', '
SELECT buddy_id, position
FROM {db_prefix}buddies
WHERE id_member = {int:id_member}
AND position > {int:position}
ORDER BY time_updated DESC LIMIT 1',
array(
'id_member' => $context['user']['id'],
'position' => $old_position,
)
);
list($buddy_id, $new_position) = $smcFunc['db_fetch_row']($request);
$buddy_id = (int)$buddy_id;
$new_position = (int)$new_position;
if ($new_position == 0)
$new_position = ($_GET['dir'] == 'up') ? $old_position - 1 : $old_position + 1;
$smcFunc['db_query']('', '
UPDATE {db_prefix}buddies SET
position = {int:position},
time_updated = {int:time}
WHERE id_member = {int:id_member}
AND buddy_id = {int:buddy_id}',
array(
'position' => $new_position,
'time' => time(),
'id_member' => $context['user']['id'],
'buddy_id' => $_GET['u'],
)
);
$smcFunc['db_query']('', '
UPDATE {db_prefix}buddies SET
position = {int:position},
time_updated = {int:time}
WHERE id_member = {int:id_member}
AND buddy_id = {int:buddy_id}',
array(
'position' => $old_position,
'time' => time(),
'id_member' => $context['user']['id'],
'buddy_id' => $buddy_id,
)
);
redirectexit('action=buddies');
}
function BuddyAdd()
{
global $smcFunc, $sourcedir, $txt, $context, $scripturl, $language, $modSettings;
checkSession('get');
$_GET['u'] = (int)$_GET['u'];
$request = $smcFunc['db_query']('', '
SELECT approved
FROM {db_prefix}buddies
WHERE id_member = {int:id_member}
AND buddy_id = {int:buddy_id}',
array(
'id_member' => $context['user']['id'],
'buddy_id' => $_GET['u'],
)
);
if ($smcFunc['db_num_rows']($request) > 0)
fatal_error($txt['buddy_already_added'], false);
$request = $smcFunc['db_query']('', '
SELECT real_name
FROM {db_prefix}members
WHERE id_member = {int:id_member}',
array(
'id_member' => $_GET['u'],
)
);
if ($smcFunc['db_num_rows']($request) < 1)
redirectexit();
// Find the new position.
$request = $smcFunc['db_query']('', 'SELECT position
FROM {db_prefix}buddies
WHERE id_member = {int:id_member}
ORDER BY position DESC
LIMIT 1',
array(
'id_member' => $context['user']['id'],
)
);
list($position) = $smcFunc['db_fetch_row']($request);
$position = $position + 1;
$smcFunc['db_insert']('normal', '{db_prefix}buddies',
array(
'id_member' => 'int',
'buddy_id' => 'int',
'approved' => 'int',
'position' => 'int',
'time_updated' => 'int',
'requested' => 'int',
),
array(
'id_member' => $context['user']['id'],
'buddy_id' => $_GET['u'],
'approved' => '0',
'position' => $position,
'time_updated' => time(),
'requested' => $context['user']['id'],
),
array()
);
$request = $smcFunc['db_query']('', '
SELECT position
FROM {db_prefix}buddies
WHERE id_member = {int:id_member}
ORDER BY position DESC
LIMIT 1',
array(
'id_member' => $_GET['u'],
)
);
list($position) = $smcFunc['db_fetch_row']($request);
$position = $position + 1;
$smcFunc['db_insert']('normal', '{db_prefix}buddies',
array(
'buddy_id' => 'int',
'id_member' => 'int',
'approved' => 'int',
'position' => 'int',
'time_updated' => 'int',
'requested' => 'int',
),
array(
'buddy_id' => $context['user']['id'],
'id_member' => $_GET['u'],
'approved' => '0',
'position' => $position,
'time_updated' => time(),
'requested' => $context['user']['id'],
),
array()
);
// Let's notify the user.
$request = $smcFunc['db_query']('', '
SELECT lngfile
FROM {db_prefix}members
WHERE id_member = {int:id_member}',
array(
'id_member' => $_GET['u'],
)
);
list($user_language) = $smcFunc['db_fetch_row']($request);
loadLanguage('UltimateProfile', empty($user_language) || empty($modSettings['userLanguage']) ? $language : $user_language, false);
require_once $sourcedir . '/Subs-Post.php';
sendpm(array('to' => array($_GET['u']), 'bcc' => array()), sprintf($txt['buddy_notif_new_subject'], $context['user']['name']), sprintf($txt['buddy_notif_new_body'], $context['user']['name'], $scripturl . '?action=buddies'), false, array('id' => 0, 'name' => $txt['profile_notif_com_user'], 'username' => $txt['profile_notif_com_user']));
redirectexit('action=profile;u=' . $_GET['u']);
}
function BuddyApprove()
{
global $smcFunc, $user_info, $user_profile, $context;
checkSession('get');
$_GET['u'] = (int)$_GET['u'];
$smcFunc['db_query']('', '
UPDATE {db_prefix}buddies SET
approved = 1
WHERE id_member = {int:id_member}
AND buddy_id = {int:buddy_id}',
array(
'id_member' => $context['user']['id'],
'buddy_id' => $_GET['u'],
)
);
$smcFunc['db_query']('', '
UPDATE {db_prefix}buddies SET
approved = 1
WHERE buddy_id = {int:buddy_id}
AND id_member = {int:id_member}',
array(
'buddy_id' => $context['user']['id'],
'id_member' => $_GET['u'],
)
);
// Update SMF's system as well...
$user_info['buddies'][] = $_GET['u'];
updateMemberData($context['user']['id'], array('buddy_list' => "'" . implode(',', $user_info['buddies']) . "'"));
loadMemberData($_GET['u'], false, 'normal');
$buddies = explode(',', $user_profile[$_GET['u']]['buddy_list']);
$buddies[] = $context['user']['id'];
updateMemberData($_GET['u'], array('buddy_list' => "'" . implode(',', $buddies) . "'"));
redirectexit('action=buddies');
}
function BuddyRemove()
{
global $smcFunc, $user_info, $user_profile, $context;
checkSession('get');
$_GET['u'] = (int)$_GET['u'];
$smcFunc['db_query']('', '
DELETE FROM {db_prefix}buddies
WHERE id_member = {int:id_member}
AND buddy_id = {int:buddy_id}',
array(
'id_member' => $context['user']['id'],
'buddy_id' => $_GET['u'],
)
);
$smcFunc['db_query']('', '
DELETE FROM {db_prefix}buddies
WHERE buddy_id = {int:buddy_id}
AND id_member = {int:id_member}',
array(
'buddy_id' => $context['user']['id'],
'id_member' => $_GET['u'],
)
);
// Update SMF's system as well...
$user_info['buddies'] = array_diff($user_info['buddies'], array($_GET['u']));
updateMemberData($context['user']['id'], array('buddy_list' => "'" . implode(',', $user_info['buddies']) . "'"));
loadMemberData($_GET['u'], false, 'normal');
$buddies = explode(',', $user_profile[$_GET['u']]['buddy_list']);
$buddies = array_diff($buddies, array($context['user']['id']));
updateMemberData($_GET['u'], array('buddy_list' => "'" . implode(',', $buddies) . "'"));
redirectexit('action=buddies');
}
?>

View File

@ -1,487 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0
*/
// Original module by Aaron O'Neil - aaron@mud-master.com
if (!defined('SMF'))
die('Hacking attempt...');
/* This file has only one real task... showing the calendar. Posting is done
in Post.php - this just has the following functions:
void CalendarMain()
- loads the specified month's events, holidays, and birthdays.
- requires the calendar_view permission.
- depends on the cal_enabled setting, and many of the other cal_
settings.
- uses the calendar_start_day theme option. (Monday/Sunday)
- uses the main sub template in the Calendar template.
- goes to the month and year passed in 'month' and 'year' by
get or post.
- accessed through ?action=calendar.
void CalendarPost()
- processes posting/editing/deleting a calendar event.
- calls Post() function if event is linked to a post.
- calls insertEvent() to insert the event if not linked to post.
- requires the calendar_post permission to use.
- uses the event_post sub template in the Calendar template.
- is accessed with ?action=calendar;sa=post.
void iCalDownload()
- offers up a download of an event in iCal 2.0 format.
*/
// Show the calendar.
function CalendarMain()
{
global $txt, $context, $modSettings, $scripturl, $options, $sourcedir;
// Permissions, permissions, permissions.
isAllowedTo('calendar_view');
// Doing something other than calendar viewing?
$subActions = array(
'ical' => 'iCalDownload',
'post' => 'CalendarPost',
);
if (isset($_GET['sa']) && isset($subActions[$_GET['sa']]) && !WIRELESS)
return $subActions[$_GET['sa']]();
// This is gonna be needed...
loadTemplate('Calendar');
// You can't do anything if the calendar is off.
if (empty($modSettings['cal_enabled']))
fatal_lang_error('calendar_off', false);
// Set the page title to mention the calendar ;).
$context['page_title'] = $txt['calendar'];
// Is this a week view?
$context['view_week'] = isset($_GET['viewweek']);
// Don't let search engines index weekly calendar pages.
if ($context['view_week'])
$context['robot_no_index'] = true;
// Get the current day of month...
require_once($sourcedir . '/Subs-Calendar.php');
$today = getTodayInfo();
// If the month and year are not passed in, use today's date as a starting point.
$curPage = array(
'day' => isset($_REQUEST['day']) ? (int) $_REQUEST['day'] : $today['day'],
'month' => isset($_REQUEST['month']) ? (int) $_REQUEST['month'] : $today['month'],
'year' => isset($_REQUEST['year']) ? (int) $_REQUEST['year'] : $today['year']
);
// Make sure the year and month are in valid ranges.
if ($curPage['month'] < 1 || $curPage['month'] > 12)
fatal_lang_error('invalid_month', false);
if ($curPage['year'] < $modSettings['cal_minyear'] || $curPage['year'] > $modSettings['cal_maxyear'])
fatal_lang_error('invalid_year', false);
// If we have a day clean that too.
if ($context['view_week'])
{
// Note $isValid is -1 < PHP 5.1
$isValid = mktime(0, 0, 0, $curPage['month'], $curPage['day'], $curPage['year']);
if ($curPage['day'] > 31 || !$isValid || $isValid == -1)
fatal_lang_error('invalid_day', false);
}
// Load all the context information needed to show the calendar grid.
$calendarOptions = array(
'start_day' => !empty($options['calendar_start_day']) ? $options['calendar_start_day'] : 0,
'show_birthdays' => in_array($modSettings['cal_showbdays'], array(1, 2)),
'show_events' => in_array($modSettings['cal_showevents'], array(1, 2)),
'show_holidays' => in_array($modSettings['cal_showholidays'], array(1, 2)),
'show_week_num' => true,
'short_day_titles' => false,
'show_next_prev' => true,
'show_week_links' => true,
'size' => 'large',
);
// Load up the main view.
if ($context['view_week'])
$context['calendar_grid_main'] = getCalendarWeek($curPage['month'], $curPage['year'], $curPage['day'], $calendarOptions);
else
$context['calendar_grid_main'] = getCalendarGrid($curPage['month'], $curPage['year'], $calendarOptions);
// Load up the previous and next months.
$calendarOptions['show_birthdays'] = $calendarOptions['show_events'] = $calendarOptions['show_holidays'] = false;
$calendarOptions['short_day_titles'] = true;
$calendarOptions['show_next_prev'] = false;
$calendarOptions['show_week_links'] = false;
$calendarOptions['size'] = 'small';
$context['calendar_grid_current'] = getCalendarGrid($curPage['month'], $curPage['year'], $calendarOptions);
// Only show previous month if it isn't pre-January of the min-year
if ($context['calendar_grid_current']['previous_calendar']['year'] > $modSettings['cal_minyear'] || $curPage['month'] != 1)
$context['calendar_grid_prev'] = getCalendarGrid($context['calendar_grid_current']['previous_calendar']['month'], $context['calendar_grid_current']['previous_calendar']['year'], $calendarOptions);
// Only show next month if it isn't post-December of the max-year
if ($context['calendar_grid_current']['next_calendar']['year'] < $modSettings['cal_maxyear'] || $curPage['month'] != 12)
$context['calendar_grid_next'] = getCalendarGrid($context['calendar_grid_current']['next_calendar']['month'], $context['calendar_grid_current']['next_calendar']['year'], $calendarOptions);
// Basic template stuff.
$context['can_post'] = allowedTo('calendar_post');
$context['current_day'] = $curPage['day'];
$context['current_month'] = $curPage['month'];
$context['current_year'] = $curPage['year'];
$context['show_all_birthdays'] = isset($_GET['showbd']);
// Set the page title to mention the month or week, too
$context['page_title'] .= ' - ' . ($context['view_week'] ? sprintf($txt['calendar_week_title'], $context['calendar_grid_main']['week_number'], ($context['calendar_grid_main']['week_number'] == 53 ? $context['current_year'] - 1 : $context['current_year'])) : $txt['months'][$context['current_month']] . ' ' . $context['current_year']);
// Load up the linktree!
$context['linktree'][] = array(
'url' => $scripturl . '?action=calendar',
'name' => $txt['calendar']
);
// Add the current month to the linktree.
$context['linktree'][] = array(
'url' => $scripturl . '?action=calendar;year=' . $context['current_year'] . ';month=' . $context['current_month'],
'name' => $txt['months'][$context['current_month']] . ' ' . $context['current_year']
);
// If applicable, add the current week to the linktree.
if ($context['view_week'])
$context['linktree'][] = array(
'url' => $scripturl . '?action=calendar;viewweek;year=' . $context['current_year'] . ';month=' . $context['current_month'] . ';day=' . $context['current_day'],
'name' => $txt['calendar_week'] . ' ' . $context['calendar_grid_main']['week_number']
);
}
function CalendarPost()
{
global $context, $txt, $user_info, $sourcedir, $scripturl;
global $modSettings, $topic, $smcFunc;
// Well - can they?
isAllowedTo('calendar_post');
// We need this for all kinds of useful functions.
require_once($sourcedir . '/Subs-Calendar.php');
// Cast this for safety...
if (isset($_REQUEST['eventid']))
$_REQUEST['eventid'] = (int) $_REQUEST['eventid'];
// Submitting?
if (isset($_POST[$context['session_var']], $_REQUEST['eventid']))
{
checkSession();
// Validate the post...
if (!isset($_POST['link_to_board']))
validateEventPost();
// If you're not allowed to edit any events, you have to be the poster.
if ($_REQUEST['eventid'] > 0 && !allowedTo('calendar_edit_any'))
isAllowedTo('calendar_edit_' . (!empty($user_info['id']) && getEventPoster($_REQUEST['eventid']) == $user_info['id'] ? 'own' : 'any'));
// New - and directing?
if ($_REQUEST['eventid'] == -1 && isset($_POST['link_to_board']))
{
$_REQUEST['calendar'] = 1;
require_once($sourcedir . '/Post.php');
return Post();
}
// New...
elseif ($_REQUEST['eventid'] == -1)
{
$eventOptions = array(
'board' => 0,
'topic' => 0,
'title' => substr($_REQUEST['evtitle'], 0, 60),
'member' => $user_info['id'],
'start_date' => sprintf('%04d-%02d-%02d', $_POST['year'], $_POST['month'], $_POST['day']),
'span' => isset($_POST['span']) && $_POST['span'] > 0 ? min((int) $modSettings['cal_maxspan'], (int) $_POST['span'] - 1) : 0,
);
insertEvent($eventOptions);
}
// Deleting...
elseif (isset($_REQUEST['deleteevent']))
removeEvent($_REQUEST['eventid']);
// ... or just update it?
else
{
$eventOptions = array(
'title' => substr($_REQUEST['evtitle'], 0, 60),
'span' => empty($modSettings['cal_allowspan']) || empty($_POST['span']) || $_POST['span'] == 1 || empty($modSettings['cal_maxspan']) || $_POST['span'] > $modSettings['cal_maxspan'] ? 0 : min((int) $modSettings['cal_maxspan'], (int) $_POST['span'] - 1),
'start_date' => strftime('%Y-%m-%d', mktime(0, 0, 0, (int) $_REQUEST['month'], (int) $_REQUEST['day'], (int) $_REQUEST['year'])),
);
modifyEvent($_REQUEST['eventid'], $eventOptions);
}
updateSettings(array(
'calendar_updated' => time(),
));
// No point hanging around here now...
redirectexit($scripturl . '?action=calendar;month=' . $_POST['month'] . ';year=' . $_POST['year']);
}
// If we are not enabled... we are not enabled.
if (empty($modSettings['cal_allow_unlinked']) && empty($_REQUEST['eventid']))
{
$_REQUEST['calendar'] = 1;
require_once($sourcedir . '/Post.php');
return Post();
}
// New?
if (!isset($_REQUEST['eventid']))
{
$today = getdate();
$context['event'] = array(
'boards' => array(),
'board' => 0,
'new' => 1,
'eventid' => -1,
'year' => isset($_REQUEST['year']) ? $_REQUEST['year'] : $today['year'],
'month' => isset($_REQUEST['month']) ? $_REQUEST['month'] : $today['mon'],
'day' => isset($_REQUEST['day']) ? $_REQUEST['day'] : $today['mday'],
'title' => '',
'span' => 1,
);
$context['event']['last_day'] = (int) strftime('%d', mktime(0, 0, 0, $context['event']['month'] == 12 ? 1 : $context['event']['month'] + 1, 0, $context['event']['month'] == 12 ? $context['event']['year'] + 1 : $context['event']['year']));
// Get list of boards that can be posted in.
$boards = boardsAllowedTo('post_new');
if (empty($boards))
fatal_lang_error('cannot_post_new', 'permission');
// Load the list of boards and categories in the context.
require_once($sourcedir . '/Subs-MessageIndex.php');
$boardListOptions = array(
'included_boards' => in_array(0, $boards) ? null : $boards,
'not_redirection' => true,
'use_permissions' => true,
'selected_board' => $modSettings['cal_defaultboard'],
);
$context['event']['categories'] = getBoardList($boardListOptions);
}
else
{
$context['event'] = getEventProperties($_REQUEST['eventid']);
if ($context['event'] === false)
fatal_lang_error('no_access', false);
// If it has a board, then they should be editing it within the topic.
if (!empty($context['event']['topic']['id']) && !empty($context['event']['topic']['first_msg']))
{
// We load the board up, for a check on the board access rights...
$topic = $context['event']['topic']['id'];
loadBoard();
}
// Make sure the user is allowed to edit this event.
if ($context['event']['member'] != $user_info['id'])
isAllowedTo('calendar_edit_any');
elseif (!allowedTo('calendar_edit_any'))
isAllowedTo('calendar_edit_own');
}
// Template, sub template, etc.
loadTemplate('Calendar');
$context['sub_template'] = 'event_post';
$context['page_title'] = isset($_REQUEST['eventid']) ? $txt['calendar_edit'] : $txt['calendar_post_event'];
$context['linktree'][] = array(
'name' => $context['page_title'],
);
}
function iCalDownload()
{
global $smcFunc, $sourcedir, $forum_version, $context, $modSettings;
// Goes without saying that this is required.
if (!isset($_REQUEST['eventid']))
fatal_lang_error('no_access', false);
// This is kinda wanted.
require_once($sourcedir . '/Subs-Calendar.php');
// Load up the event in question and check it exists.
$event = getEventProperties($_REQUEST['eventid']);
if ($event === false)
fatal_lang_error('no_access', false);
// Check the title isn't too long - iCal requires some formatting if so.
$title = str_split($event['title'], 30);
foreach ($title as $id => $line)
{
if ($id != 0)
$title[$id] = ' ' . $title[$id];
$title[$id] .= "\n";
}
// Format the date.
$date = $event['year'] . '-' . ($event['month'] < 10 ? '0' . $event['month'] : $event['month']) . '-' . ($event['day'] < 10 ? '0' . $event['day'] : $event['day']) . 'T';
$date .= '1200:00:00Z';
// This is what we will be sending later.
$filecontents = '';
$filecontents .= 'BEGIN:VCALENDAR' . "\n";
$filecontents .= 'VERSION:2.0' . "\n";
$filecontents .= 'PRODID:-//SimpleMachines//SMF ' . (empty($forum_version) ? 1.0 : strtr($forum_version, array('SMF ' => ''))) . '//EN' . "\n";
$filecontents .= 'BEGIN:VEVENT' . "\n";
$filecontents .= 'DTSTART:' . $date . "\n";
$filecontents .= 'DTEND:' . $date . "\n";
$filecontents .= 'SUMMARY:' . implode('', $title);
$filecontents .= 'END:VEVENT' . "\n";
$filecontents .= 'END:VCALENDAR';
// Send some standard headers.
ob_end_clean();
if (!empty($modSettings['enableCompressedOutput']))
@ob_start('ob_gzhandler');
else
ob_start();
// Send the file headers
header('Pragma: ');
header('Cache-Control: no-cache');
if (!$context['browser']['is_gecko'])
header('Content-Transfer-Encoding: binary');
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 525600 * 60) . ' GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . 'GMT');
header('Accept-Ranges: bytes');
header('Connection: close');
header('Content-Disposition: attachment; filename=' . $event['title'] . '.ics');
// How big is it?
if (empty($modSettings['enableCompressedOutput']))
header('Content-Length: ' . $smcFunc['strlen']($filecontents));
// This is a calendar item!
header('Content-Type: text/calendar');
// Chuck out the card.
echo $filecontents;
// Off we pop - lovely!
obExit(false);
}
// This is not the code you are looking for.
function clock()
{
global $settings, $context;
$context['onimg'] = $settings['images_url'] . '/bbc/bbc_bg.gif';
$context['offimg'] = $settings['images_url'] . '/bbc/bbc_hoverbg.gif';
$context['page_title'] = 'Anyone know what time it is?';
$context['robot_no_index'] = true;
$omfg = isset($_REQUEST['omfg']);
$bcd = !isset($_REQUEST['rb']) && !isset($_REQUEST['omfg']) && !isset($_REQUEST['time']);
loadTemplate('Calendar');
if ($bcd && !$omfg)
{
$context['sub_template'] = 'bcd';
$context['clockicons'] = unserialize(base64_decode('YTo2OntzOjI6ImgxIjthOjI6e2k6MDtpOjI7aToxO2k6MTt9czoyOiJoMiI7YTo0OntpOjA7aTo4O2k6MTtpOjQ7aToyO2k6MjtpOjM7aToxO31zOjI6Im0xIjthOjM6e2k6MDtpOjQ7aToxO2k6MjtpOjI7aToxO31zOjI6Im0yIjthOjQ6e2k6MDtpOjg7aToxO2k6NDtpOjI7aToyO2k6MztpOjE7fXM6MjoiczEiO2E6Mzp7aTowO2k6NDtpOjE7aToyO2k6MjtpOjE7fXM6MjoiczIiO2E6NDp7aTowO2k6ODtpOjE7aTo0O2k6MjtpOjI7aTozO2k6MTt9fQ=='));
}
elseif (!$omfg && !isset($_REQUEST['time']))
{
$context['sub_template'] = 'hms';
$context['clockicons'] = unserialize(base64_decode('YTozOntzOjE6ImgiO2E6NTp7aTowO2k6MTY7aToxO2k6ODtpOjI7aTo0O2k6MztpOjI7aTo0O2k6MTt9czoxOiJtIjthOjY6e2k6MDtpOjMyO2k6MTtpOjE2O2k6MjtpOjg7aTozO2k6NDtpOjQ7aToyO2k6NTtpOjE7fXM6MToicyI7YTo2OntpOjA7aTozMjtpOjE7aToxNjtpOjI7aTo4O2k6MztpOjQ7aTo0O2k6MjtpOjU7aToxO319'));
}
elseif ($omfg)
{
$context['sub_template'] = 'omfg';
$context['clockicons'] = unserialize(base64_decode('YTo2OntzOjQ6InllYXIiO2E6Nzp7aTowO2k6NjQ7aToxO2k6MzI7aToyO2k6MTY7aTozO2k6ODtpOjQ7aTo0O2k6NTtpOjI7aTo2O2k6MTt9czo1OiJtb250aCI7YTo0OntpOjA7aTo4O2k6MTtpOjQ7aToyO2k6MjtpOjM7aToxO31zOjM6ImRheSI7YTo1OntpOjA7aToxNjtpOjE7aTo4O2k6MjtpOjQ7aTozO2k6MjtpOjQ7aToxO31zOjQ6ImhvdXIiO2E6NTp7aTowO2k6MTY7aToxO2k6ODtpOjI7aTo0O2k6MztpOjI7aTo0O2k6MTt9czozOiJtaW4iO2E6Njp7aTowO2k6MzI7aToxO2k6MTY7aToyO2k6ODtpOjM7aTo0O2k6NDtpOjI7aTo1O2k6MTt9czozOiJzZWMiO2E6Njp7aTowO2k6MzI7aToxO2k6MTY7aToyO2k6ODtpOjM7aTo0O2k6NDtpOjI7aTo1O2k6MTt9fQ=='));
}
elseif (isset($_REQUEST['time']))
{
$context['sub_template'] = 'thetime';
$time = getdate($_REQUEST['time'] == 'now' ? time() : (int) $_REQUEST['time']);
$context['clockicons'] = array(
'year' => array(
64 => false,
32 => false,
16 => false,
8 => false,
4 => false,
2 => false,
1 => false
),
'month' => array(
8 => false,
4 => false,
2 => false,
1 => false
),
'day' => array(
16 => false,
4 => false,
8 => false,
2 => false,
1 => false
),
'hour' => array(
32 => false,
16 => false,
8 => false,
4 => false,
2 => false,
1 => false
),
'min' => array(
32 => false,
16 => false,
8 => false,
4 => false,
2 => false,
1 => false
),
'sec' => array(
32 => false,
16 => false,
8 => false,
4 => false,
2 => false,
1 => false
),
);
$year = $time['year'] % 100;
$month = $time['mon'];
$day = $time['mday'];
$hour = $time['hours'];
$min = $time['minutes'];
$sec = $time['seconds'];
foreach ($context['clockicons'] as $t => $vs)
foreach ($vs as $v => $dumb)
{
if ($$t >= $v)
{
$$t -= $v;
$context['clockicons'][$t][$v] = true;
}
}
}
}
?>

View File

@ -1,88 +0,0 @@
<?php
if (!defined('SMF'))
die('Hacking attempt...');
function Chat() {
global $context, $settings, $user_info, $txt, $modSettings, $smcFunc;
$context['page_title'] = $modSettings['irc_page_title'];
$context['linktree'][] = array(
'url' => $scripturl . '?action=chat',
'name' => $modSettings['irc_page_title'],
);
if (empty($context['smileys']))
{
$context['smileys'] = array(
'postform' => array(),
'popup' => array(),
);
if (empty($modSettings['smiley_enable']) && $user_info['smiley_set'] != 'none')
$context['smileys']['postform'][] = array(
'smileys' => array(
array('code' => ':)', 'filename' => 'smiley.gif', 'description' => $txt['icon_smiley']),
array('code' => ';)', 'filename' => 'wink.gif', 'description' => $txt['icon_wink']),
array('code' => ':D', 'filename' => 'cheesy.gif', 'description' => $txt['icon_cheesy']),
array('code' => ';D', 'filename' => 'grin.gif', 'description' => $txt['icon_grin']),
array('code' => '>:(', 'filename' => 'angry.gif', 'description' => $txt['icon_angry']),
array('code' => ':(', 'filename' => 'sad.gif', 'description' => $txt['icon_sad']),
array('code' => ':o', 'filename' => 'shocked.gif', 'description' => $txt['icon_shocked']),
array('code' => '8)', 'filename' => 'cool.gif', 'description' => $txt['icon_cool']),
array('code' => '???', 'filename' => 'huh.gif', 'description' => $txt['icon_huh']),
array('code' => '::)', 'filename' => 'rolleyes.gif', 'description' => $txt['icon_rolleyes']),
array('code' => ':P', 'filename' => 'tongue.gif', 'description' => $txt['icon_tongue']),
array('code' => ':-[', 'filename' => 'embarrassed.gif', 'description' => $txt['icon_embarrassed']),
array('code' => ':-X', 'filename' => 'lipsrsealed.gif', 'description' => $txt['icon_lips']),
array('code' => ':-\\', 'filename' => 'undecided.gif', 'description' => $txt['icon_undecided']),
array('code' => ':-*', 'filename' => 'kiss.gif', 'description' => $txt['icon_kiss']),
array('code' => ':\'(', 'filename' => 'cry.gif', 'description' => $txt['icon_cry'])
),
'last' => true,
);
elseif ($user_info['smiley_set'] != 'none')
{
if (($temp = cache_get_data('posting_smileys', 480)) == null)
{
$request = $smcFunc['db_query']('', '
SELECT code, filename, description, smiley_row, hidden
FROM {db_prefix}smileys
WHERE hidden IN (0, 2)
ORDER BY smiley_row, smiley_order',
array(
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
{
$row['filename'] = htmlspecialchars($row['filename']);
$row['description'] = htmlspecialchars($row['description']);
$context['smileys'][empty($row['hidden']) ? 'postform' : 'popup'][$row['smiley_row']]['smileys'][] = $row;
}
$smcFunc['db_free_result']($request);
cache_put_data('posting_smileys', $context['smileys'], 480);
}
else
$context['smileys'] = $temp;
}
// Clean house... add slashes to the code for javascript.
foreach (array_keys($context['smileys']) as $location)
{
foreach ($context['smileys'][$location] as $j => $row)
{
$n = count($context['smileys'][$location][$j]['smileys']);
for ($i = 0; $i < $n; $i++)
{
$context['smileys'][$location][$j]['smileys'][$i]['code'] = addslashes($context['smileys'][$location][$j]['smileys'][$i]['code']);
$context['smileys'][$location][$j]['smileys'][$i]['js_description'] = addslashes($context['smileys'][$location][$j]['smileys'][$i]['description']);
}
$context['smileys'][$location][$j]['smileys'][$n - 1]['last'] = true;
}
if (!empty($context['smileys'][$location]))
$context['smileys'][$location][count($context['smileys'][$location]) - 1]['last'] = true;
}
}
loadTemplate('Chat');
}
?>

View File

@ -1,715 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0
*/
/* Gif Util copyright 2003 by Yamasoft (S/C). All rights reserved.
Do not remove this portion of the header, or use these functions except
from the original author. To get it, please navigate to:
http://www.yamasoft.com/php-gif.zip
*/
if (!defined('SMF'))
die('Hacking attempt...');
/* Classes used for reading gif files (in case PHP's GD doesn't provide the
proper gif-functions).
*/
class gif_lzw_compression
{
public $MAX_LZW_BITS;
public $Fresh, $CodeSize, $SetCodeSize, $MaxCode, $MaxCodeSize, $FirstCode, $OldCode;
public $ClearCode, $EndCode, $Next, $Vals, $Stack, $sp, $Buf, $CurBit, $LastBit, $Done, $LastByte;
public function __construct()
{
$this->MAX_LZW_BITS = 12;
unset($this->Next, $this->Vals, $this->Stack, $this->Buf);
$this->Next = range(0, (1 << $this->MAX_LZW_BITS) - 1);
$this->Vals = range(0, (1 << $this->MAX_LZW_BITS) - 1);
$this->Stack = range(0, (1 << ($this->MAX_LZW_BITS + 1)) - 1);
$this->Buf = range(0, 279);
}
public function decompress($data, &$datLen)
{
$stLen = strlen($data);
$datLen = 0;
$ret = '';
$this->LZWCommand($data, true);
while (($iIndex = $this->LZWCommand($data, false)) >= 0)
$ret .= chr($iIndex);
$datLen = $stLen - strlen($data);
if ($iIndex != -2)
return false;
return $ret;
}
public function LZWCommand(&$data, $bInit)
{
if ($bInit)
{
$this->SetCodeSize = ord($data[0]);
$data = substr($data, 1);
$this->CodeSize = $this->SetCodeSize + 1;
$this->ClearCode = 1 << $this->SetCodeSize;
$this->EndCode = $this->ClearCode + 1;
$this->MaxCode = $this->ClearCode + 2;
$this->MaxCodeSize = $this->ClearCode << 1;
$this->GetCode($data, $bInit);
$this->Fresh = 1;
for ($i = 0; $i < $this->ClearCode; $i++)
{
$this->Next[$i] = 0;
$this->Vals[$i] = $i;
}
for (; $i < (1 << $this->MAX_LZW_BITS); $i++)
{
$this->Next[$i] = 0;
$this->Vals[$i] = 0;
}
$this->sp = 0;
return 1;
}
if ($this->Fresh)
{
$this->Fresh = 0;
do
{
$this->FirstCode = $this->GetCode($data, $bInit);
$this->OldCode = $this->FirstCode;
}
while ($this->FirstCode == $this->ClearCode);
return $this->FirstCode;
}
if ($this->sp > 0)
{
$this->sp--;
return $this->Stack[$this->sp];
}
while (($Code = $this->GetCode($data, $bInit)) >= 0)
{
if ($Code == $this->ClearCode)
{
for ($i = 0; $i < $this->ClearCode; $i++)
{
$this->Next[$i] = 0;
$this->Vals[$i] = $i;
}
for (; $i < (1 << $this->MAX_LZW_BITS); $i++)
{
$this->Next[$i] = 0;
$this->Vals[$i] = 0;
}
$this->CodeSize = $this->SetCodeSize + 1;
$this->MaxCodeSize = $this->ClearCode << 1;
$this->MaxCode = $this->ClearCode + 2;
$this->sp = 0;
$this->FirstCode = $this->GetCode($data, $bInit);
$this->OldCode = $this->FirstCode;
return $this->FirstCode;
}
if ($Code == $this->EndCode)
return -2;
$InCode = $Code;
if ($Code >= $this->MaxCode)
{
$this->Stack[$this->sp] = $this->FirstCode;
$this->sp++;
$Code = $this->OldCode;
}
while ($Code >= $this->ClearCode)
{
$this->Stack[$this->sp] = $this->Vals[$Code];
$this->sp++;
if ($Code == $this->Next[$Code]) // Circular table entry, big GIF Error!
return -1;
$Code = $this->Next[$Code];
}
$this->FirstCode = $this->Vals[$Code];
$this->Stack[$this->sp] = $this->FirstCode;
$this->sp++;
if (($Code = $this->MaxCode) < (1 << $this->MAX_LZW_BITS))
{
$this->Next[$Code] = $this->OldCode;
$this->Vals[$Code] = $this->FirstCode;
$this->MaxCode++;
if (($this->MaxCode >= $this->MaxCodeSize) && ($this->MaxCodeSize < (1 << $this->MAX_LZW_BITS)))
{
$this->MaxCodeSize *= 2;
$this->CodeSize++;
}
}
$this->OldCode = $InCode;
if ($this->sp > 0)
{
$this->sp--;
return $this->Stack[$this->sp];
}
}
return $Code;
}
public function GetCode(&$data, $bInit)
{
if ($bInit)
{
$this->CurBit = 0;
$this->LastBit = 0;
$this->Done = 0;
$this->LastByte = 2;
return 1;
}
if (($this->CurBit + $this->CodeSize) >= $this->LastBit)
{
if ($this->Done)
{
// Ran off the end of my bits...
if ($this->CurBit >= $this->LastBit)
return 0;
return -1;
}
$this->Buf[0] = $this->Buf[$this->LastByte - 2];
$this->Buf[1] = $this->Buf[$this->LastByte - 1];
$count = ord($data[0]);
$data = substr($data, 1);
if ($count)
{
for ($i = 0; $i < $count; $i++)
$this->Buf[2 + $i] = ord($data{$i});
$data = substr($data, $count);
}
else
$this->Done = 1;
$this->LastByte = 2 + $count;
$this->CurBit = ($this->CurBit - $this->LastBit) + 16;
$this->LastBit = (2 + $count) << 3;
}
$iRet = 0;
for ($i = $this->CurBit, $j = 0; $j < $this->CodeSize; $i++, $j++)
$iRet |= (($this->Buf[intval($i / 8)] & (1 << ($i % 8))) != 0) << $j;
$this->CurBit += $this->CodeSize;
return $iRet;
}
}
class gif_color_table
{
public $m_nColors;
public $m_arColors;
public function __construct()
{
unset($this->m_nColors, $this->m_arColors);
}
public function load($lpData, $num)
{
$this->m_nColors = 0;
$this->m_arColors = array();
for ($i = 0; $i < $num; $i++)
{
$rgb = substr($lpData, $i * 3, 3);
if (strlen($rgb) < 3)
return false;
$this->m_arColors[] = (ord($rgb[2]) << 16) + (ord($rgb[1]) << 8) + ord($rgb[0]);
$this->m_nColors++;
}
return true;
}
public function toString()
{
$ret = '';
for ($i = 0; $i < $this->m_nColors; $i++)
{
$ret .=
chr(($this->m_arColors[$i] & 0x000000FF)) . // R
chr(($this->m_arColors[$i] & 0x0000FF00) >> 8) . // G
chr(($this->m_arColors[$i] & 0x00FF0000) >> 16); // B
}
return $ret;
}
public function colorIndex($rgb)
{
$rgb = intval($rgb) & 0xFFFFFF;
$r1 = ($rgb & 0x0000FF);
$g1 = ($rgb & 0x00FF00) >> 8;
$b1 = ($rgb & 0xFF0000) >> 16;
$idx = -1;
for ($i = 0; $i < $this->m_nColors; $i++)
{
$r2 = ($this->m_arColors[$i] & 0x000000FF);
$g2 = ($this->m_arColors[$i] & 0x0000FF00) >> 8;
$b2 = ($this->m_arColors[$i] & 0x00FF0000) >> 16;
$d = abs($r2 - $r1) + abs($g2 - $g1) + abs($b2 - $b1);
if (($idx == -1) || ($d < $dif))
{
$idx = $i;
$dif = $d;
}
}
return $idx;
}
}
class gif_file_header
{
public $m_lpVer, $m_nWidth, $m_nHeight, $m_bGlobalClr, $m_nColorRes;
public $m_bSorted, $m_nTableSize, $m_nBgColor, $m_nPixelRatio;
public $m_colorTable;
public function __construct()
{
unset($this->m_lpVer, $this->m_nWidth, $this->m_nHeight, $this->m_bGlobalClr, $this->m_nColorRes);
unset($this->m_bSorted, $this->m_nTableSize, $this->m_nBgColor, $this->m_nPixelRatio, $this->m_colorTable);
}
public function load($lpData, &$hdrLen)
{
$hdrLen = 0;
$this->m_lpVer = substr($lpData, 0, 6);
if (($this->m_lpVer != 'GIF87a') && ($this->m_lpVer != 'GIF89a'))
return false;
list ($this->m_nWidth, $this->m_nHeight) = array_values(unpack('v2', substr($lpData, 6, 4)));
if (!$this->m_nWidth || !$this->m_nHeight)
return false;
$b = ord(substr($lpData, 10, 1));
$this->m_bGlobalClr = ($b & 0x80) ? true : false;
$this->m_nColorRes = ($b & 0x70) >> 4;
$this->m_bSorted = ($b & 0x08) ? true : false;
$this->m_nTableSize = 2 << ($b & 0x07);
$this->m_nBgColor = ord(substr($lpData, 11, 1));
$this->m_nPixelRatio = ord(substr($lpData, 12, 1));
$hdrLen = 13;
if ($this->m_bGlobalClr)
{
$this->m_colorTable = new gif_color_table();
if (!$this->m_colorTable->load(substr($lpData, $hdrLen), $this->m_nTableSize))
return false;
$hdrLen += 3 * $this->m_nTableSize;
}
return true;
}
}
class gif_image_header
{
public $m_nLeft, $m_nTop, $m_nWidth, $m_nHeight, $m_bLocalClr;
public $m_bInterlace, $m_bSorted, $m_nTableSize, $m_colorTable;
public function __construct()
{
unset($this->m_nLeft, $this->m_nTop, $this->m_nWidth, $this->m_nHeight, $this->m_bLocalClr);
unset($this->m_bInterlace, $this->m_bSorted, $this->m_nTableSize, $this->m_colorTable);
}
public function load($lpData, &$hdrLen)
{
$hdrLen = 0;
// Get the width/height/etc. from the header.
list ($this->m_nLeft, $this->m_nTop, $this->m_nWidth, $this->m_nHeight) = array_values(unpack('v4', substr($lpData, 0, 8)));
if (!$this->m_nWidth || !$this->m_nHeight)
return false;
$b = ord($lpData[8]);
$this->m_bLocalClr = ($b & 0x80) ? true : false;
$this->m_bInterlace = ($b & 0x40) ? true : false;
$this->m_bSorted = ($b & 0x20) ? true : false;
$this->m_nTableSize = 2 << ($b & 0x07);
$hdrLen = 9;
if ($this->m_bLocalClr)
{
$this->m_colorTable = new gif_color_table();
if (!$this->m_colorTable->load(substr($lpData, $hdrLen), $this->m_nTableSize))
return false;
$hdrLen += 3 * $this->m_nTableSize;
}
return true;
}
}
class gif_image
{
public $m_disp, $m_bUser, $m_bTrans, $m_nDelay, $m_nTrans, $m_lpComm;
public $m_gih, $m_data, $m_lzw;
public function __construct()
{
unset($this->m_disp, $this->m_bUser, $this->m_nDelay, $this->m_nTrans, $this->m_lpComm, $this->m_data);
$this->m_gih = new gif_image_header();
$this->m_lzw = new gif_lzw_compression();
}
public function load($data, &$datLen)
{
$datLen = 0;
while (true)
{
$b = ord($data[0]);
$data = substr($data, 1);
$datLen++;
switch ($b)
{
// Extension...
case 0x21:
$len = 0;
if (!$this->skipExt($data, $len))
return false;
$datLen += $len;
break;
// Image...
case 0x2C:
// Load the header and color table.
$len = 0;
if (!$this->m_gih->load($data, $len))
return false;
$data = substr($data, $len);
$datLen += $len;
// Decompress the data, and ride on home ;).
$len = 0;
if (!($this->m_data = $this->m_lzw->decompress($data, $len)))
return false;
$data = substr($data, $len);
$datLen += $len;
if ($this->m_gih->m_bInterlace)
$this->deInterlace();
return true;
case 0x3B: // EOF
default:
return false;
}
}
return false;
}
public function skipExt(&$data, &$extLen)
{
$extLen = 0;
$b = ord($data[0]);
$data = substr($data, 1);
$extLen++;
switch ($b)
{
// Graphic Control...
case 0xF9:
$b = ord($data[1]);
$this->m_disp = ($b & 0x1C) >> 2;
$this->m_bUser = ($b & 0x02) ? true : false;
$this->m_bTrans = ($b & 0x01) ? true : false;
list ($this->m_nDelay) = array_values(unpack('v', substr($data, 2, 2)));
$this->m_nTrans = ord($data[4]);
break;
// Comment...
case 0xFE:
$this->m_lpComm = substr($data, 1, ord($data[0]));
break;
// Plain text...
case 0x01:
break;
// Application...
case 0xFF:
break;
}
// Skip default as defs may change.
$b = ord($data[0]);
$data = substr($data, 1);
$extLen++;
while ($b > 0)
{
$data = substr($data, $b);
$extLen += $b;
$b = ord($data[0]);
$data = substr($data, 1);
$extLen++;
}
return true;
}
public function deInterlace()
{
$data = $this->m_data;
for ($i = 0; $i < 4; $i++)
{
switch ($i)
{
case 0:
$s = 8;
$y = 0;
break;
case 1:
$s = 8;
$y = 4;
break;
case 2:
$s = 4;
$y = 2;
break;
case 3:
$s = 2;
$y = 1;
break;
}
for (; $y < $this->m_gih->m_nHeight; $y += $s)
{
$lne = substr($this->m_data, 0, $this->m_gih->m_nWidth);
$this->m_data = substr($this->m_data, $this->m_gih->m_nWidth);
$data =
substr($data, 0, $y * $this->m_gih->m_nWidth) .
$lne .
substr($data, ($y + 1) * $this->m_gih->m_nWidth);
}
}
$this->m_data = $data;
}
}
class gif_file
{
public $header, $image, $data, $loaded;
public function __construct()
{
$this->data = '';
$this->loaded = false;
$this->header = new gif_file_header();
$this->image = new gif_image();
}
public function loadFile($filename, $iIndex)
{
if ($iIndex < 0)
return false;
$this->data = @file_get_contents($filename);
if ($this->data === false)
return false;
// Tell the header to load up....
$len = 0;
if (!$this->header->load($this->data, $len))
return false;
$this->data = substr($this->data, $len);
// Keep reading (at least once) so we get to the actual image we're looking for.
for ($j = 0; $j <= $iIndex; $j++)
{
$imgLen = 0;
if (!$this->image->load($this->data, $imgLen))
return false;
$this->data = substr($this->data, $imgLen);
}
$this->loaded = true;
return true;
}
public function get_png_data($background_color)
{
if (!$this->loaded)
return false;
// Prepare the color table.
if ($this->image->m_gih->m_bLocalClr)
{
$colors = $this->image->m_gih->m_nTableSize;
$pal = $this->image->m_gih->m_colorTable->toString();
if ($background_color != -1)
$background_color = $this->image->m_gih->m_colorTable->colorIndex($background_color);
}
elseif ($this->header->m_bGlobalClr)
{
$colors = $this->header->m_nTableSize;
$pal = $this->header->m_colorTable->toString();
if ($background_color != -1)
$background_color = $this->header->m_colorTable->colorIndex($background_color);
}
else
{
$colors = 0;
$background_color = -1;
}
if ($background_color == -1)
$background_color = $this->header->m_nBgColor;
$data = &$this->image->m_data;
$header = &$this->image->m_gih;
$i = 0;
$bmp = '';
// Prepare the bitmap itself.
for ($y = 0; $y < $this->header->m_nHeight; $y++)
{
$bmp .= "\x00";
for ($x = 0; $x < $this->header->m_nWidth; $x++, $i++)
{
// Is this in the proper range? If so, get the specific pixel data...
if ($x >= $header->m_nLeft && $y >= $header->m_nTop && $x < ($header->m_nLeft + $header->m_nWidth) && $y < ($header->m_nTop + $header->m_nHeight))
$bmp .= $data{$i};
// Otherwise, this is background...
else
$bmp .= chr($background_color);
}
}
$bmp = gzcompress($bmp, 9);
// Output the basic signature first of all.
$out = "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A";
// Now, we want the header...
$out .= "\x00\x00\x00\x0D";
$tmp = 'IHDR' . pack('N', (int) $this->header->m_nWidth) . pack('N', (int) $this->header->m_nHeight) . "\x08\x03\x00\x00\x00";
$out .= $tmp . pack('N', smf_crc32($tmp));
// The palette, assuming we have one to speak of...
if ($colors > 0)
{
$out .= pack('N', (int) $colors * 3);
$tmp = 'PLTE' . $pal;
$out .= $tmp . pack('N', smf_crc32($tmp));
}
// Do we have any transparency we want to make available?
if ($this->image->m_bTrans && $colors > 0)
{
$out .= pack('N', (int) $colors);
$tmp = 'tRNS';
// Stick each color on - full transparency or none.
for ($i = 0; $i < $colors; $i++)
$tmp .= $i == $this->image->m_nTrans ? "\x00" : "\xFF";
$out .= $tmp . pack('N', smf_crc32($tmp));
}
// Here's the data itself!
$out .= pack('N', strlen($bmp));
$tmp = 'IDAT' . $bmp;
$out .= $tmp . pack('N', smf_crc32($tmp));
// EOF marker...
$out .= "\x00\x00\x00\x00" . 'IEND' . "\xAE\x42\x60\x82";
return $out;
}
}
// crc32 doesn't work as expected on 64-bit functions - make our own.
// http://www.php.net/crc32#79567
if (!function_exists('smf_crc32'))
{
function smf_crc32($number)
{
$crc = crc32($number);
if ($crc & 0x80000000)
{
$crc ^= 0xffffffff;
$crc += 1;
$crc = -$crc;
}
return $crc;
}
}
?>

File diff suppressed because it is too large Load Diff

View File

@ -1,104 +0,0 @@
<?php
/**********************************************************************************
* CustomAction.php *
***********************************************************************************
* Software Version: 3.0 *
**********************************************************************************/
if (!defined('SMF'))
die('Hacking attempt...');
function ViewCustomAction()
{
global $context, $smcFunc, $db_prefix, $txt;
// So which custom action is this?
$request = $smcFunc['db_query']('', '
SELECT id_action, name, permissions_mode, action_type, header, body
FROM {db_prefix}custom_actions
WHERE url = {string:url}
AND enabled = 1',
array(
'url' => $context['current_action'],
)
);
$context['action'] = $smcFunc['db_fetch_assoc']($request);
$smcFunc['db_free_result']($request);
// By any chance are we in a sub-action?
if (!empty($_REQUEST['sa']))
{
$request = $smcFunc['db_query']('', '
SELECT id_action, name, permissions_mode, action_type, header, body
FROM {db_prefix}custom_actions
WHERE url = {string:url}
AND enabled = 1
AND id_parent = {int:id_parent}',
array(
'id_parent' => $context['action']['id_action'],
'url' => $_REQUEST['sa'],
)
);
if ($smcFunc['db_num_rows']($request) != 0)
{
$sub = $smcFunc['db_fetch_assoc']($request);
$smcFunc['db_free_result']($request);
$context['action']['name'] = $sub['name'];
// Do we have our own permissions?
if ($sub['permissions_mode'] != 2)
{
$context['action']['id_action'] = $sub['id_action'];
$context['action']['permissions_mode'] = $sub['permissions_mode'];
}
$context['action']['action_type'] = $sub['action_type'];
$context['action']['header'] = $sub['header'];
$context['action']['body'] = $sub['body'];
}
}
// Are we even allowed to be here?
if ($context['action']['permissions_mode'] == 1)
{
// Standard message, please.
$txt['cannot_ca_' . $context['action']['id_action']] = '';
isAllowedTo('ca_' . $context['action']['id_action']);
}
// Do this first to allow it to be overwritten by PHP source file code.
$context['page_title'] = $context['action']['name'];
switch ($context['action']['action_type'])
{
// Any HTML headers?
case 0:
$context['html_headers'] .= $context['action']['header'];
break;
// Do we need to parse any BBC?
case 1:
$context['action']['body'] = parse_bbc($context['action']['body']);
break;
// We have some more stuff to do for PHP actions.
case 2:
fixPHP($context['action']['header']);
fixPHP($context['action']['body']);
eval($context['action']['header']);
}
// Get the templates sorted out!
loadTemplate('CustomAction');
$context['sub_template'] = 'view_custom_action';
}
// Get rid of any <? or <?php at the start of code.
function fixPHP(&$code)
{
$code = preg_replace('~^\s*<\?(php)?~', '', $code);
}
?>

View File

@ -1,376 +0,0 @@
<?php
if (!defined('SMF'))
die('Hacking attempt...');
// This function shows the custom forms and submits them.
function CustomForm()
{
global $smcFunc, $context, $txt, $scripturl, $sourcedir, $user_info, $modSettings;
// Do we have a valid form id?
if(isset($_REQUEST['id'])
&& intval($_REQUEST['id']))
{
$form_id = intval($_REQUEST['id']);
// Wait a second... Are you even allowed to use this form?
if(!allowedTo('custom_forms_'.$form_id))
redirectExit("action=form");
// Get the data about the current form.
$request = $smcFunc['db_query']('','
SELECT title, output, subject, id_board, template_function
FROM {db_prefix}cf_forms
WHERE id_form = {int:id}',
array(
'id' => $form_id,
)
);
// Did we get some form data? If not then redirect the user to the form view page.
if(!($form_data = $smcFunc['db_fetch_assoc']($request)))
redirectExit("action=form;");
$output = $form_data['output'];
$subject = $form_data['subject'];
$board = $form_data['id_board'];
$form_title = $form_data['title'];
// Free the db request.
$smcFunc['db_free_result']($request);
// Get a list of the current fields attached to this form.
$request = $smcFunc['db_query']('','
SELECT title, text, type, type_vars
FROM {db_prefix}cf_fields
WHERE id_form = {int:id}
AND title != \'\'
AND text != \'\'
AND type != \'\'
ORDER BY ID_FIELD',
array(
'id' => $form_id,
)
);
$data = array();
// Get all of data from the db query.
while($row = $smcFunc['db_fetch_assoc']($request))
$data[] = $row;
// Free the db request.
$smcFunc['db_free_result']($request);
// Do we have fields attached to this form? If not then redirect the user to the form view page.
if(empty($data))
redirectExit("action=form;");
$fail_submit = false;
// Do we need to submit this form?
if(isset($_GET['submit']))
{
$vars = array();
$replace = array();
$i = -1;
// Check for valid post data from the forms fields.
foreach($data as $field)
{
$i++;
$value = '';
$size = '';
$default = '';
$temp = ($field['type_vars'] != '') ? explode(',', $field['type_vars']) : array();
$type_vars = array();
// Remove whitespace from temp, to avoid unwanted issues.
for($p=0; $p < count($temp); $p++)
$temp[$p] = trim($temp[$p]);
// Go through all of the type_vars to format them correctly.
if(!empty($temp))
foreach($temp as $var)
{
// Check for a size value.
if(substr($var, 0, 5) == 'size=')
$size = intval(substr($var, 5));
// Check for a default value
if(substr($var, 0, 8) == 'default=')
$default = substr($var, 8);
// Add them to the vars list.
if($var != '')
$type_vars[] = $var;
}
$required = in_array('required', $temp);
// Go through each of the possible types of fields.
switch ($field['type'])
{
case 'checkbox':
$value = isset($_REQUEST[$field['title']]) ? $_REQUEST[$field['title']] : false;
// Replace the normal true/false values if we have special type_var values.
if(isset($type_vars[0]) && ($value))
$value = $type_vars[0];
elseif(isset($type_vars[1]) && !($value))
$value = $type_vars[1];
elseif($value)
$value = $txt['yes'];
else
$value = $txt['no'];
break;
case 'selectbox':
// Skip this field, if there are no select values.
if(empty($type_vars))
continue 2;
$value = isset($_REQUEST[$field['title']]) ? $_REQUEST[$field['title']] : '';
// Make sure that the selectbox value is in the array, otherwise stop those dodgy users from passing weird values. ;)
if(!in_array($value, $type_vars))
$value = '';
break;
case 'int':
$value = isset($_REQUEST[$field['title']]) ? intval($_REQUEST[$field['title']]) : '';
// If value is empty then set it to the default.
if(($value == '')
&& !$required)
$value = $default;
// Restrict the length of value if necessary.
if(($size != ''))
$value = substr($value, 0, $size);
break;
case 'float':
$value = isset($_REQUEST[$field['title']]) ? floatval($_REQUEST[$field['title']]) : '';
// If value is empty then set it to the default.
if(($value == '')
&& !$required)
$value = $default;
// Restrict the length of the float value if necessary.
if(($size != ''))
$value = rtrim(substr($value, 0, $size), '.');
break;
case 'radiobox':
// Skip this field, if there are no radio select values.
if(empty($type_vars))
continue 2;
$value = isset($_REQUEST[$field['title']]) ? $_REQUEST[$field['title']] : '';
// Make sure that the radiobox value is in the array, otherwise stop those dodgy users from passing weird values. ;)
if(!in_array($value, $type_vars))
$value = '';
break;
// Do the formating for both large and normal textboxes.
default:
$value = isset($_REQUEST[$field['title']]) ? $_REQUEST[$field['title']] : '';
// If value is empty then set it to the default.
if(($value == '')
&& !$required)
$value = $default;
// Only bother with further formating if there is now some text. - This avoids huge errors with the parse_bbc() function returning all bbc.
if(!($value == ''))
{
// Remove all bbc code if we don't need to parse it.
if(!in_array('parse_bbc', $type_vars))
$value = strip_tags(parse_bbc($value, false), '<br>');
// Restrict the length of value if necessary, can stuff up html, but hey...
if(($size != ''))
$value = substr($value, 0, $size);
}
}
// Do we have an invalid value? Is this field required?
if(($required
&& (($value == '') || ($value == '0'))
&& ($field['type'] != 'checkbox'))
// Failing for selectboxes is far more simple, If there is no valid value, it fails.
|| (($field['type'] == 'selectbox') && ($value == '')))
{
// Do the 'fail form/field' stuff.
$data[$i]['failed'] = true;
$fail_submit = true;
continue;
}
// Add this fields value to the list of variables for the output post.
$vars[] = '/\{'.$field['title'].'\}/';
$replace[] = $value;
// Also add this data back into the data array, just in case we can't actually submit the form.
$data[$i]['value'] = $value;
// Do a small fix for the last line, if this is a checkbox.
if($field['type'] == 'checkbox')
$data[$i]['value'] = isset($_REQUEST[$field['title']]) ? $_REQUEST[$field['title']] : false;
// Do a small fix for the last line, if this is a largetextbox.
if(($field['type'] == 'largetextbox'))
$data[$i]['value'] = isset($_REQUEST[$field['title']]) ? $_REQUEST[$field['title']] : '';
}
// Do we have completly valid field data?
if(!$fail_submit)
{
require_once($sourcedir.'/Subs-Post.php');
// Replace all vars with their correct value, for both the message and the subject.
$output = preg_replace($vars, $replace, $output);
$subject = preg_replace($vars, $replace, $subject);
// Collect all necessary parameters for the creation of the post.
$msgOptions = array(
'id' => 0,
'subject' => $subject,
'body' => $output,
'smileys_enabled' => true,
);
$topicOptions = array(
'id' => 0,
'board' => $board,
'mark_as_read' => true,
);
$posterOptions = array(
'id' => $user_info['id'],
);
// Finally create the post!!! :D
createPost($msgOptions, $topicOptions, $posterOptions);
// Redirect this user as well.
redirectexit('board=' . $board . '.0');
}
}
// Otherwise we shall show the submit form page.
$context['fields'] = array();
// Okay, lets format the field data.
foreach($data as $field)
{
$size = false;
$type_vars = ($field['type_vars'] != '') ? explode(',', $field['type_vars']) : array();
$vars = array();
$required = false;
// Go through all of the type_vars to format them correctly.
if(!empty($type_vars))
foreach($type_vars as $var)
{
// Remove whitespace from vars, to avoid unwanted issues.
$var = trim($var);
// Add them to the vars list, in the correct format for the template.
if($var != '')
$vars[] = $var;
// Check to see if this field is required.
if($var == 'required')
$required = true;
}
// Make sure that we have valid options, if this is a selectbox.
if(($field['type'] == 'selectbox')
&& empty($vars))
continue;
// Make sure that we have valid options, if this is a radiobox.
if(($field['type'] == 'radiobox')
&& empty($vars))
continue;
// Store any previous values for the template to look after.
if(isset($field['value']))
$modSettings[$field['title']] = $field['value'];
// Finally put the data for this field into the $context['field'] array for the 'submit form' template functions.
$context['fields'][$field['title']] = array(
'text' => $field['text'],
'type' => $field['type'],
'data' => $vars,
'value' => isset($field['value']) ? $field['value'] : '',
'required' => $required,
'failed' => isset($field['failed']),
);
}
// Do we have fields data? If not then redirect the user to the form view page.
if(empty($context['fields']))
redirectExit("action=form;");
// Load the language files.
loadLanguage('Modifications');
// Setup and load the necessary template related stuff.
$context['settings_title'] = '<a href="'.$scripturl.'?action=form;">'.((isset($modSettings['CustomForm_view_title']) && ($modSettings['CustomForm_view_title'] != '')) ? $modSettings['CustomForm_view_title'] : $txt['CustomForm_tabheader']) . '</a> : ' . $form_title;
$context['failed_form_submit'] = $fail_submit;
$context['template_function'] = $form_data['template_function'];
$context['post_url'] = $scripturl.'?action=form;id='.$form_id.';submit;';
$context['sub_template'] = 'submit_form';
loadTemplate('CustomForm');
}
// If not then fall to the default view form page, with the list of forms.
else
{
// Wait a second... Are you even allowed to view the form list?
if(!allowedTo('CustomForm_view_perms'))
redirectExit();
// Declare the array of data which we need to pass to the template.
$context['custom_forms_list'] = array();
// Firstly get a list of all the fields from the cf_fields table.
$request = $smcFunc['db_query']('','
SELECT id_form
FROM {db_prefix}cf_fields
WHERE title != \'\'
AND text != \'\'
AND type != \'\''
);
$forms = array();
while($row = $smcFunc['db_fetch_assoc']($request))
$forms[] = $row['id_form'];
$smcFunc['db_free_result']($request);
// Get the data from the cf_forms table.
$request = $smcFunc['db_query']('','
SELECT f.id_form, f.title, b.name, b.id_board
FROM {db_prefix}cf_forms f, {db_prefix}boards b
WHERE b.id_board = f.id_board
AND b.redirect = \'\''
);
// Go through all of the forms and add them to the list.
while($row = $smcFunc['db_fetch_assoc']($request))
{
// Wait. Are you allowed to view/use this form?
if(!allowedTo('custom_forms_'.$row['id_form']))
continue;
// Did we get some fields from this form?
if(!in_array($row['id_form'], $forms))
continue;
// Add this forms data, for the template to show.
$context['custom_forms_list'][] = array(
'id' => $row['id_form'],
'title' => $row['title'],
'id_board' => $row['id_board'],
'board' => $row['name'],
);
}
// Free the db request.
$smcFunc['db_free_result']($request);
// Finally load the necessary template for this action.
$context['sub_template'] = 'FormList';
loadTemplate('CustomForm');
}
// Set the page title, just for lolz! :D
$context['page_title'] = (isset($modSettings['CustomForm_view_title']) && ($modSettings['CustomForm_view_title'] != '')) ? $modSettings['CustomForm_view_title'] : $txt['CustomForm_tabheader'];
}
?>

View File

@ -1,454 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0
*/
if (!defined('SMF'))
die('Hacking attempt...');
/* This file contains rarely used extended database functionality.
void db_extra_init()
- add this file's functions to the $smcFunc array.
resource smf_db_backup_table($table, $backup_table)
- backup $table to $backup_table.
- returns the request handle to the table creation query
string function smf_db_get_version()
- get the version number.
string db_insert_sql(string table_name)
- gets all the necessary INSERTs for the table named table_name.
- goes in 250 row segments.
- returns the query to insert the data back in.
- returns an empty string if the table was empty.
array smf_db_list_tables($db = false, $filter = false)
- lists all tables in the database
- could be filtered according to $filter
- returns an array of table names. (strings)
float smf_db_optimize_table($table)
- optimize a table
- $table - the table to be optimized
- returns how much it was gained
string db_table_sql(string table_name)
- dumps the CREATE for the specified table. (by table_name.)
- returns the CREATE statement.
*/
// Add the file functions to the $smcFunc array.
function db_extra_init()
{
global $smcFunc;
if (!isset($smcFunc['db_backup_table']) || $smcFunc['db_backup_table'] != 'smf_db_backup_table')
$smcFunc += array(
'db_backup_table' => 'smf_db_backup_table',
'db_optimize_table' => 'smf_db_optimize_table',
'db_insert_sql' => 'smf_db_insert_sql',
'db_table_sql' => 'smf_db_table_sql',
'db_list_tables' => 'smf_db_list_tables',
'db_get_version' => 'smf_db_get_version',
);
}
// Backup $table to $backup_table.
function smf_db_backup_table($table, $backup_table)
{
global $smcFunc, $db_prefix;
$table = str_replace('{db_prefix}', $db_prefix, $table);
// First, get rid of the old table.
$smcFunc['db_query']('', '
DROP TABLE IF EXISTS {raw:backup_table}',
array(
'backup_table' => $backup_table,
)
);
// Can we do this the quick way?
$result = $smcFunc['db_query']('', '
CREATE TABLE {raw:backup_table} LIKE {raw:table}',
array(
'backup_table' => $backup_table,
'table' => $table
));
// If this failed, we go old school.
if ($result)
{
$request = $smcFunc['db_query']('', '
INSERT INTO {raw:backup_table}
SELECT *
FROM {raw:table}',
array(
'backup_table' => $backup_table,
'table' => $table
));
// Old school or no school?
if ($request)
return $request;
}
// At this point, the quick method failed.
$result = $smcFunc['db_query']('', '
SHOW CREATE TABLE {raw:table}',
array(
'table' => $table,
)
);
list (, $create) = $smcFunc['db_fetch_row']($result);
$smcFunc['db_free_result']($result);
$create = preg_split('/[\n\r]/', $create);
$auto_inc = '';
// Default engine type.
$engine = 'MyISAM';
$charset = '';
$collate = '';
foreach ($create as $k => $l)
{
// Get the name of the auto_increment column.
if (strpos($l, 'auto_increment'))
$auto_inc = trim($l);
// For the engine type, see if we can work out what it is.
if (strpos($l, 'ENGINE') !== false || strpos($l, 'TYPE') !== false)
{
// Extract the engine type.
preg_match('~(ENGINE|TYPE)=(\w+)(\sDEFAULT)?(\sCHARSET=(\w+))?(\sCOLLATE=(\w+))?~', $l, $match);
if (!empty($match[1]))
$engine = $match[1];
if (!empty($match[2]))
$engine = $match[2];
if (!empty($match[5]))
$charset = $match[5];
if (!empty($match[7]))
$collate = $match[7];
}
// Skip everything but keys...
if (strpos($l, 'KEY') === false)
unset($create[$k]);
}
if (!empty($create))
$create = '(
' . implode('
', $create) . ')';
else
$create = '';
$request = $smcFunc['db_query']('', '
CREATE TABLE {raw:backup_table} {raw:create}
ENGINE={raw:engine}' . (empty($charset) ? '' : ' CHARACTER SET {raw:charset}' . (empty($collate) ? '' : ' COLLATE {raw:collate}')) . '
SELECT *
FROM {raw:table}',
array(
'backup_table' => $backup_table,
'table' => $table,
'create' => $create,
'engine' => $engine,
'charset' => empty($charset) ? '' : $charset,
'collate' => empty($collate) ? '' : $collate,
)
);
if ($auto_inc != '')
{
if (preg_match('~\`(.+?)\`\s~', $auto_inc, $match) != 0 && substr($auto_inc, -1, 1) == ',')
$auto_inc = substr($auto_inc, 0, -1);
$smcFunc['db_query']('', '
ALTER TABLE {raw:backup_table}
CHANGE COLUMN {raw:column_detail} {raw:auto_inc}',
array(
'backup_table' => $backup_table,
'column_detail' => $match[1],
'auto_inc' => $auto_inc,
)
);
}
return $request;
}
// Optimize a table - return data freed!
function smf_db_optimize_table($table)
{
global $smcFunc, $db_name, $db_prefix;
$table = str_replace('{db_prefix}', $db_prefix, $table);
// Get how much overhead there is.
$request = $smcFunc['db_query']('', '
SHOW TABLE STATUS LIKE {string:table_name}',
array(
'table_name' => str_replace('_', '\_', $table),
)
);
$row = $smcFunc['db_fetch_assoc']($request);
$smcFunc['db_free_result']($request);
$data_before = isset($row['Data_free']) ? $row['Data_free'] : 0;
$request = $smcFunc['db_query']('', '
OPTIMIZE TABLE `{raw:table}`',
array(
'table' => $table,
)
);
if (!$request)
return -1;
// How much left?
$request = $smcFunc['db_query']('', '
SHOW TABLE STATUS LIKE {string:table}',
array(
'table' => str_replace('_', '\_', $table),
)
);
$row = $smcFunc['db_fetch_assoc']($request);
$smcFunc['db_free_result']($request);
$total_change = isset($row['Data_free']) && $data_before > $row['Data_free'] ? $data_before / 1024 : 0;
return $total_change;
}
// List all the tables in the database.
function smf_db_list_tables($db = false, $filter = false)
{
global $db_name, $smcFunc;
$db = $db == false ? $db_name : $db;
$db = trim($db);
$filter = $filter == false ? '' : ' LIKE \'' . $filter . '\'';
$request = $smcFunc['db_query']('', '
SHOW TABLES
FROM `{raw:db}`
{raw:filter}',
array(
'db' => $db[0] == '`' ? strtr($db, array('`' => '')) : $db,
'filter' => $filter,
)
);
$tables = array();
while ($row = $smcFunc['db_fetch_row']($request))
$tables[] = $row[0];
$smcFunc['db_free_result']($request);
return $tables;
}
// Get the content (INSERTs) for a table.
function smf_db_insert_sql($tableName)
{
global $smcFunc, $db_prefix;
$tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
// This will be handy...
$crlf = "\r\n";
// Get everything from the table.
$result = $smcFunc['db_query']('', '
SELECT /*!40001 SQL_NO_CACHE */ *
FROM `{raw:table}`',
array(
'table' => $tableName,
)
);
// The number of rows, just for record keeping and breaking INSERTs up.
$num_rows = $smcFunc['db_num_rows']($result);
$current_row = 0;
if ($num_rows == 0)
return '';
$fields = array_keys($smcFunc['db_fetch_assoc']($result));
$smcFunc['db_data_seek']($result, 0);
// Start it off with the basic INSERT INTO.
$data = 'INSERT INTO `' . $tableName . '`' . $crlf . "\t" . '(`' . implode('`, `', $fields) . '`)' . $crlf . 'VALUES ';
// Loop through each row.
while ($row = $smcFunc['db_fetch_row']($result))
{
$current_row++;
// Get the fields in this row...
$field_list = array();
for ($j = 0; $j < $smcFunc['db_num_fields']($result); $j++)
{
// Try to figure out the type of each field. (NULL, number, or 'string'.)
if (!isset($row[$j]))
$field_list[] = 'NULL';
elseif (is_numeric($row[$j]) && (int) $row[$j] == $row[$j])
$field_list[] = $row[$j];
else
$field_list[] = '\'' . $smcFunc['db_escape_string']($row[$j]) . '\'';
}
// 'Insert' the data.
$data .= '(' . implode(', ', $field_list) . ')';
// All done!
if ($current_row == $num_rows)
$data .= ';' . $crlf;
// Start a new INSERT statement after every 250....
elseif ($current_row > 249 && $current_row % 250 == 0)
$data .= ';' . $crlf . 'INSERT INTO `' . $tableName . '`' . $crlf . "\t" . '(`' . implode('`, `', $fields) . '`)' . $crlf . 'VALUES ';
// Otherwise, go to the next line.
else
$data .= ',' . $crlf . "\t";
}
$smcFunc['db_free_result']($result);
// Return an empty string if there were no rows.
return $num_rows == 0 ? '' : $data;
}
// Get the schema (CREATE) for a table.
function smf_db_table_sql($tableName)
{
global $smcFunc, $db_prefix;
$tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
// This will be needed...
$crlf = "\r\n";
// Drop it if it exists.
$schema_create = 'DROP TABLE IF EXISTS `' . $tableName . '`;' . $crlf . $crlf;
// Start the create table...
$schema_create .= 'CREATE TABLE `' . $tableName . '` (' . $crlf;
// Find all the fields.
$result = $smcFunc['db_query']('', '
SHOW FIELDS
FROM `{raw:table}`',
array(
'table' => $tableName,
)
);
while ($row = $smcFunc['db_fetch_assoc']($result))
{
// Make the CREATE for this column.
$schema_create .= ' `' . $row['Field'] . '` ' . $row['Type'] . ($row['Null'] != 'YES' ? ' NOT NULL' : '');
// Add a default...?
if (!empty($row['Default']) || $row['Null'] !== 'YES')
{
// Make a special case of auto-timestamp.
if ($row['Default'] == 'CURRENT_TIMESTAMP')
$schema_create .= ' /*!40102 NOT NULL default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP */';
// Text shouldn't have a default.
elseif ($row['Default'] !== null)
{
// If this field is numeric the default needs no escaping.
$type = strtolower($row['Type']);
$isNumericColumn = strpos($type, 'int') !== false || strpos($type, 'bool') !== false || strpos($type, 'bit') !== false || strpos($type, 'float') !== false || strpos($type, 'double') !== false || strpos($type, 'decimal') !== false;
$schema_create .= ' default ' . ($isNumericColumn ? $row['Default'] : '\'' . $smcFunc['db_escape_string']($row['Default']) . '\'');
}
}
// And now any extra information. (such as auto_increment.)
$schema_create .= ($row['Extra'] != '' ? ' ' . $row['Extra'] : '') . ',' . $crlf;
}
$smcFunc['db_free_result']($result);
// Take off the last comma.
$schema_create = substr($schema_create, 0, -strlen($crlf) - 1);
// Find the keys.
$result = $smcFunc['db_query']('', '
SHOW KEYS
FROM `{raw:table}`',
array(
'table' => $tableName,
)
);
$indexes = array();
while ($row = $smcFunc['db_fetch_assoc']($result))
{
// IS this a primary key, unique index, or regular index?
$row['Key_name'] = $row['Key_name'] == 'PRIMARY' ? 'PRIMARY KEY' : (empty($row['Non_unique']) ? 'UNIQUE ' : ($row['Comment'] == 'FULLTEXT' || (isset($row['Index_type']) && $row['Index_type'] == 'FULLTEXT') ? 'FULLTEXT ' : 'KEY ')) . '`' . $row['Key_name'] . '`';
// Is this the first column in the index?
if (empty($indexes[$row['Key_name']]))
$indexes[$row['Key_name']] = array();
// A sub part, like only indexing 15 characters of a varchar.
if (!empty($row['Sub_part']))
$indexes[$row['Key_name']][$row['Seq_in_index']] = '`' . $row['Column_name'] . '`(' . $row['Sub_part'] . ')';
else
$indexes[$row['Key_name']][$row['Seq_in_index']] = '`' . $row['Column_name'] . '`';
}
$smcFunc['db_free_result']($result);
// Build the CREATEs for the keys.
foreach ($indexes as $keyname => $columns)
{
// Ensure the columns are in proper order.
ksort($columns);
$schema_create .= ',' . $crlf . ' ' . $keyname . ' (' . implode($columns, ', ') . ')';
}
// Now just get the comment and type... (MyISAM, etc.)
$result = $smcFunc['db_query']('', '
SHOW TABLE STATUS
LIKE {string:table}',
array(
'table' => strtr($tableName, array('_' => '\\_', '%' => '\\%')),
)
);
$row = $smcFunc['db_fetch_assoc']($result);
$smcFunc['db_free_result']($result);
// Probably MyISAM.... and it might have a comment.
$schema_create .= $crlf . ') ENGINE=' . (isset($row['Type']) ? $row['Type'] : $row['Engine']) . ($row['Comment'] != '' ? ' COMMENT="' . $row['Comment'] . '"' : '');
return $schema_create;
}
// Get the version number.
function smf_db_get_version()
{
global $smcFunc;
$request = $smcFunc['db_query']('', '
SELECT VERSION()',
array(
)
);
list ($ver) = $smcFunc['db_fetch_row']($request);
$smcFunc['db_free_result']($request);
return $ver;
}
?>

View File

@ -1,328 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0
*/
if (!defined('SMF'))
die('Hacking attempt...');
/* This file contains rarely used extended database functionality.
void db_extra_init()
- add this file's functions to the $smcFunc array.
resource smf_db_backup_table($table, $backup_table)
- backup $table to $backup_table.
- returns the request handle to the table creation query
string function smf_db_get_version()
- get the version number.
string db_insert_sql(string table_name)
- gets all the necessary INSERTs for the table named table_name.
- goes in 250 row segments.
- returns the query to insert the data back in.
- returns an empty string if the table was empty.
array smf_db_list_tables($db = false, $filter = false)
- lists all tables in the database
- could be filtered according to $filter
- returns an array of table names. (strings)
float smf_db_optimize_table($table)
- optimize a table
- $table - the table to be optimized
- returns how much it was gained
string db_table_sql(string table_name)
- dumps the CREATE for the specified table. (by table_name.)
- returns the CREATE statement.
*/
// Add the file functions to the $smcFunc array.
function db_extra_init()
{
global $smcFunc;
if (!isset($smcFunc['db_backup_table']) || $smcFunc['db_backup_table'] != 'smf_db_backup_table')
$smcFunc += array(
'db_backup_table' => 'smf_db_backup_table',
'db_optimize_table' => 'smf_db_optimize_table',
'db_insert_sql' => 'smf_db_insert_sql',
'db_table_sql' => 'smf_db_table_sql',
'db_list_tables' => 'smf_db_list_tables',
'db_get_version' => 'smf_db_get_version',
);
}
// Backup $table to $backup_table.
function smf_db_backup_table($table, $backup_table)
{
global $smcFunc, $db_prefix;
$table = str_replace('{db_prefix}', $db_prefix, $table);
// Do we need to drop it first?
$tables = smf_db_list_tables(false, $backup_table);
if (!empty($tables))
$smcFunc['db_query']('', '
DROP TABLE {raw:backup_table}',
array(
'backup_table' => $backup_table,
)
);
//!!! Should we create backups of sequences as well?
$smcFunc['db_query']('', '
CREATE TABLE {raw:backup_table}
(
LIKE {raw:table}
INCLUDING DEFAULTS
)',
array(
'backup_table' => $backup_table,
'table' => $table,
)
);
$smcFunc['db_query']('', '
INSERT INTO {raw:backup_table}
SELECT * FROM {raw:table}',
array(
'backup_table' => $backup_table,
'table' => $table,
)
);
}
// Optimize a table - return data freed!
function smf_db_optimize_table($table)
{
global $smcFunc, $db_prefix;
$table = str_replace('{db_prefix}', $db_prefix, $table);
$request = $smcFunc['db_query']('', '
VACUUM ANALYZE {raw:table}',
array(
'table' => $table,
)
);
if (!$request)
return -1;
$row = $smcFunc['db_fetch_assoc']($request);
$smcFunc['db_free_result']($request);
if (isset($row['Data_free']))
return $row['Data_free'] / 1024;
else
return 0;
}
// List all the tables in the database.
function smf_db_list_tables($db = false, $filter = false)
{
global $smcFunc;
$request = $smcFunc['db_query']('', '
SELECT tablename
FROM pg_tables
WHERE schemaname = {string:schema_public}' . ($filter == false ? '' : '
AND tablename LIKE {string:filter}') . '
ORDER BY tablename',
array(
'schema_public' => 'public',
'filter' => $filter,
)
);
$tables = array();
while ($row = $smcFunc['db_fetch_row']($request))
$tables[] = $row[0];
$smcFunc['db_free_result']($request);
return $tables;
}
// Get the content (INSERTs) for a table.
function smf_db_insert_sql($tableName)
{
global $smcFunc, $db_prefix;
$tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
// This will be handy...
$crlf = "\r\n";
// Get everything from the table.
$result = $smcFunc['db_query']('', '
SELECT *
FROM {raw:table}',
array(
'table' => $tableName,
)
);
// The number of rows, just for record keeping and breaking INSERTs up.
$num_rows = $smcFunc['db_num_rows']($result);
if ($num_rows == 0)
return '';
$fields = array_keys($smcFunc['db_fetch_assoc']($result));
$smcFunc['db_data_seek']($result, 0);
// Start it off with the basic INSERT INTO.
$data = '';
$insert_msg = $crlf . 'INSERT INTO ' . $tableName . $crlf . "\t" . '(' . implode(', ', $fields) . ')' . $crlf . 'VALUES ' . $crlf . "\t";
// Loop through each row.
while ($row = $smcFunc['db_fetch_row']($result))
{
// Get the fields in this row...
$field_list = array();
for ($j = 0; $j < $smcFunc['db_num_fields']($result); $j++)
{
// Try to figure out the type of each field. (NULL, number, or 'string'.)
if (!isset($row[$j]))
$field_list[] = 'NULL';
elseif (is_numeric($row[$j]) && (int) $row[$j] == $row[$j])
$field_list[] = $row[$j];
else
$field_list[] = '\'' . $smcFunc['db_escape_string']($row[$j]) . '\'';
}
// 'Insert' the data.
$data .= $insert_msg . '(' . implode(', ', $field_list) . ');';
}
$smcFunc['db_free_result']($result);
// Return an empty string if there were no rows.
return $num_rows == 0 ? '' : $data;
}
// Get the schema (CREATE) for a table.
function smf_db_table_sql($tableName)
{
global $smcFunc, $db_prefix;
$tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
// This will be needed...
$crlf = "\r\n";
// Start the create table...
$schema_create = 'CREATE TABLE ' . $tableName . ' (' . $crlf;
$index_create = '';
$seq_create = '';
// Find all the fields.
$result = $smcFunc['db_query']('', '
SELECT column_name, column_default, is_nullable, data_type, character_maximum_length
FROM information_schema.columns
WHERE table_name = {string:table}
ORDER BY ordinal_position',
array(
'table' => $tableName,
)
);
while ($row = $smcFunc['db_fetch_assoc']($result))
{
if ($row['data_type'] == 'character varying')
$row['data_type'] = 'varchar';
elseif ($row['data_type'] == 'character')
$row['data_type'] = 'char';
if ($row['character_maximum_length'])
$row['data_type'] .= '(' . $row['character_maximum_length'] . ')';
// Make the CREATE for this column.
$schema_create .= ' "' . $row['column_name'] . '" ' . $row['data_type'] . ($row['is_nullable'] != 'YES' ? ' NOT NULL' : '');
// Add a default...?
if (trim($row['column_default']) != '')
{
$schema_create .= ' default ' . $row['column_default'] . '';
// Auto increment?
if (preg_match('~nextval\(\'(.+?)\'(.+?)*\)~i', $row['column_default'], $matches) != 0)
{
// Get to find the next variable first!
$count_req = $smcFunc['db_query']('', '
SELECT MAX("{raw:column}")
FROM {raw:table}',
array(
'column' => $row['column_name'],
'table' => $tableName,
)
);
list ($max_ind) = $smcFunc['db_fetch_row']($count_req);
$smcFunc['db_free_result']($count_req);
// Get the right bloody start!
$seq_create .= 'CREATE SEQUENCE ' . $matches[1] . ' START WITH ' . ($max_ind + 1) . ';' . $crlf . $crlf;
}
}
$schema_create .= ',' . $crlf;
}
$smcFunc['db_free_result']($result);
// Take off the last comma.
$schema_create = substr($schema_create, 0, -strlen($crlf) - 1);
$result = $smcFunc['db_query']('', '
SELECT CASE WHEN i.indisprimary THEN 1 ELSE 0 END AS is_primary, pg_get_indexdef(i.indexrelid) AS inddef
FROM pg_class AS c
INNER JOIN pg_index AS i ON (i.indrelid = c.oid)
INNER JOIN pg_class AS c2 ON (c2.oid = i.indexrelid)
WHERE c.relname = {string:table}',
array(
'table' => $tableName,
)
);
$indexes = array();
while ($row = $smcFunc['db_fetch_assoc']($result))
{
if ($row['is_primary'])
{
if (preg_match('~\(([^\)]+?)\)~i', $row['inddef'], $matches) == 0)
continue;
$index_create .= $crlf . 'ALTER TABLE ' . $tableName . ' ADD PRIMARY KEY ("' . $matches[1] . '");';
}
else
$index_create .= $crlf . $row['inddef'] . ';';
}
$smcFunc['db_free_result']($result);
// Finish it off!
$schema_create .= $crlf . ');';
return $seq_create . $schema_create . $index_create;
}
// Get the version number.
function smf_db_get_version()
{
global $smcFunc;
$request = $smcFunc['db_query']('', '
SHOW server_version',
array(
)
);
list ($ver) = $smcFunc['db_fetch_row']($request);
$smcFunc['db_free_result']($request);
return $ver;
}
?>

View File

@ -1,346 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0
*/
if (!defined('SMF'))
die('Hacking attempt...');
/* This file contains rarely used extended database functionality.
void db_extra_init()
- add this file's functions to the $smcFunc array.
resource smf_db_backup_table($table, $backup_table)
- backup $table to $backup_table.
- returns the request handle to the table creation query
string function smf_db_get_version()
- get the version number.
string db_insert_sql(string table_name)
- gets all the necessary INSERTs for the table named table_name.
- goes in 250 row segments.
- returns the query to insert the data back in.
- returns an empty string if the table was empty.
array smf_db_list_tables($db = false, $filter = false)
- lists all tables in the database
- could be filtered according to $filter
- returns an array of table names. (strings)
float smf_db_optimize_table($table)
- optimize a table
- $table - the table to be optimized
- returns how much it was gained
string db_table_sql(string table_name)
- dumps the CREATE for the specified table. (by table_name.)
- returns the CREATE statement.
*/
// Add the file functions to the $smcFunc array.
function db_extra_init()
{
global $smcFunc;
if (!isset($smcFunc['db_backup_table']) || $smcFunc['db_backup_table'] != 'smf_db_backup_table')
$smcFunc += array(
'db_backup_table' => 'smf_db_backup_table',
'db_optimize_table' => 'smf_db_optimize_table',
'db_insert_sql' => 'smf_db_insert_sql',
'db_table_sql' => 'smf_db_table_sql',
'db_list_tables' => 'smf_db_list_tables',
'db_get_backup' => 'smf_db_get_backup',
'db_get_version' => 'smf_db_get_version',
);
}
// Backup $table to $backup_table.
function smf_db_backup_table($table, $backup_table)
{
global $smcFunc, $db_prefix;
$table = str_replace('{db_prefix}', $db_prefix, $table);
$result = $smcFunc['db_query']('', '
SELECT sql
FROM sqlite_master
WHERE type = {string:txttable}
AND name = {string:table}',
array(
'table' => $table,
'txttable' => 'table'
)
);
list ($create) = $smcFunc['db_fetch_row']($result);
$smcFunc['db_free_result']($result);
$create = preg_split('/[\n\r]/', $create);
$auto_inc = '';
// Remove the first line and check to see if the second one contain useless info.
unset($create[0]);
if (trim($create[1]) == '(')
unset($create[1]);
if (trim($create[count($create)]) == ')')
unset($create[count($create)]);
foreach ($create as $k => $l)
{
// Get the name of the auto_increment column.
if (strpos($l, 'primary') || strpos($l, 'PRIMARY'))
$auto_inc = trim($l);
// Skip everything but keys...
if ((strpos($l, 'KEY') !== false && strpos($l, 'PRIMARY KEY') === false) || strpos($l, $table) !== false || strpos(trim($l), 'PRIMARY KEY') === 0)
unset($create[$k]);
}
if (!empty($create))
$create = '(
' . implode('
', $create) . ')';
else
$create = '';
// Is there an extra junk at the end?
if (substr($create, -2, 1) == ',')
$create = substr($create, 0, -2) . ')';
if (substr($create, -2) == '))')
$create = substr($create, 0, -1);
$smcFunc['db_query']('', '
DROP TABLE {raw:backup_table}',
array(
'backup_table' => $backup_table,
'db_error_skip' => true,
)
);
$request = $smcFunc['db_quote']('
CREATE TABLE {raw:backup_table} {raw:create}',
array(
'backup_table' => $backup_table,
'create' => $create,
));
$smcFunc['db_query']('', '
CREATE TABLE {raw:backup_table} {raw:create}',
array(
'backup_table' => $backup_table,
'create' => $create,
));
$request = $smcFunc['db_query']('', '
INSERT INTO {raw:backup_table}
SELECT *
FROM {raw:table}',
array(
'backup_table' => $backup_table,
'table' => $table,
));
return $request;
}
// Optimize a table - return data freed!
function smf_db_optimize_table($table)
{
global $smcFunc, $db_prefix;
$table = str_replace('{db_prefix}', $db_prefix, $table);
$request = $smcFunc['db_query']('', '
VACUUM {raw:table}',
array(
'table' => $table,
)
);
if (!$request)
return -1;
$row = $smcFunc['db_fetch_assoc']($request);
$smcFunc['db_free_result']($request);
// The function returns nothing.
return 0;
}
// List all the tables in the database.
function smf_db_list_tables($db = false, $filter = false)
{
global $smcFunc;
$filter = $filter == false ? '' : ' AND name LIKE \'' . str_replace("\_", "_", $filter) . '\'';
$request = $smcFunc['db_query']('', '
SELECT name
FROM sqlite_master
WHERE type = {string:type}
{raw:filter}
ORDER BY name',
array(
'type' => 'table',
'filter' => $filter,
)
);
$tables = array();
while ($row = $smcFunc['db_fetch_row']($request))
$tables[] = $row[0];
$smcFunc['db_free_result']($request);
return $tables;
}
// Get the content (INSERTs) for a table.
function smf_db_insert_sql($tableName)
{
global $smcFunc, $db_prefix;
$tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
// This will be handy...
$crlf = "\r\n";
// Get everything from the table.
$result = $smcFunc['db_query']('', '
SELECT *
FROM {raw:table}',
array(
'table' => $tableName,
)
);
// The number of rows, just for record keeping and breaking INSERTs up.
$num_rows = $smcFunc['db_num_rows']($result);
if ($num_rows == 0)
return '';
$fields = array_keys($smcFunc['db_fetch_assoc']($result));
// SQLite fetches an array so we need to filter out the numberic index for the columns.
foreach ($fields as $key => $name)
if (is_numeric($name))
unset($fields[$key]);
$smcFunc['db_data_seek']($result, 0);
// Start it off with the basic INSERT INTO.
$data = 'BEGIN TRANSACTION;' . $crlf;
// Loop through each row.
while ($row = $smcFunc['db_fetch_row']($result))
{
// Get the fields in this row...
$field_list = array();
for ($j = 0; $j < $smcFunc['db_num_fields']($result); $j++)
{
// Try to figure out the type of each field. (NULL, number, or 'string'.)
if (!isset($row[$j]))
$field_list[] = 'NULL';
elseif (is_numeric($row[$j]) && (int) $row[$j] == $row[$j])
$field_list[] = $row[$j];
else
$field_list[] = '\'' . $smcFunc['db_escape_string']($row[$j]) . '\'';
}
$data .= 'INSERT INTO ' . $tableName . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $field_list) . ');' . $crlf;
}
$smcFunc['db_free_result']($result);
// Return an empty string if there were no rows.
return $num_rows == 0 ? '' : $data . 'COMMIT;' . $crlf;
}
// Get the schema (CREATE) for a table.
function smf_db_table_sql($tableName)
{
global $smcFunc, $db_prefix;
$tableName = str_replace('{db_prefix}', $db_prefix, $tableName);
// This will be needed...
$crlf = "\r\n";
// Start the create table...
$schema_create = '';
$index_create = '';
// Let's get the create statement directly from SQLite.
$result = $smcFunc['db_query']('', '
SELECT sql
FROM sqlite_master
WHERE type = {string:type}
AND name = {string:table_name}',
array(
'type' => 'table',
'table_name' => $tableName,
)
);
list ($schema_create) = $smcFunc['db_fetch_row']($result);
$smcFunc['db_free_result']($result);
// Now the indexes.
$result = $smcFunc['db_query']('', '
SELECT sql
FROM sqlite_master
WHERE type = {string:type}
AND tbl_name = {string:table_name}',
array(
'type' => 'index',
'table_name' => $tableName,
)
);
$indexes = array();
while ($row = $smcFunc['db_fetch_assoc']($result))
if (trim($row['sql']) != '')
$indexes[] = $row['sql'];
$smcFunc['db_free_result']($result);
$index_create .= implode(';' . $crlf, $indexes);
$schema_create = empty($indexes) ? rtrim($schema_create) : $schema_create . ';' . $crlf . $crlf;
return $schema_create . $index_create;
}
// Get the version number.
function smf_db_get_version()
{
return sqlite_libversion();
}
// Simple return the database - and die!
function smf_db_get_backup()
{
global $db_name;
$db_file = substr($db_name, -3) === '.db' ? $db_name : $db_name . '.db';
// Add more info if zipped...
$ext = '';
if (isset($_REQUEST['compress']) && function_exists('gzencode'))
$ext = '.gz';
// Do the remaining headers.
header('Content-Disposition: attachment; filename="' . $db_file . $ext . '"');
header('Cache-Control: private');
header('Connection: close');
// Literally dump the contents. Try reading the file first.
if (@readfile($db_file) == null)
echo file_get_contents($db_file);
obExit(false);
}
?>

View File

@ -1,582 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0
*/
if (!defined('SMF'))
die('Hacking attempt...');
/* This file contains database functionality specifically designed for packages to utilize.
bool smf_db_create_table(string table_name, array columns, array indexes = array(),
array parameters = array(), string if_exists = 'ignore')
- Can be used to create a table without worrying about schema compatabilities.
- If the table exists will, by default, do nothing.
- Builds table with columns as passed to it - at least one column must be sent.
The columns array should have one sub-array for each column - these sub arrays contain:
+ 'name' = Column name
+ 'type' = Type of column - values from (smallint,mediumint,int,text,varchar,char,tinytext,mediumtext,largetext)
+ 'size' => Size of column (If applicable) - for example 255 for a large varchar, 10 for an int etc. If not
set SMF will pick a size.
+ 'default' = Default value - do not set if no default required.
+ 'null' => Can it be null (true or false) - if not set default will be false.
+ 'auto' => Set to true to make it an auto incrementing column. Set to a numerical value to set
from what it should begin counting.
- Adds indexes as specified within indexes parameter. Each index should be a member of $indexes. Values are:
+ 'name' => Index name (If left empty SMF will generate).
+ 'type' => Type of index. Choose from 'primary', 'unique' or 'index'. If not set will default to 'index'.
+ 'columns' => Array containing columns that form part of key - in the order the index is to be created.
- parameters: (None yet)
- if_exists values:
+ 'ignore' will do nothing if the table exists. (And will return true)
+ 'overwrite' will drop any existing table of the same name.
+ 'error' will return false if the table already exists.
*/
// Add the file functions to the $smcFunc array.
function db_packages_init()
{
global $smcFunc, $reservedTables, $db_package_log, $db_prefix;
if (!isset($smcFunc['db_create_table']) || $smcFunc['db_create_table'] != 'smf_db_create_table')
{
$smcFunc += array(
'db_add_column' => 'smf_db_add_column',
'db_add_index' => 'smf_db_add_index',
'db_calculate_type' => 'smf_db_calculate_type',
'db_change_column' => 'smf_db_change_column',
'db_create_table' => 'smf_db_create_table',
'db_drop_table' => 'smf_db_drop_table',
'db_table_structure' => 'smf_db_table_structure',
'db_list_columns' => 'smf_db_list_columns',
'db_list_indexes' => 'smf_db_list_indexes',
'db_remove_column' => 'smf_db_remove_column',
'db_remove_index' => 'smf_db_remove_index',
);
$db_package_log = array();
}
// We setup an array of SMF tables we can't do auto-remove on - in case a mod writer cocks it up!
$reservedTables = array('admin_info_files', 'approval_queue', 'attachments', 'ban_groups', 'ban_items',
'board_permissions', 'boards', 'calendar', 'calendar_holidays', 'categories', 'collapsed_categories',
'custom_fields', 'group_moderators', 'log_actions', 'log_activity', 'log_banned', 'log_boards',
'log_digest', 'log_errors', 'log_floodcontrol', 'log_group_requests', 'log_karma', 'log_mark_read',
'log_notify', 'log_online', 'log_packages', 'log_polls', 'log_reported', 'log_reported_comments',
'log_scheduled_tasks', 'log_search_messages', 'log_search_results', 'log_search_subjects',
'log_search_topics', 'log_topics', 'mail_queue', 'membergroups', 'members', 'message_icons',
'messages', 'moderators', 'package_servers', 'permission_profiles', 'permissions', 'personal_messages',
'pm_recipients', 'poll_choices', 'polls', 'scheduled_tasks', 'sessions', 'settings', 'smileys',
'themes', 'topics');
foreach ($reservedTables as $k => $table_name)
$reservedTables[$k] = strtolower($db_prefix . $table_name);
// We in turn may need the extra stuff.
db_extend('extra');
}
// Create a table.
function smf_db_create_table($table_name, $columns, $indexes = array(), $parameters = array(), $if_exists = 'ignore', $error = 'fatal')
{
global $reservedTables, $smcFunc, $db_package_log, $db_prefix, $db_character_set;
// Strip out the table name, we might not need it in some cases
$real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
// With or without the database name, the fullname looks like this.
$full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// First - no way do we touch SMF tables.
if (in_array(strtolower($table_name), $reservedTables))
return false;
// Log that we'll want to remove this on uninstall.
$db_package_log[] = array('remove_table', $table_name);
// Slightly easier on MySQL than the others...
$tables = $smcFunc['db_list_tables']();
if (in_array($full_table_name, $tables))
{
// This is a sad day... drop the table? If not, return false (error) by default.
if ($if_exists == 'overwrite')
$smcFunc['db_drop_table']($table_name);
else
return $if_exists == 'ignore';
}
// Righty - let's do the damn thing!
$table_query = 'CREATE TABLE ' . $table_name . "\n" . '(';
foreach ($columns as $column)
{
// Auto increment is easy here!
if (!empty($column['auto']))
{
$default = 'auto_increment';
}
elseif (isset($column['default']) && $column['default'] !== null)
$default = 'default \'' . $smcFunc['db_escape_string']($column['default']) . '\'';
else
$default = '';
// Sort out the size... and stuff...
$column['size'] = isset($column['size']) && is_numeric($column['size']) ? $column['size'] : null;
list ($type, $size) = $smcFunc['db_calculate_type']($column['type'], $column['size']);
// Allow unsigned integers (mysql only)
$unsigned = in_array($type, array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')) && !empty($column['unsigned']) ? 'unsigned ' : '';
if ($size !== null)
$type = $type . '(' . $size . ')';
// Now just put it together!
$table_query .= "\n\t`" .$column['name'] . '` ' . $type . ' ' . (!empty($unsigned) ? $unsigned : '') . (!empty($column['null']) ? '' : 'NOT NULL') . ' ' . $default . ',';
}
// Loop through the indexes next...
foreach ($indexes as $index)
{
$columns = implode(',', $index['columns']);
// Is it the primary?
if (isset($index['type']) && $index['type'] == 'primary')
$table_query .= "\n\t" . 'PRIMARY KEY (' . implode(',', $index['columns']) . '),';
else
{
if (empty($index['name']))
$index['name'] = implode('_', $index['columns']);
$table_query .= "\n\t" . (isset($index['type']) && $index['type'] == 'unique' ? 'UNIQUE' : 'KEY') . ' ' . $index['name'] . ' (' . $columns . '),';
}
}
// No trailing commas!
if (substr($table_query, -1) == ',')
$table_query = substr($table_query, 0, -1);
$table_query .= ') ENGINE=MyISAM';
if (!empty($db_character_set) && $db_character_set == 'utf8')
$table_query .= ' DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci';
// Create the table!
$smcFunc['db_query']('', $table_query,
array(
'security_override' => true,
)
);
}
// Drop a table.
function smf_db_drop_table($table_name, $parameters = array(), $error = 'fatal')
{
global $reservedTables, $smcFunc, $db_prefix;
// After stripping away the database name, this is what's left.
$real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
// Get some aliases.
$full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// God no - dropping one of these = bad.
if (in_array(strtolower($table_name), $reservedTables))
return false;
// Does it exist?
if (in_array($full_table_name, $smcFunc['db_list_tables']()))
{
$query = 'DROP TABLE ' . $table_name;
$smcFunc['db_query']('',
$query,
array(
'security_override' => true,
)
);
return true;
}
// Otherwise do 'nout.
return false;
}
// Add a column.
function smf_db_add_column($table_name, $column_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
{
global $smcFunc, $db_package_log, $txt, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// Log that we will want to uninstall this!
$db_package_log[] = array('remove_column', $table_name, $column_info['name']);
// Does it exist - if so don't add it again!
$columns = $smcFunc['db_list_columns']($table_name, false);
foreach ($columns as $column)
if ($column == $column_info['name'])
{
// If we're going to overwrite then use change column.
if ($if_exists == 'update')
return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
else
return false;
}
// Get the specifics...
$column_info['size'] = isset($column_info['size']) && is_numeric($column_info['size']) ? $column_info['size'] : null;
list ($type, $size) = $smcFunc['db_calculate_type']($column_info['type'], $column_info['size']);
// Allow unsigned integers (mysql only)
$unsigned = in_array($type, array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')) && !empty($column_info['unsigned']) ? 'unsigned ' : '';
if ($size !== null)
$type = $type . '(' . $size . ')';
// Now add the thing!
$query = '
ALTER TABLE ' . $table_name . '
ADD `' . $column_info['name'] . '` ' . $type . ' ' . (!empty($unsigned) ? $unsigned : '') . (empty($column_info['null']) ? 'NOT NULL' : '') . ' ' .
(!isset($column_info['default']) ? '' : 'default \'' . $smcFunc['db_escape_string']($column_info['default']) . '\'') . ' ' .
(empty($column_info['auto']) ? '' : 'auto_increment primary key') . ' ';
$smcFunc['db_query']('', $query,
array(
'security_override' => true,
)
);
return true;
}
// Remove a column.
function smf_db_remove_column($table_name, $column_name, $parameters = array(), $error = 'fatal')
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// Does it exist?
$columns = $smcFunc['db_list_columns']($table_name, true);
foreach ($columns as $column)
if ($column['name'] == $column_name)
{
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
DROP COLUMN ' . $column_name,
array(
'security_override' => true,
)
);
return true;
}
// If here we didn't have to work - joy!
return false;
}
// Change a column.
function smf_db_change_column($table_name, $old_column, $column_info, $parameters = array(), $error = 'fatal')
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// Check it does exist!
$columns = $smcFunc['db_list_columns']($table_name, true);
$old_info = null;
foreach ($columns as $column)
if ($column['name'] == $old_column)
$old_info = $column;
// Nothing?
if ($old_info == null)
return false;
// Get the right bits.
if (!isset($column_info['name']))
$column_info['name'] = $old_column;
if (!isset($column_info['default']))
$column_info['default'] = $old_info['default'];
if (!isset($column_info['null']))
$column_info['null'] = $old_info['null'];
if (!isset($column_info['auto']))
$column_info['auto'] = $old_info['auto'];
if (!isset($column_info['type']))
$column_info['type'] = $old_info['type'];
if (!isset($column_info['size']) || !is_numeric($column_info['size']))
$column_info['size'] = $old_info['size'];
if (!isset($column_info['unsigned']) || !in_array($column_info['type'], array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')))
$column_info['unsigned'] = '';
list ($type, $size) = $smcFunc['db_calculate_type']($column_info['type'], $column_info['size']);
// Allow for unsigned integers (mysql only)
$unsigned = in_array($type, array('int', 'tinyint', 'smallint', 'mediumint', 'bigint')) && !empty($column_info['unsigned']) ? 'unsigned ' : '';
if ($size !== null)
$type = $type . '(' . $size . ')';
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
CHANGE COLUMN `' . $old_column . '` `' . $column_info['name'] . '` ' . $type . ' ' . (!empty($unsigned) ? $unsigned : '') . (empty($column_info['null']) ? 'NOT NULL' : '') . ' ' .
(!isset($column_info['default']) ? '' : 'default \'' . $smcFunc['db_escape_string']($column_info['default']) . '\'') . ' ' .
(empty($column_info['auto']) ? '' : 'auto_increment') . ' ',
array(
'security_override' => true,
)
);
}
// Add an index.
function smf_db_add_index($table_name, $index_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
{
global $smcFunc, $db_package_log, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// No columns = no index.
if (empty($index_info['columns']))
return false;
$columns = implode(',', $index_info['columns']);
// No name - make it up!
if (empty($index_info['name']))
{
// No need for primary.
if (isset($index_info['type']) && $index_info['type'] == 'primary')
$index_info['name'] = '';
else
$index_info['name'] = implode('_', $index_info['columns']);
}
else
$index_info['name'] = $index_info['name'];
// Log that we are going to want to remove this!
$db_package_log[] = array('remove_index', $table_name, $index_info['name']);
// Let's get all our indexes.
$indexes = $smcFunc['db_list_indexes']($table_name, true);
// Do we already have it?
foreach ($indexes as $index)
{
if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary'))
{
// If we want to overwrite simply remove the current one then continue.
if ($if_exists != 'update' || $index['type'] == 'primary')
return false;
else
$smcFunc['db_remove_index']($table_name, $index_info['name']);
}
}
// If we're here we know we don't have the index - so just add it.
if (!empty($index_info['type']) && $index_info['type'] == 'primary')
{
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
ADD PRIMARY KEY (' . $columns . ')',
array(
'security_override' => true,
)
);
}
else
{
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
ADD ' . (isset($index_info['type']) && $index_info['type'] == 'unique' ? 'UNIQUE' : 'INDEX') . ' ' . $index_info['name'] . ' (' . $columns . ')',
array(
'security_override' => true,
)
);
}
}
// Remove an index.
function smf_db_remove_index($table_name, $index_name, $parameters = array(), $error = 'fatal')
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// Better exist!
$indexes = $smcFunc['db_list_indexes']($table_name, true);
foreach ($indexes as $index)
{
// If the name is primary we want the primary key!
if ($index['type'] == 'primary' && $index_name == 'primary')
{
// Dropping primary key?
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
DROP PRIMARY KEY',
array(
'security_override' => true,
)
);
return true;
}
if ($index['name'] == $index_name)
{
// Drop the bugger...
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
DROP INDEX ' . $index_name,
array(
'security_override' => true,
)
);
return true;
}
}
// Not to be found ;(
return false;
}
// Get the schema formatted name for a type.
function smf_db_calculate_type($type_name, $type_size = null, $reverse = false)
{
// MySQL is actually the generic baseline.
return array($type_name, $type_size);
}
// Get table structure.
function smf_db_table_structure($table_name, $parameters = array())
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
return array(
'name' => $table_name,
'columns' => $smcFunc['db_list_columns']($table_name, true),
'indexes' => $smcFunc['db_list_indexes']($table_name, true),
);
}
// Return column information for a table.
function smf_db_list_columns($table_name, $detail = false, $parameters = array())
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
$result = $smcFunc['db_query']('', '
SHOW FIELDS
FROM {raw:table_name}',
array(
'table_name' => substr($table_name, 0, 1) == '`' ? $table_name : '`' . $table_name . '`',
)
);
$columns = array();
while ($row = $smcFunc['db_fetch_assoc']($result))
{
if (!$detail)
{
$columns[] = $row['Field'];
}
else
{
// Is there an auto_increment?
$auto = strpos($row['Extra'], 'auto_increment') !== false ? true : false;
// Can we split out the size?
if (preg_match('~(.+?)\s*\((\d+)\)(?:(?:\s*)?(unsigned))?~i', $row['Type'], $matches) === 1)
{
$type = $matches[1];
$size = $matches[2];
if (!empty($matches[3]) && $matches[3] == 'unsigned')
$unsigned = true;
}
else
{
$type = $row['Type'];
$size = null;
}
$columns[$row['Field']] = array(
'name' => $row['Field'],
'null' => $row['Null'] != 'YES' ? false : true,
'default' => isset($row['Default']) ? $row['Default'] : null,
'type' => $type,
'size' => $size,
'auto' => $auto,
);
if (isset($unsigned))
{
$columns[$row['Field']]['unsigned'] = $unsigned;
unset($unsigned);
}
}
}
$smcFunc['db_free_result']($result);
return $columns;
}
// What about some index information?
function smf_db_list_indexes($table_name, $detail = false, $parameters = array())
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
$result = $smcFunc['db_query']('', '
SHOW KEYS
FROM {raw:table_name}',
array(
'table_name' => substr($table_name, 0, 1) == '`' ? $table_name : '`' . $table_name . '`',
)
);
$indexes = array();
while ($row = $smcFunc['db_fetch_assoc']($result))
{
if (!$detail)
$indexes[] = $row['Key_name'];
else
{
// What is the type?
if ($row['Key_name'] == 'PRIMARY')
$type = 'primary';
elseif (empty($row['Non_unique']))
$type = 'unique';
elseif (isset($row['Index_type']) && $row['Index_type'] == 'FULLTEXT')
$type = 'fulltext';
else
$type = 'index';
// This is the first column we've seen?
if (empty($indexes[$row['Key_name']]))
{
$indexes[$row['Key_name']] = array(
'name' => $row['Key_name'],
'type' => $type,
'columns' => array(),
);
}
// Is it a partial index?
if (!empty($row['Sub_part']))
$indexes[$row['Key_name']]['columns'][] = $row['Column_name'] . '(' . $row['Sub_part'] . ')';
else
$indexes[$row['Key_name']]['columns'][] = $row['Column_name'];
}
}
$smcFunc['db_free_result']($result);
return $indexes;
}
?>

View File

@ -1,746 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0.10
*/
if (!defined('SMF'))
die('Hacking attempt...');
/* This file contains database functionality specifically designed for packages to utilize.
bool smf_db_create_table(string table_name, array columns, array indexes = array(),
array parameters = array(), string if_exists = 'ignore')
- Can be used to create a table without worrying about schema compatabilities.
- If the table exists will, by default, do nothing.
- Builds table with columns as passed to it - at least one column must be sent.
The columns array should have one sub-array for each column - these sub arrays contain:
+ 'name' = Column name
+ 'type' = Type of column - values from (smallint,mediumint,int,text,varchar,char,tinytext,mediumtext,largetext)
+ 'size' => Size of column (If applicable) - for example 255 for a large varchar, 10 for an int etc. If not
set SMF will pick a size.
+ 'default' = Default value - do not set if no default required.
+ 'null' => Can it be null (true or false) - if not set default will be false.
+ 'auto' => Set to true to make it an auto incrementing column. Set to a numerical value to set
from what it should begin counting.
- Adds indexes as specified within indexes parameter. Each index should be a member of $indexes. Values are:
+ 'name' => Index name (If left empty SMF will generate).
+ 'type' => Type of index. Choose from 'primary', 'unique' or 'index'. If not set will default to 'index'.
+ 'columns' => Array containing columns that form part of key - in the order the index is to be created.
- parameters: (None yet)
- if_exists values:
+ 'ignore' will do nothing if the table exists. (And will return true)
+ 'overwrite' will drop any existing table of the same name.
+ 'error' will return false if the table already exists.
*/
// Add the file functions to the $smcFunc array.
function db_packages_init()
{
global $smcFunc, $reservedTables, $db_package_log, $db_prefix;
if (!isset($smcFunc['db_create_table']) || $smcFunc['db_create_table'] != 'smf_db_create_table')
{
$smcFunc += array(
'db_add_column' => 'smf_db_add_column',
'db_add_index' => 'smf_db_add_index',
'db_calculate_type' => 'smf_db_calculate_type',
'db_change_column' => 'smf_db_change_column',
'db_create_table' => 'smf_db_create_table',
'db_drop_table' => 'smf_db_drop_table',
'db_table_structure' => 'smf_db_table_structure',
'db_list_columns' => 'smf_db_list_columns',
'db_list_indexes' => 'smf_db_list_indexes',
'db_remove_column' => 'smf_db_remove_column',
'db_remove_index' => 'smf_db_remove_index',
);
$db_package_log = array();
}
// We setup an array of SMF tables we can't do auto-remove on - in case a mod writer cocks it up!
$reservedTables = array('admin_info_files', 'approval_queue', 'attachments', 'ban_groups', 'ban_items',
'board_permissions', 'boards', 'calendar', 'calendar_holidays', 'categories', 'collapsed_categories',
'custom_fields', 'group_moderators', 'log_actions', 'log_activity', 'log_banned', 'log_boards',
'log_digest', 'log_errors', 'log_floodcontrol', 'log_group_requests', 'log_karma', 'log_mark_read',
'log_notify', 'log_online', 'log_packages', 'log_polls', 'log_reported', 'log_reported_comments',
'log_scheduled_tasks', 'log_search_messages', 'log_search_results', 'log_search_subjects',
'log_search_topics', 'log_topics', 'mail_queue', 'membergroups', 'members', 'message_icons',
'messages', 'moderators', 'package_servers', 'permission_profiles', 'permissions', 'personal_messages',
'pm_recipients', 'poll_choices', 'polls', 'scheduled_tasks', 'sessions', 'settings', 'smileys',
'themes', 'topics');
foreach ($reservedTables as $k => $table_name)
$reservedTables[$k] = strtolower($db_prefix . $table_name);
// We in turn may need the extra stuff.
db_extend('extra');
}
// Create a table.
function smf_db_create_table($table_name, $columns, $indexes = array(), $parameters = array(), $if_exists = 'ignore', $error = 'fatal')
{
global $reservedTables, $smcFunc, $db_package_log, $db_prefix;
// Strip out the table name, we might not need it in some cases
$real_prefix = preg_match('~^("?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
// With or without the database name, the fullname looks like this.
$full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// First - no way do we touch SMF tables.
if (in_array(strtolower($table_name), $reservedTables))
return false;
// Log that we'll want to remove this on uninstall.
$db_package_log[] = array('remove_table', $table_name);
// This... my friends... is a function in a half - let's start by checking if the table exists!
$tables = $smcFunc['db_list_tables']();
if (in_array($full_table_name, $tables))
{
// This is a sad day... drop the table? If not, return false (error) by default.
if ($if_exists == 'overwrite')
$smcFunc['db_drop_table']($table_name);
else
return $if_exists == 'ignore';
}
// If we've got this far - good news - no table exists. We can build our own!
$smcFunc['db_transaction']('begin');
$table_query = 'CREATE TABLE ' . $table_name . "\n" . '(';
foreach ($columns as $column)
{
// If we have an auto increment do it!
if (!empty($column['auto']))
{
$smcFunc['db_query']('', '
CREATE SEQUENCE ' . $table_name . '_seq',
array(
'security_override' => true,
)
);
$default = 'default nextval(\'' . $table_name . '_seq\')';
}
elseif (isset($column['default']) && $column['default'] !== null)
$default = 'default \'' . $smcFunc['db_escape_string']($column['default']) . '\'';
else
$default = '';
// Sort out the size...
$column['size'] = isset($column['size']) && is_numeric($column['size']) ? $column['size'] : null;
list ($type, $size) = $smcFunc['db_calculate_type']($column['type'], $column['size']);
if ($size !== null)
$type = $type . '(' . $size . ')';
// Now just put it together!
$table_query .= "\n\t\"" . $column['name'] . '" ' . $type . ' ' . (!empty($column['null']) ? '' : 'NOT NULL') . ' ' . $default . ',';
}
// Loop through the indexes a sec...
$index_queries = array();
foreach ($indexes as $index)
{
$columns = implode(',', $index['columns']);
// Primary goes in the table...
if (isset($index['type']) && $index['type'] == 'primary')
$table_query .= "\n\t" . 'PRIMARY KEY (' . implode(',', $index['columns']) . '),';
else
{
if (empty($index['name']))
$index['name'] = implode('_', $index['columns']);
$index_queries[] = 'CREATE ' . (isset($index['type']) && $index['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $table_name . '_' . $index['name'] . ' ON ' . $table_name . ' (' . $columns . ')';
}
}
// No trailing commas!
if (substr($table_query, -1) == ',')
$table_query = substr($table_query, 0, -1);
$table_query .= ')';
// Create the table!
$smcFunc['db_query']('', $table_query,
array(
'security_override' => true,
)
);
// And the indexes...
foreach ($index_queries as $query)
$smcFunc['db_query']('', $query,
array(
'security_override' => true,
)
);
// Go, go power rangers!
$smcFunc['db_transaction']('commit');
}
// Drop a table.
function smf_db_drop_table($table_name, $parameters = array(), $error = 'fatal')
{
global $reservedTables, $smcFunc, $db_prefix;
// After stripping away the database name, this is what's left.
$real_prefix = preg_match('~^("?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
// Get some aliases.
$full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// God no - dropping one of these = bad.
if (in_array(strtolower($table_name), $reservedTables))
return false;
// Does it exist?
if (in_array($full_table_name, $smcFunc['db_list_tables']()))
{
// We can then drop the table.
$smcFunc['db_transaction']('begin');
// the table
$table_query = 'DROP TABLE ' . $table_name;
// and the assosciated sequence, if any
$sequence_query = 'DROP SEQUENCE IF EXISTS ' . $table_name . '_seq';
// drop them
$smcFunc['db_query']('',
$table_query,
array(
'security_override' => true,
)
);
$smcFunc['db_query']('',
$sequence_query,
array(
'security_override' => true,
)
);
$smcFunc['db_transaction']('commit');
return true;
}
// Otherwise do 'nout.
return false;
}
// Add a column.
function smf_db_add_column($table_name, $column_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
{
global $smcFunc, $db_package_log, $txt, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// Log that we will want to uninstall this!
$db_package_log[] = array('remove_column', $table_name, $column_info['name']);
// Does it exist - if so don't add it again!
$columns = $smcFunc['db_list_columns']($table_name, false);
foreach ($columns as $column)
if ($column == $column_info['name'])
{
// If we're going to overwrite then use change column.
if ($if_exists == 'update')
return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
else
return false;
}
// Get the specifics...
$column_info['size'] = isset($column_info['size']) && is_numeric($column_info['size']) ? $column_info['size'] : null;
list ($type, $size) = $smcFunc['db_calculate_type']($column_info['type'], $column_info['size']);
if ($size !== null)
$type = $type . '(' . $size . ')';
// Now add the thing!
$query = '
ALTER TABLE ' . $table_name . '
ADD COLUMN ' . $column_info['name'] . ' ' . $type;
$smcFunc['db_query']('', $query,
array(
'security_override' => true,
)
);
// If there's more attributes they need to be done via a change on PostgreSQL.
unset($column_info['type'], $column_info['size']);
if (count($column_info) != 1)
return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
else
return true;
}
// Remove a column.
function smf_db_remove_column($table_name, $column_name, $parameters = array(), $error = 'fatal')
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// Does it exist?
$columns = $smcFunc['db_list_columns']($table_name, true);
foreach ($columns as $column)
if ($column['name'] == $column_name)
{
// If there is an auto we need remove it!
if ($column['auto'])
$smcFunc['db_query']('',
'DROP SEQUENCE ' . $table_name . '_seq',
array(
'security_override' => true,
)
);
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
DROP COLUMN ' . $column_name,
array(
'security_override' => true,
)
);
return true;
}
// If here we didn't have to work - joy!
return false;
}
// Change a column.
function smf_db_change_column($table_name, $old_column, $column_info, $parameters = array(), $error = 'fatal')
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// Check it does exist!
$columns = $smcFunc['db_list_columns']($table_name, true);
$old_info = null;
foreach ($columns as $column)
if ($column['name'] == $old_column)
$old_info = $column;
// Nothing?
if ($old_info == null)
return false;
// Now we check each bit individually and ALTER as required.
if (isset($column_info['name']) && $column_info['name'] != $old_column)
{
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
RENAME COLUMN ' . $old_column . ' TO ' . $column_info['name'],
array(
'security_override' => true,
)
);
}
// Different default?
if (isset($column_info['default']) && $column_info['default'] != $old_info['default'])
{
$action = $column_info['default'] !== null ? 'SET DEFAULT \'' . $smcFunc['db_escape_string']($column_info['default']) . '\'' : 'DROP DEFAULT';
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
ALTER COLUMN ' . $column_info['name'] . ' ' . $action,
array(
'security_override' => true,
)
);
}
// Is it null - or otherwise?
if (isset($column_info['null']) && $column_info['null'] != $old_info['null'])
{
$action = $column_info['null'] ? 'DROP' : 'SET';
$smcFunc['db_transaction']('begin');
if (!$column_info['null'])
{
// We have to set it to something if we are making it NOT NULL.
$setTo = isset($column_info['default']) ? $column_info['default'] : (strpos($old_info['type'], 'int') !== false ? 0 : '');
$smcFunc['db_query']('', '
UPDATE ' . $table_name . '
SET ' . $column_info['name'] . ' = \'' . $setTo . '\'
WHERE ' . $column_info['name'] . ' IS NULL',
array(
'security_override' => true,
)
);
}
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
ALTER COLUMN ' . $column_info['name'] . ' ' . $action . ' NOT NULL',
array(
'security_override' => true,
)
);
$smcFunc['db_transaction']('commit');
}
// What about a change in type?
if (isset($column_info['type']) && ($column_info['type'] != $old_info['type'] || (isset($column_info['size']) && $column_info['size'] != $old_info['size'])))
{
$column_info['size'] = isset($column_info['size']) && is_numeric($column_info['size']) ? $column_info['size'] : null;
list ($type, $size) = $smcFunc['db_calculate_type']($column_info['type'], $column_info['size']);
if ($size !== null)
$type = $type . '(' . $size . ')';
// The alter is a pain.
$smcFunc['db_transaction']('begin');
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
ADD COLUMN ' . $column_info['name'] . '_tempxx ' . $type,
array(
'security_override' => true,
)
);
$smcFunc['db_query']('', '
UPDATE ' . $table_name . '
SET ' . $column_info['name'] . '_tempxx = CAST(' . $column_info['name'] . ' AS ' . $type . ')',
array(
'security_override' => true,
)
);
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
DROP COLUMN ' . $column_info['name'],
array(
'security_override' => true,
)
);
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
RENAME COLUMN ' . $column_info['name'] . '_tempxx TO ' . $column_info['name'],
array(
'security_override' => true,
)
);
$smcFunc['db_transaction']('commit');
}
// Finally - auto increment?!
if (isset($column_info['auto']) && $column_info['auto'] != $old_info['auto'])
{
// Are we removing an old one?
if ($old_info['auto'])
{
// Alter the table first - then drop the sequence.
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
ALTER COLUMN ' . $column_info['name'] . ' SET DEFAULT \'0\'',
array(
'security_override' => true,
)
);
$smcFunc['db_query']('', '
DROP SEQUENCE ' . $table_name . '_seq',
array(
'security_override' => true,
)
);
}
// Otherwise add it!
else
{
$smcFunc['db_query']('', '
CREATE SEQUENCE ' . $table_name . '_seq',
array(
'security_override' => true,
)
);
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
ALTER COLUMN ' . $column_info['name'] . ' SET DEFAULT nextval(\'' . $table_name . '_seq\')',
array(
'security_override' => true,
)
);
}
}
}
// Add an index.
function smf_db_add_index($table_name, $index_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
{
global $smcFunc, $db_package_log, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// No columns = no index.
if (empty($index_info['columns']))
return false;
$columns = implode(',', $index_info['columns']);
// No name - make it up!
if (empty($index_info['name']))
{
// No need for primary.
if (isset($index_info['type']) && $index_info['type'] == 'primary')
$index_info['name'] = '';
else
$index_info['name'] = $table_name . implode('_', $index_info['columns']);
}
else
$index_info['name'] = $table_name . $index_info['name'];
// Log that we are going to want to remove this!
$db_package_log[] = array('remove_index', $table_name, $index_info['name']);
// Let's get all our indexes.
$indexes = $smcFunc['db_list_indexes']($table_name, true);
// Do we already have it?
foreach ($indexes as $index)
{
if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary'))
{
// If we want to overwrite simply remove the current one then continue.
if ($if_exists != 'update' || $index['type'] == 'primary')
return false;
else
$smcFunc['db_remove_index']($table_name, $index_info['name']);
}
}
// If we're here we know we don't have the index - so just add it.
if (!empty($index_info['type']) && $index_info['type'] == 'primary')
{
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
ADD PRIMARY KEY (' . $columns . ')',
array(
'security_override' => true,
)
);
}
else
{
$smcFunc['db_query']('', '
CREATE ' . (isset($index_info['type']) && $index_info['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $index_info['name'] . ' ON ' . $table_name . ' (' . $columns . ')',
array(
'security_override' => true,
)
);
}
}
// Remove an index.
function smf_db_remove_index($table_name, $index_name, $parameters = array(), $error = 'fatal')
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// Better exist!
$indexes = $smcFunc['db_list_indexes']($table_name, true);
if ($index_name != 'primary')
$index_name = $table_name . '_' . $index_name;
foreach ($indexes as $index)
{
// If the name is primary we want the primary key!
if ($index['type'] == 'primary' && $index_name == 'primary')
{
// Dropping primary key is odd...
$smcFunc['db_query']('', '
ALTER TABLE ' . $table_name . '
DROP CONSTRAINT ' . $index['name'],
array(
'security_override' => true,
)
);
return true;
}
if ($index['name'] == $index_name)
{
// Drop the bugger...
$smcFunc['db_query']('', '
DROP INDEX ' . $index_name,
array(
'security_override' => true,
)
);
return true;
}
}
// Not to be found ;(
return false;
}
// Get the schema formatted name for a type.
function smf_db_calculate_type($type_name, $type_size = null, $reverse = false)
{
// Generic => Specific.
if (!$reverse)
{
$types = array(
'varchar' => 'character varying',
'char' => 'character',
'mediumint' => 'int',
'tinyint' => 'smallint',
'tinytext' => 'character varying',
'mediumtext' => 'text',
'largetext' => 'text',
);
}
else
{
$types = array(
'character varying' => 'varchar',
'character' => 'char',
'integer' => 'int',
);
}
// Got it? Change it!
if (isset($types[$type_name]))
{
if ($type_name == 'tinytext')
$type_size = 255;
$type_name = $types[$type_name];
}
// Numbers don't have a size.
if (strpos($type_name, 'int') !== false)
$type_size = null;
return array($type_name, $type_size);
}
// Get table structure.
function smf_db_table_structure($table_name, $parameters = array())
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
return array(
'name' => $table_name,
'columns' => $smcFunc['db_list_columns']($table_name, true),
'indexes' => $smcFunc['db_list_indexes']($table_name, true),
);
}
// Return column information for a table.
function smf_db_list_columns($table_name, $detail = false, $parameters = array())
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
$result = $smcFunc['db_query']('', '
SELECT column_name, column_default, is_nullable, data_type, character_maximum_length
FROM information_schema.columns
WHERE table_name = \'' . $table_name . '\'
ORDER BY ordinal_position',
array(
'security_override' => true,
)
);
$columns = array();
while ($row = $smcFunc['db_fetch_assoc']($result))
{
if (!$detail)
{
$columns[] = $row['column_name'];
}
else
{
$auto = false;
// What is the default?
if (preg_match('~nextval\(\'(.+?)\'(.+?)*\)~i', $row['column_default'], $matches) != 0)
{
$default = null;
$auto = true;
}
elseif (trim($row['column_default']) != '')
$default = strpos($row['column_default'], '::') === false ? $row['column_default'] : substr($row['column_default'], 0, strpos($row['column_default'], '::'));
else
$default = null;
// Make the type generic.
list ($type, $size) = $smcFunc['db_calculate_type']($row['data_type'], $row['character_maximum_length'], true);
$columns[$row['column_name']] = array(
'name' => $row['column_name'],
'null' => $row['is_nullable'] ? true : false,
'default' => $default,
'type' => $type,
'size' => $size,
'auto' => $auto,
);
}
}
$smcFunc['db_free_result']($result);
return $columns;
}
// What about some index information?
function smf_db_list_indexes($table_name, $detail = false, $parameters = array())
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
$result = $smcFunc['db_query']('', '
SELECT CASE WHEN i.indisprimary THEN 1 ELSE 0 END AS is_primary,
CASE WHEN i.indisunique THEN 1 ELSE 0 END AS is_unique,
c2.relname AS name,
pg_get_indexdef(i.indexrelid) AS inddef
FROM pg_class AS c, pg_class AS c2, pg_index AS i
WHERE c.relname = \'' . $table_name . '\'
AND c.oid = i.indrelid
AND i.indexrelid = c2.oid',
array(
'security_override' => true,
)
);
$indexes = array();
while ($row = $smcFunc['db_fetch_assoc']($result))
{
// Try get the columns that make it up.
if (preg_match('~\(([^\)]+?)\)~i', $row['inddef'], $matches) == 0)
continue;
$columns = explode(',', $matches[1]);
if (empty($columns))
continue;
foreach ($columns as $k => $v)
$columns[$k] = trim($v);
// Fix up the name to be consistent cross databases
if (substr($row['name'], -5) == '_pkey' && $row['is_primary'] == 1)
$row['name'] = 'PRIMARY';
else
$row['name'] = str_replace($table_name . '_', '', $row['name']);
if (!$detail)
$indexes[] = $row['name'];
else
{
$indexes[$row['name']] = array(
'name' => $row['name'],
'type' => $row['is_primary'] ? 'primary' : ($row['is_unique'] ? 'unique' : 'index'),
'columns' => $columns,
);
}
}
$smcFunc['db_free_result']($result);
return $indexes;
}
?>

View File

@ -1,736 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0
*/
if (!defined('SMF'))
die('Hacking attempt...');
/* This file contains database functionality specifically designed for packages to utilize.
bool smf_db_create_table(string table_name, array columns, array indexes = array(),
array parameters = array(), string if_exists = 'ignore')
- Can be used to create a table without worrying about schema compatabilities.
- If the table exists will, by default, do nothing.
- Builds table with columns as passed to it - at least one column must be sent.
The columns array should have one sub-array for each column - these sub arrays contain:
+ 'name' = Column name
+ 'type' = Type of column - values from (smallint,mediumint,int,text,varchar,char,tinytext,mediumtext,largetext)
+ 'size' => Size of column (If applicable) - for example 255 for a large varchar, 10 for an int etc. If not
set SMF will pick a size.
+ 'default' = Default value - do not set if no default required.
+ 'null' => Can it be null (true or false) - if not set default will be false.
+ 'auto' => Set to true to make it an auto incrementing column. Set to a numerical value to set
from what it should begin counting.
- Adds indexes as specified within indexes parameter. Each index should be a member of $indexes. Values are:
+ 'name' => Index name (If left empty SMF will generate).
+ 'type' => Type of index. Choose from 'primary', 'unique' or 'index'. If not set will default to 'index'.
+ 'columns' => Array containing columns that form part of key - in the order the index is to be created.
- parameters: (None yet)
- if_exists values:
+ 'ignore' will do nothing if the table exists. (And will return true)
+ 'overwrite' will drop any existing table of the same name.
+ 'error' will return false if the table already exists.
*/
// Add the file functions to the $smcFunc array.
function db_packages_init()
{
global $smcFunc, $reservedTables, $db_package_log, $db_prefix;
if (!isset($smcFunc['db_create_table']) || $smcFunc['db_create_table'] != 'smf_db_create_table')
{
$smcFunc += array(
'db_add_column' => 'smf_db_add_column',
'db_add_index' => 'smf_db_add_index',
'db_alter_table' => 'smf_db_alter_table',
'db_calculate_type' => 'smf_db_calculate_type',
'db_change_column' => 'smf_db_change_column',
'db_create_table' => 'smf_db_create_table',
'db_drop_table' => 'smf_db_drop_table',
'db_table_structure' => 'smf_db_table_structure',
'db_list_columns' => 'smf_db_list_columns',
'db_list_indexes' => 'smf_db_list_indexes',
'db_remove_column' => 'smf_db_remove_column',
'db_remove_index' => 'smf_db_remove_index',
);
$db_package_log = array();
}
// We setup an array of SMF tables we can't do auto-remove on - in case a mod writer cocks it up!
$reservedTables = array('admin_info_files', 'approval_queue', 'attachments', 'ban_groups', 'ban_items',
'board_permissions', 'boards', 'calendar', 'calendar_holidays', 'categories', 'collapsed_categories',
'custom_fields', 'group_moderators', 'log_actions', 'log_activity', 'log_banned', 'log_boards',
'log_digest', 'log_errors', 'log_floodcontrol', 'log_group_requests', 'log_karma', 'log_mark_read',
'log_notify', 'log_online', 'log_packages', 'log_polls', 'log_reported', 'log_reported_comments',
'log_scheduled_tasks', 'log_search_messages', 'log_search_results', 'log_search_subjects',
'log_search_topics', 'log_topics', 'mail_queue', 'membergroups', 'members', 'message_icons',
'messages', 'moderators', 'package_servers', 'permission_profiles', 'permissions', 'personal_messages',
'pm_recipients', 'poll_choices', 'polls', 'scheduled_tasks', 'sessions', 'settings', 'smileys',
'themes', 'topics');
foreach ($reservedTables as $k => $table_name)
$reservedTables[$k] = strtolower($db_prefix . $table_name);
// We in turn may need the extra stuff.
db_extend('extra');
}
// Create a table.
function smf_db_create_table($table_name, $columns, $indexes = array(), $parameters = array(), $if_exists = 'ignore', $error = 'fatal')
{
global $reservedTables, $smcFunc, $db_package_log, $db_prefix;
// With or without the database name, the full name looks like this.
$real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
$full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// First - no way do we touch SMF tables.
// Commented out for now. We need to alter SMF tables in order to use this in the upgrade.
/*
if (in_array(strtolower($table_name), $reservedTables))
return false;
*/
// Log that we'll want to remove this on uninstall.
$db_package_log[] = array('remove_table', $table_name);
// Does this table exist or not?
$tables = $smcFunc['db_list_tables']();
if (in_array($full_table_name, $tables))
{
// This is a sad day... drop the table? If not, return false (error) by default.
if ($if_exists == 'overwrite')
$smcFunc['db_drop_table']($table_name);
else
return $if_exists == 'ignore';
}
// Righty - let's do the damn thing!
$table_query = 'CREATE TABLE ' . $table_name . "\n" . '(';
$done_primary = false;
foreach ($columns as $column)
{
// Auto increment is special
if (!empty($column['auto']))
{
$table_query .= "\n" . $column['name'] . ' integer PRIMARY KEY,';
$done_primary = true;
continue;
}
elseif (isset($column['default']) && $column['default'] !== null)
$default = 'default \'' . $smcFunc['db_escape_string']($column['default']) . '\'';
else
$default = '';
// Sort out the size... and stuff...
$column['size'] = isset($column['size']) && is_numeric($column['size']) ? $column['size'] : null;
list ($type, $size) = $smcFunc['db_calculate_type']($column['type'], $column['size']);
if ($size !== null)
$type = $type . '(' . $size . ')';
// Now just put it together!
$table_query .= "\n\t" . $column['name'] . ' ' . $type . ' ' . (!empty($column['null']) ? '' : 'NOT NULL') . ' ' . $default . ',';
}
// Loop through the indexes next...
$index_queries = array();
foreach ($indexes as $index)
{
$columns = implode(',', $index['columns']);
// Is it the primary?
if (isset($index['type']) && $index['type'] == 'primary')
{
// If we've done the primary via auto_inc, don't do it again!
if (!$done_primary)
$table_query .= "\n\t" . 'PRIMARY KEY (' . implode(',', $index['columns']) . '),';
}
else
{
if (empty($index['name']))
$index['name'] = implode('_', $index['columns']);
$index_queries[] = 'CREATE ' . (isset($index['type']) && $index['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $table_name . '_' . $index['name'] . ' ON ' . $table_name . ' (' . $columns . ')';
}
}
// No trailing commas!
if (substr($table_query, -1) == ',')
$table_query = substr($table_query, 0, -1);
$table_query .= ')';
if (empty($parameters['skip_transaction']))
$smcFunc['db_transaction']('begin');
// Do the table and indexes...
$smcFunc['db_query']('', $table_query,
array(
'security_override' => true,
)
);
foreach ($index_queries as $query)
$smcFunc['db_query']('', $query,
array(
'security_override' => true,
)
);
if (empty($parameters['skip_transaction']))
$smcFunc['db_transaction']('commit');
}
// Drop a table.
function smf_db_drop_table($table_name, $parameters = array(), $error = 'fatal')
{
global $reservedTables, $smcFunc, $db_prefix;
// Strip out the table name, we might not need it in some cases
$real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
$full_table_name = str_replace('{db_prefix}', $real_prefix, $table_name);
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// God no - dropping one of these = bad.
if (in_array(strtolower($table_name), $reservedTables))
return false;
// Does it exist?
if (in_array($full_table_name, $smcFunc['db_list_tables']()))
{
$query = 'DROP TABLE ' . $table_name;
$smcFunc['db_query']('', $query,
array(
'security_override' => true,
)
);
return true;
}
// Otherwise do 'nout.
return false;
}
// Add a column.
function smf_db_add_column($table_name, $column_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
{
global $smcFunc, $db_package_log, $txt, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// Log that we will want to uninstall this!
$db_package_log[] = array('remove_column', $table_name, $column_info['name']);
// Does it exist - if so don't add it again!
$columns = $smcFunc['db_list_columns']($table_name, false);
foreach ($columns as $column)
if ($column == $column_info['name'])
{
// If we're going to overwrite then use change column.
if ($if_exists == 'update')
return $smcFunc['db_change_column']($table_name, $column_info['name'], $column_info);
else
return false;
}
// Alter the table to add the column.
if ($smcFunc['db_alter_table']($table_name, array('add' => array($column_info))) === false)
return false;
return true;
}
// We can't reliably do this on SQLite - damn!
function smf_db_remove_column($table_name, $column_name, $parameters = array(), $error = 'fatal')
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
if ($smcFunc['db_alter_table']($table_name, array('remove' => array(array('name' => $column_name)))))
return true;
else
return false;
}
// Change a column.
function smf_db_change_column($table_name, $old_column, $column_info, $parameters = array(), $error = 'fatal')
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
if ($smcFunc['db_alter_table']($table_name, array('change' => array(array('name' => $old_column) + $column_info))))
return true;
else
return false;
}
// Add an index.
function smf_db_add_index($table_name, $index_info, $parameters = array(), $if_exists = 'update', $error = 'fatal')
{
global $smcFunc, $db_package_log, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// No columns = no index.
if (empty($index_info['columns']))
return false;
$columns = implode(',', $index_info['columns']);
// No name - make it up!
if (empty($index_info['name']))
{
// No need for primary.
if (isset($index_info['type']) && $index_info['type'] == 'primary')
$index_info['name'] = '';
else
$index_info['name'] = implode('_', $index_info['columns']);
}
else
$index_info['name'] = $index_info['name'];
// Log that we are going to want to remove this!
$db_package_log[] = array('remove_index', $table_name, $index_info['name']);
// Let's get all our indexes.
$indexes = $smcFunc['db_list_indexes']($table_name, true);
// Do we already have it?
foreach ($indexes as $index)
{
if ($index['name'] == $index_info['name'] || ($index['type'] == 'primary' && isset($index_info['type']) && $index_info['type'] == 'primary'))
{
// If we want to overwrite simply remove the current one then continue.
if ($if_exists != 'update' || $index['type'] == 'primary')
return false;
else
$smcFunc['db_remove_index']($table_name, $index_info['name']);
}
}
// If we're here we know we don't have the index - so just add it.
if (!empty($index_info['type']) && $index_info['type'] == 'primary')
{
//!!! Doesn't work with PRIMARY KEY yet.
}
else
{
$smcFunc['db_query']('', '
CREATE ' . (isset($index_info['type']) && $index_info['type'] == 'unique' ? 'UNIQUE' : '') . ' INDEX ' . $index_info['name'] . ' ON ' . $table_name . ' (' . $columns . ')',
array(
'security_override' => true,
)
);
}
}
// Remove an index.
function smf_db_remove_index($table_name, $index_name, $parameters = array(), $error = 'fatal')
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// Better exist!
$indexes = $smcFunc['db_list_indexes']($table_name, true);
foreach ($indexes as $index)
{
//!!! Doesn't do primary key at the moment!
if ($index['type'] != 'primary' && $index['name'] == $index_name)
{
// Drop the bugger...
$smcFunc['db_query']('', '
DROP INDEX ' . $index_name,
array(
'security_override' => true,
)
);
return true;
}
}
// Not to be found ;(
return false;
}
// Get the schema formatted name for a type.
function smf_db_calculate_type($type_name, $type_size = null, $reverse = false)
{
// Generic => Specific.
if (!$reverse)
{
$types = array(
'mediumint' => 'int',
'tinyint' => 'smallint',
'mediumtext' => 'text',
'largetext' => 'text',
);
}
else
{
$types = array(
'integer' => 'int',
);
}
// Got it? Change it!
if (isset($types[$type_name]))
{
if ($type_name == 'tinytext')
$type_size = 255;
$type_name = $types[$type_name];
}
// Numbers don't have a size.
if (strpos($type_name, 'int') !== false)
$type_size = null;
return array($type_name, $type_size);
}
// Get table structure.
function smf_db_table_structure($table_name, $parameters = array())
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
return array(
'name' => $table_name,
'columns' => $smcFunc['db_list_columns']($table_name, true),
'indexes' => $smcFunc['db_list_indexes']($table_name, true),
);
}
// Harder than it should be on sqlite!
function smf_db_list_columns($table_name, $detail = false, $parameters = array())
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
$result = $smcFunc['db_query']('', '
PRAGMA table_info(' . $table_name . ')',
array(
'security_override' => true,
)
);
$columns = array();
$primaries = array();
while ($row = $smcFunc['db_fetch_assoc']($result))
{
if (!$detail)
{
$columns[] = $row['name'];
}
else
{
// Auto increment is hard to tell really... if there's only one primary it probably is.
if ($row['pk'])
$primaries[] = $row['name'];
// Can we split out the size?
if (preg_match('~(.+?)\s*\((\d+)\)~i', $row['type'], $matches))
{
$type = $matches[1];
$size = $matches[2];
}
else
{
$type = $row['type'];
$size = null;
}
$columns[$row['name']] = array(
'name' => $row['name'],
'null' => $row['notnull'] ? false : true,
'default' => $row['dflt_value'],
'type' => $type,
'size' => $size,
'auto' => false,
);
}
}
$smcFunc['db_free_result']($result);
// Put in our guess at auto_inc.
if (count($primaries) == 1)
$columns[$primaries[0]]['auto'] = true;
return $columns;
}
// What about some index information?
function smf_db_list_indexes($table_name, $detail = false, $parameters = array())
{
global $smcFunc, $db_prefix;
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
$result = $smcFunc['db_query']('', '
PRAGMA index_list(' . $table_name . ')',
array(
'security_override' => true,
)
);
$indexes = array();
while ($row = $smcFunc['db_fetch_assoc']($result))
{
if (!$detail)
$indexes[] = $row['name'];
else
{
$result2 = $smcFunc['db_query']('', '
PRAGMA index_info(' . $row['name'] . ')',
array(
'security_override' => true,
)
);
while ($row2 = $smcFunc['db_fetch_assoc']($result2))
{
// What is the type?
if ($row['unique'])
$type = 'unique';
else
$type = 'index';
// This is the first column we've seen?
if (empty($indexes[$row['name']]))
{
$indexes[$row['name']] = array(
'name' => $row['name'],
'type' => $type,
'columns' => array(),
);
}
// Add the column...
$indexes[$row['name']]['columns'][] = $row2['name'];
}
$smcFunc['db_free_result']($result2);
}
}
$smcFunc['db_free_result']($result);
return $indexes;
}
function smf_db_alter_table($table_name, $columns)
{
global $smcFunc, $db_prefix, $db_name, $boarddir;
$db_file = substr($db_name, -3) === '.db' ? $db_name : $db_name . '.db';
$table_name = str_replace('{db_prefix}', $db_prefix, $table_name);
// Let's get the current columns for the table.
$current_columns = $smcFunc['db_list_columns']($table_name, true);
// Let's get a list of columns for the temp table.
$temp_table_columns = array();
// Let's see if we have columns to remove or columns that are being added that already exist.
foreach ($current_columns as $key => $column)
{
$exists = false;
if (isset($columns['remove']))
foreach ($columns['remove'] as $drop)
if ($drop['name'] == $column['name'])
{
$exists = true;
break;
}
if (isset($columns['add']))
foreach ($columns['add'] as $key2 => $add)
if ($add['name'] == $column['name'])
{
unset($columns['add'][$key2]);
break;
}
// Doesn't exist then we 'remove'.
if (!$exists)
$temp_table_columns[] = $column['name'];
}
// If they are equal then that means that the column that we are adding exists or it doesn't exist and we are not looking to change any one of them.
if (count($temp_table_columns) == count($current_columns) && empty($columns['change']) && empty($columns['add']))
return true;
// Drop the temp table.
$smcFunc['db_query']('', '
DROP TABLE {raw:temp_table_name}',
array(
'temp_table_name' => $table_name . '_tmp',
'db_error_skip' => true,
)
);
// Let's make a backup of the current database.
// We only want the first backup of a table modification. So if there is a backup file and older than an hour just delete and back up again
$db_backup_file = $boarddir . '/Packages/backups/backup_' . $table_name . '_' . basename($db_file) . md5($table_name . $db_file);
if (file_exists($db_backup_file) && time() - filemtime($db_backup_file) > 3600)
{
@unlink($db_backup_file);
@copy($db_file, $db_backup_file);
}
elseif (!file_exists($db_backup_file))
@copy($db_file, $db_backup_file);
// If we don't have temp tables then everything crapped out. Just exit.
if (empty($temp_table_columns))
return false;
// Start
$smcFunc['db_transaction']('begin');
// Let's create the temporary table.
$createTempTable = $smcFunc['db_query']('', '
CREATE TEMPORARY TABLE {raw:temp_table_name}
(
{raw:columns}
);',
array(
'temp_table_name' => $table_name . '_tmp',
'columns' => implode(', ', $temp_table_columns),
'db_error_skip' => true,
)
) !== false;
if (!$createTempTable)
return false;
// Insert into temp table.
$smcFunc['db_query']('', '
INSERT INTO {raw:temp_table_name}
({raw:columns})
SELECT {raw:columns}
FROM {raw:table_name}',
array(
'table_name' => $table_name,
'columns' => implode(', ', $temp_table_columns),
'temp_table_name' => $table_name . '_tmp',
)
);
// Drop the current table.
$dropTable = $smcFunc['db_query']('', '
DROP TABLE {raw:table_name}',
array(
'table_name' => $table_name,
'db_error_skip' => true,
)
) !== false;
// If you can't drop the main table then there is no where to go from here. Just return.
if (!$dropTable)
return false;
// We need to keep track of the structure for the current columns and the new columns.
$new_columns = array();
$column_names = array();
// Let's get the ones that we already have first.
foreach ($current_columns as $name => $column)
{
if (in_array($name, $temp_table_columns))
{
$new_columns[$name] = array(
'name' => $name,
'type' => $column['type'],
'size' => isset($column['size']) ? (int) $column['size'] : null,
'null' => !empty($column['null']),
'auto' => isset($column['auto']) ? $column['auto'] : false,
'default' => isset($column['default']) ? $column['default'] : '',
);
// Lets keep track of the name for the column.
$column_names[$name] = $name;
}
}
// Now the new.
if (!empty($columns['add']))
foreach ($columns['add'] as $add)
{
$new_columns[$add['name']] = array(
'name' => $add['name'],
'type' => $add['type'],
'size' => isset($add['size']) ? (int) $add['size'] : null,
'null' => !empty($add['null']),
'auto' => isset($add['auto']) ? $add['auto'] : false,
'default' => isset($add['default']) ? $add['default'] : '',
);
// Let's keep track of the name for the column.
$column_names[$add['name']] = strstr('int', $add['type']) ? ' 0 AS ' . $add['name'] : ' {string:empty_string} AS ' . $add['name'];
}
// Now to change a column. Not drop but change it.
if (isset($columns['change']))
foreach ($columns['change'] as $change)
if (isset($new_columns[$change['name']]))
$new_columns[$change['name']] = array(
'name' => $change['name'],
'type' => $change['type'],
'size' => isset($change['size']) ? (int) $change['size'] : null,
'null' => !empty($change['null']),
'auto' => isset($change['auto']) ? $change['auto'] : false,
'default' => isset($change['default']) ? $change['default'] : '',
);
// Now let's create the table.
$createTable = $smcFunc['db_create_table']($table_name, $new_columns, array(), array('skip_transaction' => true));
// Did it create correctly?
if ($createTable === false)
return false;
// Back to it's original table.
$insertData = $smcFunc['db_query']('', '
INSERT INTO {raw:table_name}
({raw:columns})
SELECT ' . implode(', ', $column_names) . '
FROM {raw:temp_table_name}',
array(
'table_name' => $table_name,
'columns' => implode(', ', array_keys($new_columns)),
'columns_select' => implode(', ', $column_names),
'temp_table_name' => $table_name . '_tmp',
'empty_string' => '',
)
);
// Did everything insert correctly?
if (!$insertData)
return false;
// Drop the temp table.
$smcFunc['db_query']('', '
DROP TABLE {raw:temp_table_name}',
array(
'temp_table_name' => $table_name . '_tmp',
'db_error_skip' => true,
)
);
// Commit or else there is no point in doing the previous steps.
$smcFunc['db_transaction']('commit');
// We got here so we're good. The temp table should be deleted, if not it will be gone later on >:D.
return true;
}
?>

View File

@ -1,77 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0
*/
if (!defined('SMF'))
die('Hacking attempt...');
/* This file contains database functions specific to search related activity.
void db_search_init()
- adds the functions in this file to the $smcFunc array
boolean smf_db_search_support($search_type)
- whether this database type support the search type $search_type
void smf_db_create_word_search($size)
- create the custom word index table
*/
// Add the file functions to the $smcFunc array.
function db_search_init()
{
global $smcFunc;
if (!isset($smcFunc['db_search_query']) || $smcFunc['db_search_query'] != 'smf_db_query')
$smcFunc += array(
'db_search_query' => 'smf_db_query',
'db_search_support' => 'smf_db_search_support',
'db_create_word_search' => 'smf_db_create_word_search',
'db_support_ignore' => true,
);
}
// Does this database type support this search type?
function smf_db_search_support($search_type)
{
$supported_types = array('fulltext');
return in_array($search_type, $supported_types);
}
// Highly specific - create the custom word index table!
function smf_db_create_word_search($size)
{
global $smcFunc;
if ($size == 'small')
$size = 'smallint(5)';
elseif ($size == 'medium')
$size = 'mediumint(8)';
else
$size = 'int(10)';
$smcFunc['db_query']('', '
CREATE TABLE {db_prefix}log_search_words (
id_word {raw:size} unsigned NOT NULL default {string:string_zero},
id_msg int(10) unsigned NOT NULL default {string:string_zero},
PRIMARY KEY (id_word, id_msg)
) ENGINE=InnoDB',
array(
'string_zero' => '0',
'size' => $size,
)
);
}
?>

View File

@ -1,122 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0.7
*/
if (!defined('SMF'))
die('Hacking attempt...');
/* This file contains database functions specific to search related activity.
void db_search_init()
- adds the functions in this file to the $smcFunc array
boolean smf_db_search_support($search_type)
- whether this database type support the search type $search_type
void smf_db_create_word_search($size)
- create the custom word index table
resource smf_db_search_query($identifier, $db_string, $db_values = array(), $connection = null)
- returns the correct query for this search type.
*/
// Add the file functions to the $smcFunc array.
function db_search_init()
{
global $smcFunc;
if (!isset($smcFunc['db_search_query']) || $smcFunc['db_search_query'] != 'smf_db_search_query')
$smcFunc += array(
'db_search_query' => 'smf_db_search_query',
'db_search_support' => 'smf_db_search_support',
'db_create_word_search' => 'smf_db_create_word_search',
'db_support_ignore' => false,
);
}
// Does this database type support this search type?
function smf_db_search_support($search_type)
{
$supported_types = array('custom');
return in_array($search_type, $supported_types);
}
// Returns the correct query for this search type.
function smf_db_search_query($identifier, $db_string, $db_values = array(), $connection = null)
{
global $smcFunc;
$replacements = array(
'create_tmp_log_search_topics' => array(
'~mediumint\(\d\)~i' => 'int',
'~unsigned~i' => '',
'~ENGINE=MEMORY~i' => '',
),
'create_tmp_log_search_messages' => array(
'~mediumint\(\d\)' => 'int',
'~unsigned~i' => '',
'~TYPE=HEAP~i' => '',
),
'drop_tmp_log_search_topics' => array(
'~IF\sEXISTS~i' => '',
),
'drop_tmp_log_search_messages' => array(
'~IF\sEXISTS~i' => '',
),
'insert_into_log_messages_fulltext' => array(
'~NOT\sRLIKE~i' => '!~*',
'~RLIKE~i' => '~*',
),
'insert_log_search_results_subject' => array(
'~NOT\sRLIKE~i' => '!~*',
'~RLIKE~i' => '~*',
),
);
if (isset($replacements[$identifier]))
$db_string = preg_replace(array_keys($replacements[$identifier]), array_values($replacements[$identifier]), $db_string);
elseif (preg_match('~^\s*INSERT\sIGNORE~i', $db_string) != 0)
{
$db_string = preg_replace('~^\s*INSERT\sIGNORE~i', 'INSERT', $db_string);
// Don't error on multi-insert.
$db_values['db_error_skip'] = true;
}
$return = $smcFunc['db_query']('', $db_string,
$db_values, $connection
);
return $return;
}
// Highly specific - create the custom word index table!
function smf_db_create_word_search($size)
{
global $smcFunc;
$size = 'int';
$smcFunc['db_query']('', '
CREATE TABLE {db_prefix}log_search_words (
id_word {raw:size} NOT NULL default {string:string_zero},
id_msg int NOT NULL default {string:string_zero},
PRIMARY KEY (id_word, id_msg)
)',
array(
'size' => $size,
'string_zero' => '0',
)
);
}
?>

View File

@ -1,106 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0.7
*/
if (!defined('SMF'))
die('Hacking attempt...');
/* This file contains database functions specific to search related activity.
void db_search_init()
- adds the functions in this file to the $smcFunc array
boolean smf_db_search_support($search_type)
- whether this database type support the search type $search_type
void smf_db_create_word_search($size)
- create the custom word index table
resource smf_db_search_query($identifier, $db_string, $db_values = array(), $connection = null)
- returns the correct query for this search type.
*/
// Add the file functions to the $smcFunc array.
function db_search_init()
{
global $smcFunc;
if (!isset($smcFunc['db_search_query']) || $smcFunc['db_search_query'] != 'smf_db_search_query')
$smcFunc += array(
'db_search_query' => 'smf_db_search_query',
'db_search_support' => 'smf_db_search_support',
'db_create_word_search' => 'smf_db_create_word_search',
'db_support_ignore' => false,
);
}
// Does this database type support this search type?
function smf_db_search_support($search_type)
{
$supported_types = array('custom');
return in_array($search_type, $supported_types);
}
// Returns the correct query for this search type.
function smf_db_search_query($identifier, $db_string, $db_values = array(), $connection = null)
{
global $smcFunc;
$replacements = array(
'create_tmp_log_search_topics' => array(
'~mediumint\(\d\)~i' => 'int',
'~ENGINE=MEMORY~i' => '',
),
'create_tmp_log_search_messages' => array(
'~mediumint\(\d\)~i' => 'int',
'~TYPE=HEAP~i' => '',
),
);
if (isset($replacements[$identifier]))
$db_string = preg_replace(array_keys($replacements[$identifier]), array_values($replacements[$identifier]), $db_string);
elseif (preg_match('~^\s*INSERT\sIGNORE~i', $db_string) != 0)
{
$db_string = preg_replace('~^\s*INSERT\sIGNORE~i', 'INSERT', $db_string);
// Don't error on multi-insert.
$db_values['db_error_skip'] = true;
}
$return = $smcFunc['db_query']('', $db_string,
$db_values, $connection
);
return $return;
}
// Highly specific - create the custom word index table!
function smf_db_create_word_search($size)
{
global $smcFunc;
$size = 'int';
$smcFunc['db_query']('', '
CREATE TABLE {db_prefix}log_search_words (
id_word {raw:size} NOT NULL default {string:string_zero},
id_msg int(10) NOT NULL default {string:string_zero},
PRIMARY KEY (id_word, id_msg)
)',
array(
'size' => $size,
'string_zero' => '0',
)
);
}
?>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,182 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0
*/
if (!defined('SMF'))
die('Hacking attempt...');
/*
This file has a single job - database backup.
void DumpDatabase2()
- writes all of the database to standard output.
- uses gzip compression if compress is set in the URL/post data.
- may possibly time out in some cases.
- the data dumped depends on whether "struct" and "data" are passed.
- requires an administrator and the session hash by post.
- is called from ManageMaintenance.php.
*/
// Dumps the database to a file.
function DumpDatabase2()
{
global $db_name, $scripturl, $context, $modSettings, $crlf, $smcFunc, $db_prefix;
// Administrators only!
if (!allowedTo('admin_forum'))
fatal_lang_error('no_dump_database', 'critical');
// You can't dump nothing!
if (!isset($_REQUEST['struct']) && !isset($_REQUEST['data']))
$_REQUEST['data'] = true;
checkSession('post');
// We will need this, badly!
db_extend();
// Attempt to stop from dying...
@set_time_limit(600);
if (@ini_get('memory_limit') < 256)
@ini_set('memory_limit', '256M');
// Start saving the output... (don't do it otherwise for memory reasons.)
if (isset($_REQUEST['compress']) && function_exists('gzencode'))
{
// Make sure we're gzipping output, but then say we're not in the header ^_^.
if (empty($modSettings['enableCompressedOutput']))
@ob_start('ob_gzhandler');
// Try to clean any data already outputted.
elseif (ob_get_length() != 0)
{
ob_end_clean();
@ob_start('ob_gzhandler');
}
// Send faked headers so it will just save the compressed output as a gzip.
header('Content-Type: application/x-gzip');
header('Accept-Ranges: bytes');
header('Content-Encoding: none');
// Gecko browsers... don't like this. (Mozilla, Firefox, etc.)
if (!$context['browser']['is_gecko'])
header('Content-Transfer-Encoding: binary');
// The file extension will include .gz...
$extension = '.sql.gz';
}
else
{
// Get rid of the gzipping alreading being done.
if (!empty($modSettings['enableCompressedOutput']))
@ob_end_clean();
// If we can, clean anything already sent from the output buffer...
elseif (function_exists('ob_clean') && ob_get_length() != 0)
ob_clean();
// Tell the client to save this file, even though it's text.
header('Content-Type: ' . ($context['browser']['is_ie'] || $context['browser']['is_opera'] ? 'application/octetstream' : 'application/octet-stream'));
header('Content-Encoding: none');
// This time the extension should just be .sql.
$extension = '.sql';
}
// This should turn off the session URL parser.
$scripturl = '';
// If this database is flat file and has a handler function pass it to that.
if (!empty($smcFunc['db_get_backup']))
{
$smcFunc['db_get_backup']();
exit;
}
// Send the proper headers to let them download this file.
header('Content-Disposition: filename="' . $db_name . '-' . (empty($_REQUEST['struct']) ? 'data' : (empty($_REQUEST['data']) ? 'structure' : 'complete')) . '_' . strftime('%Y-%m-%d') . $extension . '"');
header('Cache-Control: private');
header('Connection: close');
// This makes things simpler when using it so very very often.
$crlf = "\r\n";
// SQL Dump Header.
echo
'-- ==========================================================', $crlf,
'--', $crlf,
'-- Database dump of tables in `', $db_name, '`', $crlf,
'-- ', timeformat(time(), false), $crlf,
'--', $crlf,
'-- ==========================================================', $crlf,
$crlf;
// Get all tables in the database....
if (preg_match('~^`(.+?)`\.(.+?)$~', $db_prefix, $match) != 0)
{
$db = strtr($match[1], array('`' => ''));
$dbp = str_replace('_', '\_', $match[2]);
}
else
{
$db = false;
$dbp = $db_prefix;
}
// Dump each table.
$tables = $smcFunc['db_list_tables'](false, $db_prefix . '%');
foreach ($tables as $tableName)
{
if (function_exists('apache_reset_timeout'))
@apache_reset_timeout();
// Are we dumping the structures?
if (isset($_REQUEST['struct']))
{
echo
$crlf,
'--', $crlf,
'-- Table structure for table `', $tableName, '`', $crlf,
'--', $crlf,
$crlf,
$smcFunc['db_table_sql']($tableName), ';', $crlf;
}
// How about the data?
if (!isset($_REQUEST['data']) || substr($tableName, -10) == 'log_errors')
continue;
// Are there any rows in this table?
$get_rows = $smcFunc['db_insert_sql']($tableName);
// No rows to get - skip it.
if (empty($get_rows))
continue;
echo
$crlf,
'--', $crlf,
'-- Dumping data in `', $tableName, '`', $crlf,
'--', $crlf,
$crlf,
$get_rows,
'-- --------------------------------------------------------', $crlf;
}
echo
$crlf,
'-- Done', $crlf;
exit;
}
?>

View File

@ -1,420 +0,0 @@
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2011 Simple Machines
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.0.4
*/
if (!defined('SMF'))
die('Hacking attempt...');
/* The purpose of this file is... errors. (hard to guess, huh?) It takes
care of logging, error messages, error handling, database errors, and
error log administration. It does this with:
bool db_fatal_error(bool loadavg = false)
- calls show_db_error().
- this is used for database connection error handling.
- loadavg means this is a load average problem, not a database error.
string log_error(string error_message, string error_type = general,
string filename = none, int line = none)
- logs an error, if error logging is enabled.
- depends on the enableErrorLogging setting.
- filename and line should be __FILE__ and __LINE__, respectively.
- returns the error message. (ie. die(log_error($msg));)
void fatal_error(string error_message, mixed (bool or string) log = general)
- stops execution and displays an error message.
- logs the error message if log is missing or true.
void fatal_lang_error(string error_message_key, mixed (bool or string) log = general,
array sprintf = array())
- stops execution and displays an error message by key.
- uses the string with the error_message_key key.
- loads the Errors language file.
- applies the sprintf information if specified.
- the information is logged if log is true or missing.
- logs the error in the forum's default language while displaying the error
message in the user's language
void error_handler(int error_level, string error_string, string filename,
int line)
- this is a standard PHP error handler replacement.
- dies with fatal_error() if the error_level matches with
error_reporting.
void setup_fatal_error_context(string error_message)
- uses the fatal_error sub template of the Errors template - or the
error sub template in the Wireless template.
- used by fatal_error() and fatal_lang_error()
void show_db_error(bool loadavg = false)
- called by db_fatal_error() function
- shows a complete page independent of language files or themes.
- used only if there's no way to connect to the database or the
load averages are too high to do so.
- loadavg means this is a load average problem, not a database error.
- stops further execution of the script.
*/
// Handle fatal errors - like connection errors or load average problems
function db_fatal_error($loadavg = false)
{
global $sourcedir;
show_db_error($loadavg);
// Since we use "or db_fatal_error();" this is needed...
return false;
}
// Log an error, if the option is on.
function log_error($error_message, $error_type = 'general', $file = null, $line = null)
{
global $txt, $modSettings, $sc, $user_info, $smcFunc, $scripturl, $last_error;
// Check if error logging is actually on.
if (empty($modSettings['enableErrorLogging']))
return $error_message;
// Basically, htmlspecialchars it minus &. (for entities!)
$error_message = strtr($error_message, array('<' => '&lt;', '>' => '&gt;', '"' => '&quot;'));
$error_message = strtr($error_message, array('&lt;br /&gt;' => '<br />', '&lt;b&gt;' => '<strong>', '&lt;/b&gt;' => '</strong>', "\n" => '<br />'));
// Add a file and line to the error message?
// Don't use the actual txt entries for file and line but instead use %1$s for file and %2$s for line
if ($file == null)
$file = '';
else
// Window style slashes don't play well, lets convert them to the unix style.
$file = str_replace('\\', '/', $file);
if ($line == null)
$line = 0;
else
$line = (int) $line;
// Just in case there's no id_member or IP set yet.
if (empty($user_info['id']))
$user_info['id'] = 0;
if (empty($user_info['ip']))
$user_info['ip'] = '';
// Find the best query string we can...
$query_string = empty($_SERVER['QUERY_STRING']) ? (empty($_SERVER['REQUEST_URL']) ? '' : str_replace($scripturl, '', $_SERVER['REQUEST_URL'])) : $_SERVER['QUERY_STRING'];
// Don't log the session hash in the url twice, it's a waste.
$query_string = htmlspecialchars((SMF == 'SSI' ? '' : '?') . preg_replace(array('~;sesc=[^&;]+~', '~' . session_name() . '=' . session_id() . '[&;]~'), array(';sesc', ''), $query_string));
// Just so we know what board error messages are from.
if (isset($_POST['board']) && !isset($_GET['board']))
$query_string .= ($query_string == '' ? 'board=' : ';board=') . $_POST['board'];
// What types of categories do we have?
$known_error_types = array(
'general',
'critical',
'database',
'undefined_vars',
'user',
'template',
'debug',
);
// Make sure the category that was specified is a valid one
$error_type = in_array($error_type, $known_error_types) && $error_type !== true ? $error_type : 'general';
// Don't log the same error countless times, as we can get in a cycle of depression...
$error_info = array($user_info['id'], time(), $user_info['ip'], $query_string, $error_message, (string) $sc, $error_type, $file, $line);
if (empty($last_error) || $last_error != $error_info)
{
// Insert the error into the database.
$smcFunc['db_insert']('',
'{db_prefix}log_errors',
array('id_member' => 'int', 'log_time' => 'int', 'ip' => 'string-16', 'url' => 'string-65534', 'message' => 'string-65534', 'session' => 'string', 'error_type' => 'string', 'file' => 'string-255', 'line' => 'int'),
$error_info,
array('id_error')
);
$last_error = $error_info;
}
// Return the message to make things simpler.
return $error_message;
}
// An irrecoverable error.
function fatal_error($error, $log = 'general')
{
global $txt, $context, $modSettings;
// We don't have $txt yet, but that's okay...
if (empty($txt))
die($error);
setup_fatal_error_context($log || (!empty($modSettings['enableErrorLogging']) && $modSettings['enableErrorLogging'] == 2) ? log_error($error, $log) : $error);
}
// A fatal error with a message stored in the language file.
function fatal_lang_error($error, $log = 'general', $sprintf = array())
{
global $txt, $language, $modSettings, $user_info, $context;
static $fatal_error_called = false;
// Try to load a theme if we don't have one.
if (empty($context['theme_loaded']) && empty($fatal_error_called))
{
$fatal_error_called = true;
loadTheme();
}
// If we have no theme stuff we can't have the language file...
if (empty($context['theme_loaded']))
die($error);
$reload_lang_file = true;
// Log the error in the forum's language, but don't waste the time if we aren't logging
if ($log || (!empty($modSettings['enableErrorLogging']) && $modSettings['enableErrorLogging'] == 2))
{
loadLanguage('Errors', $language);
$reload_lang_file = $language != $user_info['language'];
$error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
log_error($error_message, $log);
}
// Load the language file, only if it needs to be reloaded
if ($reload_lang_file)
{
loadLanguage('Errors');
$error_message = empty($sprintf) ? $txt[$error] : vsprintf($txt[$error], $sprintf);
}
setup_fatal_error_context($error_message);
}
// Handler for standard error messages.
function error_handler($error_level, $error_string, $file, $line)
{
global $settings, $modSettings, $db_show_debug;
// Ignore errors if we're ignoring them or they are strict notices from PHP 5 (which cannot be solved without breaking PHP 4.)
if (error_reporting() == 0 || (defined('E_STRICT') && $error_level == E_STRICT && (empty($modSettings['enableErrorLogging']) || $modSettings['enableErrorLogging'] != 2)))
return;
if (strpos($file, 'eval()') !== false && !empty($settings['current_include_filename']))
{
if (function_exists('debug_backtrace'))
{
$array = debug_backtrace();
for ($i = 0; $i < count($array); $i++)
{
if ($array[$i]['function'] != 'loadSubTemplate')
continue;
// This is a bug in PHP, with eval, it seems!
if (empty($array[$i]['args']))
$i++;
break;
}
if (isset($array[$i]) && !empty($array[$i]['args']))
$file = realpath($settings['current_include_filename']) . ' (' . $array[$i]['args'][0] . ' sub template - eval?)';
else
$file = realpath($settings['current_include_filename']) . ' (eval?)';
}
else
$file = realpath($settings['current_include_filename']) . ' (eval?)';
}
if (isset($db_show_debug) && $db_show_debug === true)
{
// Commonly, undefined indexes will occur inside attributes; try to show them anyway!
if ($error_level % 255 != E_ERROR)
{
$temporary = ob_get_contents();
if (substr($temporary, -2) == '="')
echo '"';
}
// Debugging! This should look like a PHP error message.
echo '<br />
<strong>', $error_level % 255 == E_ERROR ? 'Error' : ($error_level % 255 == E_WARNING ? 'Warning' : 'Notice'), '</strong>: ', $error_string, ' in <strong>', $file, '</strong> on line <strong>', $line, '</strong><br />';
}
$error_type = strpos(strtolower($error_string), 'undefined') !== false ? 'undefined_vars' : 'general';
$message = log_error($error_level . ': ' . $error_string, $error_type, $file, $line);
// Let's give integrations a chance to ouput a bit differently
call_integration_hook('integrate_output_error', array($message, $error_type, $error_level, $file, $line));
// Dying on these errors only causes MORE problems (blank pages!)
if ($file == 'Unknown')
return;
// If this is an E_ERROR or E_USER_ERROR.... die. Violently so.
if ($error_level % 255 == E_ERROR)
obExit(false);
else
return;
// If this is an E_ERROR, E_USER_ERROR, E_WARNING, or E_USER_WARNING.... die. Violently so.
if ($error_level % 255 == E_ERROR || $error_level % 255 == E_WARNING)
fatal_error(allowedTo('admin_forum') ? $message : $error_string, false);
// We should NEVER get to this point. Any fatal error MUST quit, or very bad things can happen.
if ($error_level % 255 == E_ERROR)
die('Hacking attempt...');
}
function setup_fatal_error_context($error_message)
{
global $context, $txt, $ssi_on_error_method;
static $level = 0;
// Attempt to prevent a recursive loop.
++$level;
if ($level > 1)
return false;
// Maybe they came from dlattach or similar?
if (SMF != 'SSI' && empty($context['theme_loaded']))
loadTheme();
// Don't bother indexing errors mate...
$context['robot_no_index'] = true;
if (!isset($context['error_title']))
$context['error_title'] = $txt['error_occured'];
$context['error_message'] = isset($context['error_message']) ? $context['error_message'] : $error_message;
if (empty($context['page_title']))
$context['page_title'] = $context['error_title'];
// Display the error message - wireless?
if (defined('WIRELESS') && WIRELESS)
$context['sub_template'] = WIRELESS_PROTOCOL . '_error';
// Load the template and set the sub template.
else
{
loadTemplate('Errors');
$context['sub_template'] = 'fatal_error';
}
// If this is SSI, what do they want us to do?
if (SMF == 'SSI')
{
if (!empty($ssi_on_error_method) && $ssi_on_error_method !== true && is_callable($ssi_on_error_method))
$ssi_on_error_method();
elseif (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
loadSubTemplate('fatal_error');
// No layers?
if (empty($ssi_on_error_method) || $ssi_on_error_method !== true)
exit;
}
// We want whatever for the header, and a footer. (footer includes sub template!)
obExit(null, true, false, true);
/* DO NOT IGNORE:
If you are creating a bridge to SMF or modifying this function, you MUST
make ABSOLUTELY SURE that this function quits and DOES NOT RETURN TO NORMAL
PROGRAM FLOW. Otherwise, security error messages will not be shown, and
your forum will be in a very easily hackable state.
*/
trigger_error('Hacking attempt...', E_USER_ERROR);
}
// Show an error message for the connection problems.
function show_db_error($loadavg = false)
{
global $sourcedir, $mbname, $maintenance, $mtitle, $mmessage, $modSettings;
global $db_connection, $webmaster_email, $db_last_error, $db_error_send, $smcFunc;
// Just check we're not in any buffers, just in case.
for ($i = ob_get_level(); $i > 0; $i--)
@ob_end_clean();
// Don't cache this page!
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache');
// Send the right error codes.
header('HTTP/1.1 503 Service Temporarily Unavailable');
header('Status: 503 Service Temporarily Unavailable');
header('Retry-After: 3600');
if ($loadavg == false)
{
// For our purposes, we're gonna want this on if at all possible.
$modSettings['cache_enable'] = '1';
if (($temp = cache_get_data('db_last_error', 600)) !== null)
$db_last_error = max($db_last_error, $temp);
if ($db_last_error < time() - 3600 * 24 * 3 && empty($maintenance) && !empty($db_error_send))
{
require_once($sourcedir . '/Subs-Admin.php');
// Avoid writing to the Settings.php file if at all possible; use shared memory instead.
cache_put_data('db_last_error', time(), 600);
if (($temp = cache_get_data('db_last_error', 600)) == null)
updateLastDatabaseError();
// Language files aren't loaded yet :(.
$db_error = @$smcFunc['db_error']($db_connection);
@mail($webmaster_email, $mbname . ': SMF Database Error!', 'There has been a problem with the database!' . ($db_error == '' ? '' : "\n" . $smcFunc['db_title'] . ' reported:' . "\n" . $db_error) . "\n\n" . 'This is a notice email to let you know that SMF could not connect to the database, contact your host if this continues.');
}
}
if (!empty($maintenance))
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="robots" content="noindex" />
<title>', $mtitle, '</title>
</head>
<body>
<h3>', $mtitle, '</h3>
', $mmessage, '
</body>
</html>';
// If this is a load average problem, display an appropriate message (but we still don't have language files!)
elseif ($loadavg)
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="robots" content="noindex" />
<title>Temporarily Unavailable</title>
</head>
<body>
<h3>Temporarily Unavailable</h3>
Due to high stress on the server the forum is temporarily unavailable. Please try again later.
</body>
</html>';
// What to do? Language files haven't and can't be loaded yet...
else
echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="robots" content="noindex" />
<title>Connection Problems</title>
</head>
<body>
<h3>Connection Problems</h3>
Sorry, SMF was unable to connect to the database. This may be caused by the server being busy. Please try again later.
</body>
</html>';
die;
}
?>

File diff suppressed because it is too large Load Diff

View File

@ -1,120 +0,0 @@
<?php
// ----------------------------------------------------------
// -- FelBlogAdmin.php --
// ----------------------------------------------------------
// -- Version: 0.94.0 for SMF 1.1.x --
// -- Copyright 2006,2007 by: Korinna "Feline" Brinkmann --
// -- Support and Updates at: http://feline-networks.com --
// ----------------------------------------------------------
if (!defined('SMF'))
die('Hacking attempt...');
// FelBlog Admin settings
function FelBlog_Admin()
{
global $context, $txt, $db_prefix, $scripturl;
if(isset($_GET['set']) && $_GET['set'] == 'upd')
{
list($tmp['wysiwyg_edit'],
$tmp['wysiwyg_comment'],
$tmp['content_len'],
$tmp['overview_pages'],
$tmp['comment_pages'],
$tmp['remove_links'],
$tmp['recent_len'],
$tmp['censor_text'],
$tmp['content_pages'],
$tmp['remove_images'],
$tmp['image_prefix']) = explode(',', '0,0,50,20,10,0,5,10,10,0,3');
$thumb_show = 0;
foreach ($_POST as $what => $value)
{
if($what == 'blogadmin')
$blogadmin = $value;
elseif($what == 'thumb_show')
$thumb_show = $value;
elseif($what == 'thumb_size')
$thumb_size = $value;
elseif($what != 'send')
$tmp[$what] = $value;
}
// make setting string for DB insert
$val='';
foreach($tmp as $n => $v)
$val = $v.','.$val;
$val = substr($val, 0, strlen($val)-1);
db_query("UPDATE {$db_prefix}felblog_settings SET value='".$val."' WHERE name='settings'", __FILE__, __LINE__);
db_query("UPDATE {$db_prefix}felblog_settings SET value='".$blogadmin."' WHERE name='blogadmin'", __FILE__, __LINE__);
db_query("UPDATE {$db_prefix}felblog_settings SET value='".$thumb_show."' WHERE name='thumb_show'", __FILE__, __LINE__);
db_query("UPDATE {$db_prefix}felblog_settings SET value='".$thumb_size."' WHERE name='thumb_size'", __FILE__, __LINE__);
redirectexit('action=felblog;sa=admin;set');
}
elseif(isset($_GET['acs']) && $_GET['acs'] == 'upd')
{
$acs['blog_acs'] = array();
$acs['blog_rd_acs'] = array();
$acs['blog_wr_acs'] = array();
foreach ($_POST as $what => $value)
{
$p = strpos($what, '_acs');
if(!$p === false)
$acs[substr($what,0, $p+4)][] = $value;
}
// merge access groups for locking
$acs['blog_wr_acs'] = array_unique(array_merge($acs['blog_wr_acs'], $acs['blog_acs']));
$acs['blog_rd_acs'] = array_unique(array_merge($acs['blog_rd_acs'], $acs['blog_wr_acs']));
// make accessgroup string for DB insert
$acsgrp = implode(',', $acs['blog_acs']).':'.implode(',', $acs['blog_rd_acs']).':'.implode(',', $acs['blog_wr_acs']);
db_query("UPDATE {$db_prefix}felblog_settings SET value='".$acsgrp."' WHERE name='blog_acs'", __FILE__, __LINE__);
redirectexit('action=felblog;sa=admin;acs');
}
// Get Admin users
$req = db_query("SELECT ID_MEMBER, realName, emailAddress
FROM {$db_prefix}members
WHERE ID_GROUP = 1
ORDER BY ID_MEMBER", __FILE__, __LINE__);
if (mysql_num_rows($req) > 0)
{
while($row = mysql_fetch_assoc($req))
{
$context['FelBlog']['Admin_List'][] = array(
'id' => $row['ID_MEMBER'],
'name' => $row['realName'],
'email' => $row['emailAddress']);
}
}
mysql_free_result($req);
// prepare tabs
$curact = isset($_GET['acs']) ? 'acs' : 'set';
$context['FelBlog']['admin_tabs'] = array(
'title' => $txt['fb_settings_title'],
'tabs' => array(
'set' => array(
'title' => $txt['fb_setcom_title'],
'href' => $scripturl . '?action=felblog;sa=admin;set'.$context['FelBlog']['UserLink'],
'is_selected' => $curact == 'set',
'is_enabled' => true,
),
'acs' => array(
'title' => $txt['fb_setacs_title'],
'href' => $scripturl . '?action=felblog;sa=admin;acs'.$context['FelBlog']['UserLink'],
'is_selected' => $curact == 'acs',
'is_enabled' => true,
),
),
);
$context['page_title'] = $txt['fb_settings_title'];
$context['FelBlog']['page_link'] = array(
'url' => $scripturl.'?'.$_SERVER['QUERY_STRING'],
'name' => $txt['fb_settings_title']);
loadTemplate('FelBlogAdmin');
}
?>

View File

@ -1,101 +0,0 @@
<?php
// ----------------------------------------------------------
// -- FelBlogCaptcha.php --
// ----------------------------------------------------------
// -- Version: 0.94.0 for SMF 1.1.x --
// -- Copyright 2006,2007 by: Korinna "Feline" Brinkmann --
// -- Support and Updates at: http://feline-networks.com --
// ----------------------------------------------------------
if (isset($_REQUEST['vcode']) && isset($_REQUEST['path']))
{
$captcha = $_REQUEST['vcode'];
$captcha = substr($captcha , 0, -strlen(dechex(mktime())));
$captcha_str = '';
for ($i = 0; $i < strlen($captcha); $i+=2)
$captcha_str .= chr(hexdec(substr($captcha, $i, 2)));
$captcha_str = base64_decode($captcha_str);
$gdfont = $_REQUEST['path'].'//fonts/Hootie.gdf';
$ttfont = $_REQUEST['path'].'/images/felblog/captcha.ttf';
$imgfont = $_REQUEST['path'].'/fonts/Hootie/';
if(isset($_REQUEST['letter']))
{
$_REQUEST['letter'] = (int) $_REQUEST['letter'];
CaptchaImageLetter($imgfont, strtolower($captcha_str{$_REQUEST['letter'] - 1}));
}
else
{
// it's GD2?
$testGD = get_extension_funcs('gd');
$gd2 = in_array('imagecreatetruecolor', $testGD) && function_exists('imagecreatetruecolor');
unset($testGD);
$BgCol = array(236, 237, 243);
$FgCol = array(64, 101, 136);
$fontidx = imageloadfont($gdfont);
// create image
$img_width = 125;
$img_height = 28;
$img = imagecreate($img_width, $img_height);
$bg_color = imagecolorallocate($img, $BgCol[0], $BgCol[1], $BgCol[2]);
imagefilledrectangle($img, 0, 0, $img_width, $img_height, $bg_color);
for ($i = 0; $i < 3; $i++)
$FgCol[$i] = rand(max($FgCol[$i] - 3, 0), min($FgCol[$i] + 3, 255));
$fg_color = imagecolorallocate($img, $FgCol[0], $FgCol[1], $FgCol[2]);
for ($i = 0; $i < 3; $i++)
$dotbgcolor[$i] = $BgCol[$i] < $FgCol[$i] ? rand(0, max($FgCol[$i] - 20, 0)) : rand(min($FgCol[$i] + 20, 255), 255);
$RndCol = imagecolorallocate($img, $dotbgcolor[0], $dotbgcolor[1], $dotbgcolor[2]);
// draw chars
$cur_x = 5;
for($i = 0; $i < 5; $i++)
{
// support TT fonts?
$can_TTF = function_exists('imagettftext');
if (!empty($can_TTF))
{
$angle = rand(-10, 10);
$font_size = rand(14, 18);
$isDraw = imagettftext($img, $font_size, $angle, $cur_x, 23, imagecolorallocate($img, rand(0, 150), rand(0, 150), rand(0, 150)), $ttfont, $captcha_str{$i});
if (empty($isDraw))
$can_TTF = '';
}
if (empty($can_TTF))
imagechar($img, $fontidx, $cur_x, 2, $captcha_str{$i}, imagecolorallocate($img, rand(0, 150), rand(0, 150), rand(0, 150)));
$cur_x += 24;
}
for ($i = rand(0, 2); $i < $img_height; $i += rand(1, 2))
for ($j = rand(0, 10); $j < $img_width; $j += rand(1, 15))
imagesetpixel($img, $j, $i, rand(0, 1) ? $fg_color : $RndCol);
imagerectangle($img, 0, 0, $img_width - 1, $img_height - 1, imagecolorallocate($img, 10, 10, 10));
// output the image
if (function_exists('imagegif'))
{
header('Content-type: image/gif');
imagegif($img);
}
else
{
header('Content-type: image/png');
imagepng($img);
}
imagedestroy($img);
die();
}
}
function CaptchaImageLetter($font, $letter)
{
header('Content-type: image/gif');
include($font . $letter . '.gif');
die();
}
?>

File diff suppressed because it is too large Load Diff

View File

@ -1,251 +0,0 @@
<?php
// ----------------------------------------------------------
// -- FelBlogSettings.php --
// ----------------------------------------------------------
// -- Version: 0.94.0 for SMF 1.1.x --
// -- Copyright 2006,2007 by: Korinna "Feline" Brinkmann --
// -- Support and Updates at: http://feline-networks.com --
// ----------------------------------------------------------
if (!defined('SMF'))
die('Hacking attempt...');
// FelBlog Manager Settings
function FelBlogSettings($uid)
{
global $context, $settings, $modSettings, $user_info, $scripturl, $txt, $user_profile, $db_prefix, $ID_MEMBER;
// Settings update
if($context['FelBlog']['action'][1] == 'upd')
{
if(!isOwner() && $context['FelBlog']['Manager']['have_blog'] && AllowedTo('admin_forum'))
{
$request = db_query("SELECT * FROM {$db_prefix}felblog_manager WHERE owner=$uid", __FILE__, __LINE__);
if($row = mysql_fetch_assoc($request))
$tmp = array(
'blogname' => addslashes($row['blogname']),
'blogdesc' => addslashes($row['blogdesc']),
'showarchive' => $row['showarchive'],
'showcategories' => $row['showcategories'],
'showcalendar' => $row['showcalendar'],
'blogcreated' => $row['blogcreated'],
'blogenabled' => 0,
'bloglocked' => 0,
'tracking' => $row['tracking']
);
mysql_free_result($request);
}
else
list($tmp['blogname'],
$tmp['blogdesc'],
$tmp['showcalendar'],
$tmp['showarchive'],
$tmp['showcategories'],
$tmp['blogenabled'],
$tmp['blogcreated'],
$tmp['bloglocked'],
$tmp['tracking']) = explode(',', ', , 0, 0, 0, 0, '.forum_time().', 0, 0|0:');
foreach ($_POST as $what => $value)
{
if ($what != 'send')
{
$value = strip_tags($value);
if($what == 'tracking')
$tr = $value;
elseif($what == 'trackself')
$trS = $value;
else
$tmp[$what] = $value;
}
}
if(isset($trS) && isset($tr))
$tmp['tracking'] = $trS.'|'.$tr;
if($context['FelBlog']['Manager']['have_blog'])
{
$updset = "UPDATE {$db_prefix}felblog_manager SET ";
foreach($tmp as $key => $data)
$updset .= $key.'='.(is_numeric($data) ? trim($data) : "'".$data."'").',';
$updset = substr($updset, 0, -1).' WHERE owner='.$uid;
}
else
{
$cols = 'owner,';
$vals = $uid.',';
foreach($tmp as $key => $data)
{
$cols .= $key.',';
$vals .= (is_numeric($data) ? trim($data) : "'".$data."'").',';
}
$updset = "INSERT INTO {$db_prefix}felblog_manager (".substr($cols, 0, -1).') VALUES ('.substr($vals, 0, -1).')';
}
db_query("$updset", __FILE__, __LINE__);
// set all content/comments as read if blog new
if(!$context['FelBlog']['Manager']['have_blog'])
{
$req = db_query("SELECT owner FROM {$db_prefix}felblog_manager", __FILE__, __LINE__);
while($row = mysql_fetch_row($req))
$user[] = $row[0];
mysql_free_result($req);
foreach($user as $u)
Mark_All_Read($u);
db_query("INSERT INTO {$db_prefix}felblog_cmnt_log
(owner, userID, contID, last_read)
SELECT c.owner, $ID_MEMBER, c.ID, max(m.ID)
FROM {$db_prefix}felblog_content as c
LEFT JOIN {$db_prefix}felblog_comments AS m ON (m.contID = c.ID)
WHERE m.ID IS NOT NULL
GROUP BY c.ID ORDER BY c.owner", __FILE__, __LINE__);
}
$rdir = str_replace('=upd', '', $_SERVER['QUERY_STRING']);
redirectexit($rdir);
}
// Remove the blog ?
elseif($context['FelBlog']['action'][1] == 'remove')
{
if((isOwner() && !isBlogLocked()) || AllowedTo('admin_forum'))
{
$request = db_query("SELECT ID FROM {$db_prefix}felblog_content WHERE owner=$uid", __FILE__, __LINE__);
if (mysql_num_rows($request) > 0)
{
while($row = mysql_fetch_assoc($request))
$tmpcont[] = $row['ID'];
// remove content
db_query("DELETE from {$db_prefix}felblog_content WHERE owner=$uid", __FILE__, __LINE__);
// remove comments
foreach($tmpcont as $cid)
db_query("DELETE from {$db_prefix}felblog_comments WHERE contID=$cid", __FILE__, __LINE__);
}
mysql_free_result($request);
// remove content log
db_query("DELETE from {$db_prefix}felblog_cont_log WHERE owner=$uid OR userID=$uid", __FILE__, __LINE__);
// remove comment log
db_query("DELETE from {$db_prefix}felblog_cmnt_log WHERE owner=$uid OR userID=$uid", __FILE__, __LINE__);
// remove tracking
$request = db_query("SELECT owner, tracking
FROM {$db_prefix}felblog_manager", __FILE__, __LINE__);
if (mysql_num_rows($request) > 0)
{
while($row = mysql_fetch_assoc($request))
$tmp[$row['owner']] = $row['tracking'];
foreach($tmp as $u => $v)
{
$tr = explode(':', $v);
if(isset($tr[1]))
{
$val = explode(',', $tr[1]);
if(in_array($uid, $val))
{
$val = array_diff($val, array($uid));
$ntr = $tr[0].':'.implode(',', $val);
db_query("UPDATE {$db_prefix}felblog_manager SET tracking='$ntr' WHERE owner=$u", __FILE__, __LINE__);
}
}
}
}
mysql_free_result($request);
// remove categories
db_query("DELETE from {$db_prefix}felblog_categories WHERE owner=$uid", __FILE__, __LINE__);
// remove ratings
db_query("DELETE from {$db_prefix}felblog_ratings WHERE owner=$uid", __FILE__, __LINE__);
// remove manager setting
db_query("DELETE from {$db_prefix}felblog_manager WHERE owner=$uid", __FILE__, __LINE__);
redirectexit('action=felblog;sa=list');
}
else
Felblog_Error($txt['fb_access_err_title'], $txt['fb_bloglocked_message'], $scripturl . '?action=felblog;sa=manager;set');
}
// Manage Categorie ?
elseif($context['FelBlog']['action'][1] == 'cat')
{
if((isOwner() && !isBlogLocked()) || AllowedTo('admin_forum'))
{
if(isset($_GET['upd']))
{
// update categories
foreach ($_POST as $what => $value)
$tmp[$what] = explode(chr(1), $value);
$upd = count($tmp['chgtype']);
for($i=0; $i < $upd; $i++)
{
$catname = stripslashes($tmp['name'][$i]);
$corder = $tmp['corder'][$i];
$depth = $tmp['depth'][$i];
$cid = $tmp['id'][$i];
if($tmp['chgtype'][$i] == 'update')
db_query("UPDATE {$db_prefix}felblog_categories
SET name = '$catname', corder = $corder, depth = $depth
WHERE owner = $uid AND ID = $cid", __FILE__, __LINE__);
elseif($tmp['chgtype'][$i] == 'insert')
db_query("INSERT INTO {$db_prefix}felblog_categories (owner, name, corder, depth)
VALUES($uid, '$catname', $corder, $depth)", __FILE__, __LINE__);
elseif($tmp['chgtype'][$i] == 'delete')
{
$request = db_query("SELECT ID FROM {$db_prefix}felblog_content
WHERE owner=$uid and categorie=$cid", __FILE__, __LINE__);
if($row = mysql_fetch_assoc($request))
{
$contID = $row['ID'];
db_query("UPDATE {$db_prefix}felblog_content
SET categorie = 0 WHERE ID = $contID AND owner = $uid)", __FILE__, __LINE__);
}
mysql_free_result($request);
db_query("DELETE FROM {$db_prefix}felblog_categories
WHERE owner = $uid AND ID = $cid", __FILE__, __LINE__);
}
}
$rdir = str_replace(';upd', '', $_SERVER['QUERY_STRING']);
redirectexit($rdir);
}
}
else
Felblog_Error($txt['fb_access_err_title'], $txt['fb_bloglocked_message'], $scripturl . '?action=felblog;sa=manager;set');
}
$context['page_title'] = $txt['fb_manager_settings_title'];
$context['FelBlog']['page_link'] = array(
'url' => $scripturl.'?'.$_SERVER['QUERY_STRING'],
'name' => $txt['fb_manager_settings_title']);
loadTemplate('FelBlogSettings');
$context['FelBlog']['setting_tabs'] = array(
'title' => $txt['fb_manager_settings_title'],
'tabs' => array(
'settings' => array(
'title' => $txt['fb_manager_setcom_title'],
'href' => $scripturl . '?action=felblog;sa=manager;set'.$context['FelBlog']['UserLink'],
'is_selected' => $context['FelBlog']['action'][1] == '',
'is_enabled' => true,
),
'categorie' => array(
'title' => $txt['fb_manager_setcat_title'],
'href' => $scripturl . '?action=felblog;sa=manager;set=cat'.$context['FelBlog']['UserLink'],
'is_selected' => $context['FelBlog']['action'][1] == 'cat',
'is_enabled' => $context['FelBlog']['Manager']['have_blog'] && (!isBlogLocked() || AllowedTo('admin_forum')),
),
'removeblog' => array(
'title' => $txt['fb_manager_remblog_title'],
'href' => $scripturl . '?action=felblog;sa=manager;set=delblog'.$context['FelBlog']['UserLink'],
'is_selected' => $context['FelBlog']['action'][1] == 'delblog',
'is_enabled' => $context['FelBlog']['Manager']['have_blog'] && (!isBlogLocked() || AllowedTo('admin_forum')),
),
),
);
}
?>

View File

@ -1,48 +0,0 @@
<?php
// ----------------------------------------------------------
// -- FelBlogTPinc.php --
// ----------------------------------------------------------
// -- Version: 0.94.0 for SMF 1.1.x --
// -- Copyright 2006,2007 by: Korinna "Feline" Brinkmann --
// -- Support and Updates at: http://feline-networks.com --
// ----------------------------------------------------------
if (!defined('SMF'))
die('Hacking attempt...');
global $context, $settings, $txt;
if(isset($context['FelBlog']) && $context['FelBlog']['loaded'])
{
echo '
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td width="2%" valign="top">
<img src="', $settings['default_images_url'] .'/felblog/blogstats.gif" alt="" style="padding-right:5px;" />
</td>
<td class="smalltext">
'. $context['FelBlog']['total_blogs'] . ($context['FelBlog']['total_blogs'] == 1 ? $txt['Felblog_stats-11'] : $txt['Felblog_stats-11']) . $context['FelBlog']['total_entries'] . ($context['FelBlog']['total_entries'] == 1 ? $txt['Felblog_stats-21'] : $txt['Felblog_stats-2']);
if(isset($context['FelBlog']['recent_blogs']))
{
echo '
<br />'.$txt['Felblog_recent'].'
</td>
</tr>
<tr>
<td colspan="2" class="smalltext">';
foreach($context['FelBlog']['recent_blogs'] as $rcb)
{
echo '
<hr />
<div style="vertical-align: top;">'. $rcb['conthref'] .'</div>
<div style="vertical-align:top;">'.$txt[525].' '.$rcb['owner'].'</div>
<div style="vertical-align:top;">'. str_replace(array('(', ')'), array('[', ']'), $rcb['created']).'</div>';
}
}
echo '
</td>
</tr>
</table>';
}
?>

View File

@ -1,25 +0,0 @@
----------------------------------------------------------
-- FelBlogTPinc.php --
----------------------------------------------------------
-- Version: 0.94.0 for SMF 1.1.x --
-- Copyright 2006,2007 by: Korinna "Feline" Brinkmann --
-- Support and Updates at: http://feline-networks.com --
----------------------------------------------------------
FelBlogTPinc.php is a small code, to add Blog statistics and
the recent list (as show in Info Center) in a TinyPortal Block.
To uses this, go to TinyPortal Admin and create a new PHP block.
Title it as "Blog stats" (or as you want).
In the body enter follow code:
global $sourcedir;
include_once($sourcedir.'/FelBlogTPinc.php');
(Try copy and paste, to prevent misspelling coding)
After you have save and enable your work, you can see the Blogstat.
Happy Blogging ;)
Fel

View File

@ -1,178 +0,0 @@
<?php
// -------------------------------------------------------------
// -- FelBlog_xhtml_lang.php (Languages for the xhtml editor) --
// -------------------------------------------------------------
// -- Version: 0.94.0 for SMF 1.1.x --
// -- Copyright 2006,2007 by: Korinna "Feline" Brinkmann --
// -- Support and Updates at: http://feline-networks.com --
// -------------------------------------------------------------
global $context;
$context['xhtml_langs'] = array(
'aa' => 'afar',
'ab' => 'abkhazian',
'af' => 'afrikaans',
'am' => 'amharic',
'ar' => 'arabic',
'as' => 'assamese',
'ay' => 'aymara',
'az' => 'azerbaijani',
'ba' => 'bashkir',
'be' => 'byelorussian',
'bg' => 'bulgarian',
'bh' => 'bihari',
'bi' => 'bislama',
'bn' => 'bengali',
'bo' => 'tibetan',
'br' => 'breton',
'ca' => 'catalan',
'co' => 'corsican',
'cs' => 'czech',
'cy' => 'welsh',
'da' => 'danish',
'de' => 'german',
'dz' => 'bhutani',
'el' => 'greek',
'en' => 'english',
'eo' => 'esperanto',
'es' => 'spanish',
'et' => 'estonian',
'eu' => 'basque',
'fa' => 'persian',
'fi' => 'finnish',
'fj' => 'fiji',
'fo' => 'faroese',
'fr' => 'french',
'fy' => 'frisian',
'ga' => 'irish',
'gd' => 'scots',
'gl' => 'galician',
'gn' => 'guarani',
'gu' => 'gujarati',
'ha' => 'hausa',
'he' => 'hebrew',
'hi' => 'hindi',
'hr' => 'croatian',
'hu' => 'hungarian',
'hy' => 'armenian',
'ia' => 'interlingua',
'id' => 'indonesian',
'ie' => 'interlingue',
'ik' => 'inupiak',
'is' => 'icelandic',
'it' => 'italian',
'iu' => 'inuktitut',
'ja' => 'japanese',
'jw' => 'javanese',
'ka' => 'georgian',
'kk' => 'kazakh',
'kl' => 'greenlandic',
'km' => 'cambodian',
'kn' => 'kannada',
'ko' => 'korean',
'ks' => 'kashmiri',
'ku' => 'kurdish',
'ky' => 'kirghiz',
'la' => 'latin',
'ln' => 'lingala',
'lo' => 'laothian',
'lt' => 'lithuanian',
'lv' => 'latvian',
'mg' => 'malagasy',
'mi' => 'maori',
'mk' => 'macedonian',
'ml' => 'malayalam',
'mn' => 'mongolian',
'mo' => 'moldavian',
'mr' => 'marathi',
'ms' => 'malay',
'mt' => 'maltese',
'my' => 'burmese',
'na' => 'nauru',
'ne' => 'nepali',
'nl' => 'dutch',
'no' => 'norwegian',
'oc' => 'occitan',
'om' => 'afan',
'or' => 'oriya',
'pa' => 'punjabi',
'pl' => 'polish',
'ps' => 'pashto',
'pt' => 'portuguese',
'qu' => 'quechua',
'rm' => 'rhaeto-romance',
'rn' => 'kirundi',
'ro' => 'romanian',
'ru' => 'russian',
'rw' => 'kinyarwanda',
'sa' => 'sanskrit',
'sd' => 'sindhi',
'sg' => 'sangho',
'sh' => 'serbo-croatian',
'si' => 'sinhalese',
'sk' => 'slovak',
'sl' => 'slovenian',
'sm' => 'samoan',
'sn' => 'shona',
'so' => 'somali',
'sq' => 'albanian',
'sr' => 'serbian',
'ss' => 'siswati',
'st' => 'sesotho',
'su' => 'sundanese',
'sv' => 'swedish',
'sw' => 'swahili',
'ta' => 'tamil',
'te' => 'telugu',
'tg' => 'tajik',
'th' => 'thai',
'ti' => 'tigrinya',
'tk' => 'turkmen',
'tl' => 'tagalog',
'tn' => 'setswana',
'to' => 'tonga',
'tr' => 'turkish',
'ts' => 'tsonga',
'tt' => 'tatar',
'tw' => 'twi',
'ug' => 'uighur',
'uk' => 'ukrainian',
'ur' => 'urdu',
'uz' => 'uzbek',
'vi' => 'vietnamese',
'vo' => 'volapuk',
'wo' => 'wolof',
'xh' => 'xhosa',
'yi' => 'yiddish',
'yo' => 'yoruba',
'za' => 'zhuang',
'zh' => 'chinese',
'zu' => 'zulu',
);

View File

@ -1,665 +0,0 @@
<?php
/******************************************************************************
* FileManager.php *
*******************************************************************************
* SMF: Simple Machines Forum - MOD *
* =========================================================================== *
* Software Version: 2.0 *
* Software by: A<>ron van Geffen *
* Updates: http://www.simplemachines.org *
******************************************************************************/
if (!defined('SMF'))
die('Hacking attempt...');
function FileManager()
{
global $protected, $scripturl, $db_prefix, $settings, $modSettings, $txt, $context, $boardurl, $boarddir, $folder;
// Make this mod only accessible for admins
isAllowedTo('admin_forum');
// Load the languagefile
loadLanguage('FileManager');
// Some template settings
$context['page_title'] = $txt['filemanager']['pagetitle'];
$context['template_layers'][] = 'filemanager';
loadTemplate('FileManager');
adminIndex('file_manager');
// Some settings
getFolder();
$context['start'] = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
$context['path'] = $boarddir . '/' . (!empty($folder) ? $folder . '/' : '');
// Protected files and folders. Only delete a file or folder from this array if you know what you're doing!
// The array will be used as a reference when renaming or deleting files/folders.
$protected = array('attachments', 'avatars', 'Packages', 'Smileys', 'Sources', 'Themes', 'Themes/default', 'Themes/default/languages', 'Themes/default/images', 'Themes/default/fonts', 'index.php', 'Settings.php', 'Settings_bak.php');
// Setup the tabs
// The basics
$context['admin_tabs'] = array(
'title' => $txt['filemanager']['pagetitle'],
'help' => null,
'description' => null,
'tabs' => array(),
);
// The actual tabs
$context['admin_tabs']['tabs'] = array(
'filemanager' => array(
'title' => $txt['filemanager']['tabindex'],
'description' => sprintf($txt['filemanager']['mainhelp'], $context['path']),
'href' => $scripturl . '?action=filemanager' . (!empty($folder) ? ';folder=' . $folder : ''),
'is_selected' => !isset($_REQUEST['sa']) || in_array((isset($_REQUEST['sa']) ? $_REQUEST['sa'] : ''), array('chmod', 'delete', 'rename')),
),
'newfolder' => array(
'title' => $txt['filemanager']['tabnewfolder'],
'description' => sprintf($txt['filemanager']['newfolderhelp'], $context['path']),
'href' => $scripturl . '?action=filemanager;sa=newfolder' . (!empty($folder) ? ';folder=' . $folder : ''),
'is_selected' => (isset($_REQUEST['sa']) ? $_REQUEST['sa'] : '') == 'newfolder',
),
'uploadfile' => array(
'title' => $txt['filemanager']['tabuploadfile'],
'description' => sprintf($txt['filemanager']['uploadfilehelp'], $context['path']),
'href' => $scripturl . '?action=filemanager;sa=uploadfile' . (!empty($folder) ? ';folder=' . $folder : ''),
'is_selected' => (isset($_REQUEST['sa']) ? $_REQUEST['sa'] : '') == 'uploadfile',
)
);
// Define the allowed subActions.
$subActions = array(
'index' => 'getIndex',
'uploadfile' => 'uploadFile',
'newfolder' => 'newFolder',
'delete' => 'delete',
'chmod' => 'chmodFileFolder',
'rename' => 'renameFileFolder',
'edit' => 'editFile',
);
// Default the sub-action to the file index
$_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'index';
$context['sub_action'] = $_REQUEST['sa'];
$context['sub_template'] = &$context['sub_action'];
// Call the right function for this sub-acton.
$subActions[$_REQUEST['sa']]();
}
// Generate the file index
function getIndex()
{
global $context, $boardurl, $scripturl, $folder, $files;
// Build the files and folders array
$context['files'] = array();
$context['folders'] = array();
$dir = dir('.');
while($entry = $dir->read())
{
// Skip the link to the current directory
if ($entry == '.')
continue;
// Gather basic information
$file = array();
$file['name'] = $entry;
$file['folder'] = is_dir($entry) == true ? 1 : 0;
$file['date'] = timeformat(@filemtime($entry));
$file['uponelevel'] = in_array($entry, array('.', '..')) == true ? 1 : 0;
$file['permissions'] = fileperms($entry);
$file['owner'] = fileowner($entry);
// Is this a folder?
if ($file['folder'])
{
if ($entry == '..')
{
// Link to parent directory, thus strip the last directory from the path
$pathArr = explode('/', $folder . '/');
$link = implode('/', array_slice($pathArr, 0, count($pathArr) - 2));
// If there is no folder left, don't add it to the link
if ($link == '')
{
// There's no $folder left, return a link without a folder parameter
if ($folder == '')
continue;
$file['link'] = $scripturl.'?action=filemanager';
}
else
{
// There's still a $folder left, return a link with a folder parameter
$link;
$file['link'] = $scripturl.'?action=filemanager;folder=' . urlEncode($link);
}
// There is no size...
$file['size'] = '';
// The icon representing the parent directory
$file['icon'] = 'parent';
// Flag it
$file['parent'] = true;
$file['folder'] = true;
}
else
{
// Go to a next folder, return a link with an extended folder parameter
$file['link'] = $scripturl.'?action=filemanager;folder=' . urlEncode((!empty($folder) ? $folder . '/' : '') . $file['name']);
// Get the amount of files inside the folder as well
$file['size'] = getDirSize($entry);
// The icon representing the directory
$file['icon'] = 'folder';
// Command links
$file['rename'] = $scripturl . '?action=filemanager;sa=rename;file=' . urlEncode((!empty($folder) ? $folder . '/' : '') . $file['name']);
$file['delete'] = $scripturl . '?action=filemanager;sa=delete;folder=' . urlEncode((!empty($folder) ? $folder . '/' : '') . $file['name']);
// We only need a CHMOD link when this isn't a Windows box
if (empty($_SERVER['WINDIR']))
$file['chmod'] = $scripturl . '?action=filemanager;sa=chmod;folder=' . urlEncode((!empty($folder) ? $folder . '/' : '') . $file['name']);
// Flag it
$file['folder'] = true;
}
}
else
{
// It's an ordinary file - link to it
$file['link'] = $boardurl . '/' . (!empty($folder) ? $folder . '/' : '') . rawurlencode($file['name']);
// And of course get the file size
$file['size'] = friendlyfilesize(@filesize($entry));
// The icon representing a file
$file['icon'] = 'file';
// Command links
$file['edit'] = $scripturl . '?action=filemanager;sa=edit;file=' . (!empty($folder) ? $folder . '/' : '') . rawurlencode($file['name']);
$file['rename'] = $scripturl . '?action=filemanager;sa=rename;file=' . (!empty($folder) ? $folder . '/' : '') . rawurlencode($file['name']);
$file['delete'] = $scripturl . '?action=filemanager;sa=delete;file=' . (!empty($folder) ? $folder . '/' : '') . rawurlencode($file['name']);
// We only need a CHMOD link when this isn't a Windows box
if (empty($_SERVER['WINDIR']))
$file['chmod'] = $scripturl . '?action=filemanager;sa=chmod;file=' . (!empty($folder) ? $folder . '/' : '') . rawurlencode($file['name']);
}
// Separate files and folders
if ($file['folder'] == true)
$context['folders'] = array_merge($context['folders'], array($entry => $file));
else
$context['files'] = array_merge($context['files'], array($entry => $file));
}
usort($context['folders'], 'compare');
usort($context['files'], 'compare');
$files = array_merge($context['folders'], $context['files']);
}
// Upload a file
function uploadFile()
{
global $txt, $context, $boarddir, $folder, $return;
if (isset($_FILES['uploadfile']))
{
// Make sure we got here in a legitimate way
checkSession('post');
// New name? Filter illegal characters in it.
if (!empty($_REQUEST['newname']))
$filename = str_replace(array('"', '\\', '/', ':', '*', '&', '?', '<', '>', '|', '@', '#', '%', '(', ')', '~', '$', ','), '', $_REQUEST['newname']);
// No filename set? Use a filtered copy of the original filename.
if (empty($filename))
$filename = str_replace(array('"', '\\', '/', ':', '*', '&', '?', '<', '>', '|', '@', '#', '%', '(', ')', '~', '$', ','), '', $_FILES['uploadfile']['name']);
// Now create a full path
$filename = $boarddir . '/' . (isset($folder) ? $folder . '/' : '') . $filename;
// Move the uploaded file to its appropriate location
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $filename))
{
@chmod($filename, 0666);
$return = sprintf($txt['filemanager']['uploadsuccessful'], $filename);
}
else
$return = $txt['filemanager']['uploadfailed'];
}
}
// Create a new folder
function newFolder()
{
global $boarddir, $txt, $folder, $foldername, $return;
if (isset($_REQUEST['foldername']))
{
// Make sure we got here in a legitimate way
checkSession('post');
$foldername = str_replace(array('"', '\\', '/', ':', '*', '&', '?', '<', '>', '|', '@', '#', '%', '(', ')', '~', '$', ','), '', $_REQUEST['foldername']);
if (!empty($foldername))
{
if (mkdir($boarddir . '/' . $folder . '/' . $foldername))
{
$return = $txt['filemanager']['foldercreatedsuccess'];
}
elseif (file_exists($boarddir . '/' . $folder . '/' . $foldername))
{
$return = $txt['filemanager']['folderalreadyexists'];
}
else
{
$return = $txt['filemanager']['foldererrorother'];
}
}
else
{
$return = $txt['filemanager']['folderinvalid'];
}
}
}
// Create or rename a file or folder
function renameFileFolder()
{
global $txt, $protected, $return;
// Is this file or folder protected? If so, show a note, but don't log it.
if (in_array($_REQUEST['file'], $protected))
fatal_error(sprintf($txt['filemanager']['protected'], $_REQUEST['file']), false);
// We've passed the test, do the renaming if applicable.
if (isset($_REQUEST['newname']) && isset($_REQUEST['oldname']))
{
// Make sure we got here in a legitimate way
checkSession('post');
if (rename($_REQUEST['oldname'], $_REQUEST['newname']))
{
$return = $txt['filemanager']['renamesuccess'];
}
else
{
$return = $txt['filemanager']['renamefailed'];
}
}
}
// Edit a file
function editFile()
{
global $txt, $protected, $return, $boarddir, $writable, $file, $contents;
// Determine the filename
if (!isset($_REQUEST['file']))
fatal_error($txt['filemanager']['editnofile'], false);
elseif (isset($_REQUEST['folder']))
$file = $boarddir . '/' . $_REQUEST['folder'] . '/' . $_REQUEST['file'];
else
$file = $boarddir . '/' . $_REQUEST['file'];
// Does this file actually exist?
$exists = file_exists($file);
if (!$exists)
fatal_error($txt['filemanager']['editnofile'], false);
// Is this file writable?
$writable = is_writable($file);
// Is this file or folder protected? If so, show a note, but don't log it.
if (in_array($_REQUEST['file'], $protected))
fatal_error(sprintf($txt['filemanager']['protected'], $_REQUEST['file']), false);
// Save the file when there's something submitted
if ($exists && $writable && isset($_POST['content']))
{
// Make sure we got here in a legitimate way
checkSession('post');
// Make sure we get rid of added slashes
$newContent = stripslashes($_POST['content']);
// Save it!
$open = fopen($file, 'w');
$done = fwrite($open, $newContent);
fclose($open);
// Show the user whether we succeeded or not
if ($done !== false)
$return = sprintf($txt['filemanager']['editsavesuccess'], $file);
else
$return = sprintf($txt['filemanager']['editsavefailed'], $file);
}
// Get the file's current contents
elseif ($exists && $writable)
{
$contents = htmlentities(file_get_contents($file));
}
}
// CHMOD a file or folder
function chmodFileFolder()
{
global $txt, $return;
// If we've entered a new permission value, convert it to octals
$permissions = isset($_REQUEST['newperms']) ? octdec($_REQUEST['newperms']) : 0;
if ($permissions != 0)
{
// Make sure we got here in a legitimate way
checkSession('post');
if (chmod($_REQUEST['what'], $permissions))
{
$return = $txt['filemanager']['chmodsuccess'];
}
else
{
$return = $txt['filemanager']['chmodfailure'];
}
}
}
// Delete a file or folder
function delete()
{
global $boarddir, $protected, $txt, $return;
// What are we attempting to delete?
if (isset($_REQUEST['folder']))
$deletewhat = $_REQUEST['folder'];
elseif (isset($_REQUEST['file']))
$deletewhat = $_REQUEST['file'];
// Is this file protected? If so, show a note, but don't log it.
if (in_array($deletewhat, $protected))
fatal_error(sprintf($txt['filemanager']['protected'], $deletewhat), false);
// Okay, delete it, but only if we're really sure!
if (isset($_REQUEST['sure']))
{
// Make sure we got here in a legitimate way
checkSession('post');
// Deleting a folder, are we?
if (isset($_REQUEST['folder']))
{
deletefolder($boarddir . '/' . $_REQUEST['folder']);
}
// No? A file then?
elseif (isset($_REQUEST['file']))
{
$deletewhat = $boarddir . '/' . $_REQUEST['file'];
// Does it actually exist?
if (file_exists($deletewhat))
{
// Can we delete it, and are we sure it's not a dir?
if (is_writable($deletewhat) && !is_dir($deletewhat))
{
@unlink($deletewhat);
$return = sprintf($txt['filemanager']['deletesuccessful'], $deletewhat);
}
// We can't delete it.
else
{
$return = sprintf($txt['filemanager']['deletefailure'], $deletewhat);
}
}
// It doesn't even exist! We're being cheated!
else
{
$return = sprintf($txt['filemanager']['deletedoesntexist'], $deletewhat);
}
}
}
}
// ===============================
// MINOR, SUPPORTING FUNCTIONS
// ===============================
// Sorts the names of files and folders
function compare($array1, $array2)
{
$a = $array1['name'];
$b = $array2['name'];
// Is this a parent folder?
if (isset($array1['parent']))
return -1;
if (isset($array2['parent']))
return 1;
// Folders should appear at the top
if (isset($array1['folder']) != isset($array2['folder']))
{
$result = isset($array2['folder']) - isset($array1['folder']);
}
// We're comparing the names of two folders or two files
else
{
$a = strtolower($a);
$b = strtolower($b);
$result = strcoll($a, $b);
}
return $result;
}
// Create a more user friendly filesize
function friendlyfilesize($size)
{
static $sizeUnits = array();
if (count($sizeUnits) == 0)
{
$sizeUnits[] = 'bytes';
$sizeUnits[] = 'kB';
$sizeUnits[] = 'MB';
$sizeUnits[] = 'GB';
$sizeUnits[] = 'TB';
}
if ($size === '')
return '';
$unitIndex = 0;
while ($size > 1024.0)
{
$size = $size / 1024.0;
$unitIndex ++;
}
if ($unitIndex == 0)
return number_format($size, 0) . '&nbsp;' . $sizeUnits[$unitIndex];
else
return number_format($size, 1, '.', ',') . '&nbsp;' . $sizeUnits[$unitIndex];
}
// Get the size of a directory
function getDirSize($dirname)
{
global $txt;
$dir = dir($dirname);
$fileCount = 0;
while ($filename = $dir->read())
$fileCount++;
// We don't want to count [.] and [..]
return ($fileCount - 2) . ' ' . ($fileCount != 1 ? $txt['filemanager']['items'] : $txt['filemanager']['item']);
}
// Retrieves the folder from the query string, and checks whether it's safe or not.
function getFolder()
{
global $boarddir, $folder, $txt;
// Extract $folder from the GET array
$folder = (isset($_REQUEST['folder']) ? $_REQUEST['folder'] : '');
// Is the directory in $folder a safe one?
$result = $folder;
if (strpos($folder, '..') !== false)
$result = '';
if (substr($folder, 0, 1) == '/')
$result = '';
if ($result != $folder)
fatal_error(sprintf($txt['filemanager']['invalid_dir'], $folder), false);
// Change directory if possible
if (isset($folder))
{
if (!@chdir($boarddir.'/'.$folder))
{
chdir($boarddir);
$folder = '';
}
}
}
// Deletes a folder
function deletefolder($path)
{
global $txt, $return;
// First we'll have to delete the folder
if (emptyfolder($path))
{
if (@rmdir($path))
{
// Deleted the folder succesfully
$return .= '<b>' . sprintf($txt['filemanager']['delfolder']['mapverwijderd'], $path) . '</b><br>';
}
else
{
// Folder couldn't be deleted :(
$return .= '<b>' . sprintf($txt['filemanager']['delfolder']['mapverwfout'], $path) . '</b><br>';
}
}
else
{
// Folder isn't empty, and thus cannot be deleted
$return .= '<b>' . sprintf($txt['filemanager']['delfolder']['mapnietleeg'], $path) . '</b><br>';
}
}
// Emptys a folder completely (help function of deletefolder())
function emptyfolder($path)
{
global $return, $txt;
// Show we're starting
$return .= '
<b>' . sprintf($txt['filemanager']['delfolder']['beginlegen'], $path) . '</b><br />';
// Let's truncate this folder!
if ($dir_handle = @opendir($path))
{
$return .= '
<ul>';
while ($file = @readdir($dir_handle))
{
// Delete file
if ($file != '.' && $file != '..' && !is_dir($path . '/' . $file))
{
$return .= '
<li>' . sprintf($txt['filemanager']['delfolder']['verwbestand'], $path . '/' . $file) . '</li>';
@unlink($path . '/' . $file);
}
// Delete folder
elseif ($file != '.' && $file != '..' && is_dir($path . '/' . $file))
{
$return .= '
<li>
' . sprintf($txt['filemanager']['delfolder']['submapgevonden'], $path . '/' . $file) . '<br />';
deletefolder($path . '/' . $file);
$return .= '
</li>';
}
}
@closedir($dir_handle);
$return .= '
</ul>
<b>' . sprintf($txt['filemanager']['delfolder']['legenklaar'], $path) . '</b><br />';
// All files were deleted successfully.
return true;
}
else
{
// Folder doesn't exist? What the crap?
$return .= '
<b>' . $txt['filemanager']['delfolder']['bestaatniet'] . '</b><br />';
return false;
}
}
// This function builds the page index
function getPageLinks()
{
global $context, $scripturl, $txt, $folder;
// Some variables. Variables are good.
$context['filemanager']['usePaging'] = 30;
$context['filemanager']['pageStart'] = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
$context['filemanager']['pageEnd'] = min((count($context['files']) + count($context['folders'])), $context['filemanager']['pageStart'] + $context['filemanager']['usePaging']);
$context['filemanager']['numberOfPages'] = ceil((count($context['files']) + count($context['folders'])) / $context['filemanager']['usePaging']);
$context['filemanager']['currentPage'] = floor($context['filemanager']['pageStart'] / $context['filemanager']['usePaging']);
// Initialise pages
static $displayPages = Array();
if (count($displayPages) == 0)
{
$displayPages[] = 0;
for ($i = $context['filemanager']['currentPage'] - 1; $i < $context['filemanager']['currentPage'] + 3; $i++)
{
if ($i >= 0 && $i < $context['filemanager']['numberOfPages'])
{
$displayPages[] = $i;
}
}
$displayPages[] = $context['filemanager']['numberOfPages'] - 1;
$displayPages = array_unique($displayPages);
}
// Initialize paging variable
$header = '';
// Build a link for each page
foreach($displayPages as $i => $pageNumber)
{
// Should we hide some numbers?
if (($pageNumber > 1) && ($pageNumber - $displayPages[$i - 1] > 1))
{
$header .= '... ';
}
// Is this the current page?
if ($pageNumber == $context['filemanager']['currentPage'])
{
$header .= '[' . ($pageNumber + 1) . ']&nbsp;';
}
// Nope, it's just a regular page
else
{
$header .= '<a href="' . $scripturl . '?action=filemanager;folder=' . $folder . ';start=' .($pageNumber * $context['filemanager']['usePaging']) . '">' . ($pageNumber + 1) . '</a>&nbsp;';;
}
}
return $header;
}
?>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More