First revision of FlatPress Crescendo+1 ( 0.703+n :) )

This commit is contained in:
real_nowhereman 2007-10-30 10:30:07 +00:00
commit a68630bf35
403 changed files with 48083 additions and 0 deletions

80
CHANGELOG Normal file
View File

@ -0,0 +1,80 @@
0703.1 Crescendo (July 10, 2007)
===============================
Small bug fixes
FIXED: bbcode: [u] tag missing
FIXED: bbcode/syntaxhighlighter: [code=MY_SYNTAX] works again
FIXED: fixed error handling with missing categories
0.703 Crescendo Final (June 27, 2007)
=====================================
UPDATED: jsUtils : Mootools 1.11
FIXED: URL issues with BBCODE
FIXED: small issues with thumb plugin
Crescendo RC2 (June 3, 2007)
============================
FIXED: spaces in file names are escaped as dashes "-" when uploaded
FIXED: various bbcode issues
FIXED: scale/width bbcode/thumb issues
MDFD: now thumb creates a .thumb dir for each subdir of images/
FIXED: leggero CSS
FIXED: double entity encoding
ADDED: (since RC1): when loggedin trying to open a non-existent
static page will bring you to the "add new static" panel
Crescendo RC1 (May 29, 2007)
============================
FIXED: plugin/bbcode: broken non-local urls
FIXED: core/FPDB archive function: /?y=nn didn't work if a month wasn't specified
FIXED: core/entry/cache : buggy workarounded function (see previous) is now fixed
FIXED: core/users : session was not kept if user IP changed
FIXED: core/rss : template now works, fixed core accordingly
ADDED: core/rss : full content support
UPDATED: plugin/jsUtils, upgraded to mootools 1.1
UPDATED: plugin/lightbox updated accordingly to slimbox 1.4
RMVD: temporarily removed prettyurls plugin
(todo: remove from default config);
I'm working to a newer cooler version, but
it will require probably some changes in core, so no-go for this
release
ADDED: Lang/it-it: added some strings I forgot
Crescendo beta1 (May 17, 2007)
============================
added: some entry/cache hooks
added: many plugin translations thanx to cimangi (http://luielei.altervista.org/)
added: panel notifications for plugins
added: new theme, new icons (updated old admin css)
fixed: lightbox updated and fixed
fixed: removed quote escaping in entries (removed and added fix for old versions)
fixed: directory deletion under php5 (thx cimangi)
fixed: entry_delete did not remove visit counter (cimangi)
fixed: session retaining in control panel under certain conditions (smartyvalidate)
changed: some behaviours in cache; need some rework as introduced a little bug... d'oh!
Crescendo alpha
===============
fixed: utils_mail()
fixed: bbcode url trim
fixed: bbcode remote image timeouts
changed: WHOLE new POST behaviour (no longer "POSTDATA" messages)
changed: new theme tags (almost finished). support for old themes; soon deprecated
changed: graphics for the old theme (almost finished)
changed: a whole bunch of graphic thingies
changed: plugin organization
added: [video] tag support http://flatpress.nowhereland.it/index.php?entry=entry070210-211548
added: update checker (experimental)
added: error/success notification system with fancy graphics :P
NOTE: italian language is still there until the wiki is ready

300
COPYING Executable file
View File

@ -0,0 +1,300 @@
FlatPress, flat-file based blog platform
Copyright (C) 2006 Edoardo Vacchi (NoWhereMan)
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 St, Fifth Floor, Boston, MA 02110-1301 USA
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin St, 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 Library 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

132
README Executable file
View File

@ -0,0 +1,132 @@
FLATPRESS README (or "the file that nobody reads except who writes") (draft 1)
==============================================================================
## 1. WHAT THE FLATPRESS?
First of all, let me thank you for choosing my FlatPress. I hope you'll
enjoy using it as I (almost) enjoyed writing it :)
FlatPress is a brand new blogging platform under heavy development.
Now, you may be like: «Another blog?? Who the heck would need that?».
## 2. WHO THE HECK NEED THAT?
Oh-kay, FP is flat-file based. This means *it doesn't require databases*.
Actually all the content in stored in text files, so you don't need
MySQL if you can't afford an hosting service which can provide that to you.
## 3. COOL. I STILL DON'T SEE WHY I SHOULD USE IT
«...as I could use SimplePHPBlog, Pivot, etc...».
Good question. FlatPress was born as an extension to SPB.
But let's clear the things out
1. This is not a _fork_: we didn't take the SPB code and edited it;
2. This is not a rewrite: we didn't take SPB concept and reinvented its wheel
This is a *new* project, which inherits from SPB just its *storing system*.
This means you can take your content/, images/ dirs from your SPB installation,
put them in FP's fp-content/ dir as they are, and, once installed, it should
almost work out-of-the-box. This is the aim.
Note that we don't want every single SPB user to switch to FP, it's just
that, as a SPB user myself, I wanted an easy way to switch from that to my project
and by the way its storing system is not bad at all :)
## 4. IF IT'S NOT THAT BAD, WHY THIS REWRITE?
As I said, this *IS NOT* a rewrite. This is a new blog.
At the time we (I) started this project SPB lacked some features, it
wasn't W3C standard-compliant and, above all, it was obviously a pain
to upgrade if you had made many changes to the code.
So the most important lacks were a plugin system and a little more
flexible theming engine.
FlatPress uses the same plugin system of WordPress.
Beware: this doesn't mean you will be able to use any of the WordPress
plugins without any effort. Only a few of the plugin "hooks" have been
implemented (search the sources for apply_filters and do_action to know which ones).
Also FlatPress uses the famous Smarty template engine for the themes (the
same of PhpBB).
Of course, this now will sound great (and quite conceited), then remember
1. This is my first complete work in PHP
2. It's unfinished :)
## 5. ANYWAY, IT SOUNDS PRETTY DECENT, HOW DO I GET IT TO WORK?
OK, let's see what it will take you to run the fruit of my sweat
(sounds juicy, doesn't it? Yech!).
A basic Apache+PHP system as a server should work. It has been small tested on IIS,
too. If you experience any problem, just let me know (be detailed describing the problem).
As I said, no need for databases. Anyway I must ask for a
version of PHP >= 4.3.0. I can't tell if it will work on older versions
so if it something is going wrong, first check this :)
Unpack the .tar.bz2 you downloaded from the main site (probably
http://flatpress.nowhereland.it/) and http://flatpress.nowhereland.it/downloads/)
and then upload it on your webserver (or test it locally).
Point your browser to http://yoursite.com/flatpress/ and just follow
*carefully* the istructions :p
## 6. FINAL WARNING AND GOODBYE
This you're using (or you're about to use) is intended as a TEST version;
it should be very stable, but it if it ever blew your PC up, just
remember you'd been told.
Kidding.
People tell me I'm quite unprofessional presenting this project.
You'll see why when you'll install FlatPress for the first time...
If that won't make your day, I just hope to make you smile :)
Once you're ready tell us what you think on the main site; any
feedback is appreciated!
## CREDITS
I want to thank here some people that helped (and are helping) me with
this project.
Hydra, betatester, small-coder, and official cheerleader :D
drudo, theme designer, supporter, space and time provider
Other thanks to giulio and alcor for their precious advice.
As an additional note, I'd like to thank also Tychondriax
another friend of mine who occasionally helps me with betasting
and bug-discovering :)
Thank you all, guys, without you I would have already given up.
Edoardo Vacchi (NoWhereMan), August, 2 2006
email: real_nowhereman at users dot sf dot net
www: http://www.nowhereland.it
flatpress home: http://flatpress.nowhereland.it

1
TESTING Executable file
View File

@ -0,0 +1 @@
This is a test version and it's not intended for production.

8
admin.php Executable file
View File

@ -0,0 +1,8 @@
<?php
require_once 'defaults.php';
require_once (INCLUDES_DIR.'includes.php');
require 'admin/main.php'
?>

33
admin/admin-inline.tpl Normal file
View File

@ -0,0 +1,33 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>{$flatpress.title}{$pagetitle}</title>
<meta http-equiv="Content-Type" content="text/html; charset={$flatpress.CHARSET}" />
{action hook=wp_head}
</head>
<body id="inline-body">
{if $submenu}
<ul id="admin-submenu">
{foreach from=$submenu key=subtab item=item}
{if $item}
<li>
{if $actionname != $subtab}
<a href="{$smarty.const.BLOG_BASEURL}admin.php?p={$panelname}&amp;action={$subtab}&mod=inline">
{$lang.admin[$panel].submenu[$subtab]|default:$subtab}
</a>
{else}
<strong>{$lang.admin[$panel].submenu[$subtab]|default:$subtab}</strong>
{/if}
</li>
{/if}
{/foreach}
</ul>
{/if}
{include file=$admin_resource|default:"admin:$panel/$action"}
</body>
</html>

BIN
admin/imgs/config.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

BIN
admin/imgs/entries.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

BIN
admin/imgs/maintain.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

BIN
admin/imgs/newentry.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

BIN
admin/imgs/plugins.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 547 B

BIN
admin/imgs/widgets.png Executable file

Binary file not shown.

After

Width:  |  Height:  |  Size: 981 B

View File

@ -0,0 +1,251 @@
<?php
define('PANEL_NOREDIRECT', 0);
define('PANEL_REDIRECT_DEFAULT', 1);
define('PANEL_REDIRECT_CURRENT', 2);
/*
*
* GLOBALS: var $action string contains name of current panel action
*
*/
class AdminPanel {
var $panelname = null;
var $smarty = null;
var $actions = array('default'=>false);
var $defaultaction = 'default';
var $actionpanel = null;
function AdminPanel(&$smarty) {
$this->smarty =& $smarty;
if (!$this->panelname)
trigger_error("Variable \$panelname is not defined!", E_USER_ERROR);
/* get plugin panels */
$plugactions = admin_getpanelactions($this->panelname);
/* add plugged actions to system-defined */
$this->actions = array_merge($this->actions, $plugactions);
/* if # actions > 1 we won't show it in the submenu bar */
/* this is just for aesthetics ;) */
if ((count($this->actions) > 1) && in_array(true, $this->actions))
$this->smarty->assign('submenu', $this->actions);
}
function &get_action(&$action) {
if (!$action)
$action = $this->defaultaction;
$obj = null;
if (!isset($this->actions[$action])) {
// trigger_error("$action:
// No such an action was defined", E_USER_ERROR);
$action = $this->defaultaction;
}
$this->smarty->assign('actionname', $action);
$class = get_class($this) . "_$action";
if (!class_exists($class)) {
$f = str_replace('_','.',$class);
$fname = ADMIN_DIR . "panels/{$this->panelname}/$f.php";
if (file_exists($fname)) {
include($fname);
if (!class_exists($class)) {
trigger_error("No classes for action $action.", E_USER_ERROR);
}
$obj =& new $class($this->smarty);
return $obj;
} else trigger_error("No script found for action $action", E_USER_ERROR);
} else {
$obj =& new $class($this->smarty);
}
return $obj;
}
}
class AdminPanelAction {
var $actionname = null;
var $smarty = null;
var $events = array();
var $commands = array();
var $langres = '';
function AdminPanelAction(&$smarty) {
$this->smarty =& $smarty;
$the_action_panel = get_class($this);
$this->smarty->assign('admin_panel_id', $the_action_panel);
if (!$this->langres)
$this->langres = 'admin.' . ADMIN_PANEL ;
}
function exec() {
$this->setup();
$result = 0; // if !=0, defaultaction for this panel is called
if (empty($_POST)) {
if ($this->commands) {
foreach($this->commands as $cmd) {
if (isset($_GET[ $cmd ])) {
return $this->docommand($cmd, $_GET[ $cmd ]);
}
}
}
$result = $this->main();
lang_load($this->langres);
} else {
$result = $this->onsubmit();
}
return $result;
}
function setup() {
}
function main() {
return 0;
}
/**
* Method onsubmit <br />
*
* @return int values:
* 1. if you want main() method to be called;
* 2. if you want main() method of the defaultaction
* 0. if you don't want any further action to be called
*
*/
function onsubmit() {
$returnvalue = 1;
$valid_evts = array_intersect(array_keys($_POST), $this->events);
if ($the_event=array_pop($valid_evts)) {
$event = "on{$the_event}";
if (method_exists($this, $event))
$returnvalue = call_user_func(array(&$this, $event));
}
return $returnvalue;
}
function docommand($the_cmd, $the_val) {
global $panel, $action;
check_admin_referer("admin_{$panel}_{$action}_{$the_cmd}_{$the_val}");
$cmd = "do{$the_cmd}";
if (method_exists($this, $cmd))
return call_user_func(array(&$this, $cmd), $the_val);
return 1;
}
}
class AdminPanelActionValidated extends AdminPanelAction {
var $validators = array();
function exec() {
if (empty($_POST))
SmartyValidate::disconnect($this->smarty);
$form_id = get_class($this);
SmartyValidate::connect($this->smarty);
if (!SmartyValidate::is_registered_form($form_id))
SmartyValidate::register_form($form_id);
$this->setup();
$retval = 0;
if (empty($_POST)) {
if ($validators =& $this->validators) {
foreach ($validators as $validator) {
$validator[6]=$form_id;
call_user_func_array(array('SmartyValidate', 'register_validator'), $validator);
}
}
if ($this->commands) {
foreach($this->commands as $cmd) {
if (isset($_GET[ $cmd ])) {
return $this->docommand($cmd);
}
}
}
lang_load($this->langres);
$retval = $this->main();
} else {
$retval = $this->onsubmit();
}
return $retval;
}
function onsubmit() {
$result = 0;
if(SmartyValidate::is_valid($_POST, get_class($this))) {
$result = parent::onsubmit();
} else $result = $this->onerror();
return $result;
}
function onerror() {
return true;
}
}
?>

20
admin/index.php Executable file
View File

@ -0,0 +1,20 @@
<?php
//require_once('../init.php');
//utils_redirect('../admin.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>FlatPress</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Not Authorized</h1>
<p>You're not allowed to browse this folder.</p>
<p>Back to <a href="..">home page</a>.</p>
</body>
</html>

193
admin/main.php Executable file
View File

@ -0,0 +1,193 @@
<?php
// aggiungere nuovo protocollo per template
include(ADMIN_DIR.'panels/admin.defaultpanels.php');
include(ADMIN_DIR.'includes/panels.prototypes.php');
require(SMARTY_DIR . 'SmartyValidate.class.php');
utils_nocache_headers();
define('MOD_ADMIN_PANEL',1);
function wp_nonce_ays() {
die('We apologize, an error occurred.');
}
/*
function admin_is_user_loggedin() {
return ($u=user_loggedin()) && utils_checkreferer() ;
}
*/
function main() {
// general setup
global $panel, $action, $lang, $smarty, $fp_admin, $fp_admin_action;
$panels = admin_getpanels();
$panel = (isset($_GET['p']))? $_GET['p'] : $panels[0];
define('ADMIN_PANEL', $panel);
$smarty->assign('panel', $panel);
if (!admin_panelexists($panel))
trigger_error('Requested panel does not exists!', E_USER_ERROR);
$panelprefix = "admin.$panel";
$panelpath = ADMIN_DIR."panels/$panel/$panelprefix.php";
$fp_admin = null;
if (file_exists($panelpath)) {
include($panelpath);
$panelclass = "admin_$panel";
if (!class_exists($panelclass))
trigger_error("No class defined for requested panel", E_USER_ERROR);
$fp_admin =& new $panelclass($smarty);
}
$action = isset($_GET['action'])? $_GET['action'] : 'default';
if (!$fp_admin)
return;
$fp_admin_action =& $fp_admin->get_action($action);
define('ADMIN_PANEL_ACTION', $action);
$smarty->assign('action', $action);
$panel_url = BLOG_BASEURL . "admin.php?p={$panel}";
$action_url = $panel_url . "&action={$action}";
$smarty->assign('panel_url', $panel_url);
$smarty->assign('action_url', $action_url);
/* check if user is loggedin */
if (!user_loggedin()) {
utils_redirect("login.php");
die();
}
if (!empty($_POST))
check_admin_referer("admin_{$panel}_{$action}");
$smarty->assign('success', sess_remove("success_{$panel}"));
$retval = $fp_admin_action->exec();
if ($retval > 0) {
// clear postdata by a redirect
sess_add("success_{$panel}", $smarty->get_template_vars('success'));
$smarty->get_template_vars('success');
$to_action = $retval > 1 ? ('&action=' . $action) : '';
$with_mod = isset($_GET['mod'])? ('&mod=' . $_GET['mod']) : '';
utils_redirect("admin.php?p={$panel}{$to_action}{$with_mod}");
}
$smarty->register_modifier('action_link', 'admin_filter_action');
$smarty->register_modifier('cmd_link', 'admin_filter_command');
}
function admin_filter_action($string, $action) {
if (strpos($string, '?')===false)
return $string .= "?action={$action}";
else
return $string .= wp_specialchars("&action={$action}");
}
function admin_filter_command($string, $cmd, $val) {
global $panel, $action;
$arg = $cmd? "&{$cmd}" : $cmd;
return wp_nonce_url("{$string}{$arg}={$val}", "admin_{$panel}_{$action}_{$cmd}_{$val}");
}
function admin_panelstrings($panelprefix) {
global $lang, $smarty;
lang_load('admin');
lang_load($panelprefix);
$smarty->assign('subject', $lang['admin']['head']);
$smarty->assign('menubar', admin_getpanels());
add_filter('wp_title', 'admin_panel_title', 10, 2);
}
function admin_panel_title($title, $sep) {
global $lang, $panel;
$t = @$lang['admin']['panels'][$panel];
$title = "$title $sep $t";
return $title;
}
function showcontrolpanel($params, &$smarty) {
$smarty->display(ABS_PATH. ADMIN_DIR . 'main.tpl');
}
// html header
function admin_title($title, $sep) {
global $lang;
return $title = "$title $sep {$lang['admin']['head']}";
}
add_filter('wp_title', 'admin_title', 10, 2);
$fp_config = config_load();
system_init();
main();
admin_panelstrings('admin.'.ADMIN_PANEL);
theme_init($smarty);
$smarty->register_function('controlpanel', 'showcontrolpanel');
$v =& $lang['admin'][$panel][$action];
$smarty->assign_by_ref('panelstrings', $v);
$smarty->assign_by_ref('plang', $v);
if (isset($_GET['mod'])) {
switch ($_GET['mod']) {
case 'inline' :
$smarty->display(ABS_PATH . ADMIN_DIR . 'admin-inline.tpl');
break;
case 'ajax' :
echo $smarty->get_template_vars('success');
}
} else {
$smarty->display('admin.tpl');
}
?>

39
admin/main.tpl Executable file
View File

@ -0,0 +1,39 @@
<ul id="admin-tabmenu">
{foreach from=$menubar item=tab}
{if $tab eq $panel}
<li>
<a id="admin-tab-current" href="{$smarty.const.BLOG_BASEURL}admin.php?p={$tab}">
{$lang.admin.panels[$tab]|default:$tab}
</a>
</li>
{else}
<li>
<a href="{$smarty.const.BLOG_BASEURL}admin.php?p={$tab}">
{$lang.admin.panels[$tab]|default:$tab}
</a>
</li>
{/if}
{/foreach}
</ul>
{if $submenu}
<ul id="admin-submenu">
{foreach from=$submenu key=subtab item=item}
{if $item}
<li>
<a {if $action == $subtab}class="active" {/if}
href="{$smarty.const.BLOG_BASEURL}admin.php?p={$panel}&amp;action={$subtab}">
{$lang.admin[$panel].submenu[$subtab]|default:$subtab}
</a>
</li>
{/if}
{/foreach}
</ul>
{/if}
<div id="admin-content">
{include file=$admin_resource|default:"admin:$panel/$action"}
</div>

View File

@ -0,0 +1,24 @@
<?php
admin_addpanel('main');
admin_addpanel('entry');
admin_addpanel('static');
admin_addpanel('uploader');
admin_addpanel('widgets');
//admin_addpanel('users');
admin_addpanel('plugin' );
admin_addpanel('themes');
admin_addpanel('config');
admin_addpanel('maintain');
?>

View File

@ -0,0 +1,115 @@
<?php
class admin_config extends AdminPanel {
var $panelname = 'config';
}
class admin_config_default extends AdminPanelActionValidated {
var $validators = array(
// not needed anymore !
// array('blog_root', 'blog_root', 'notEmpty', false, false, 'trim'),
array('www', 'www', 'notEmpty', false, false, 'trim'),
// ...
array('title', 'title', 'notEmpty', false, false, 'trim'),
//array('subtitle', 'subtitle', 'notEmpty', false, false, 'trim'),
//array('blogfooter', 'blogfooter', 'notEmpty', false, false, 'trim'),
array('email', 'email', 'isEmail', false, false, 'trim'),
array('maxentries', 'maxentries', 'isInt', false, false, 'trim'),
array('timeoffset', 'timeoffset', 'isNumber', false, false, 'trim'),
array('timeformat', 'timeformat', 'notEmpty', false, false, 'trim'),
array('dateformat', 'dateformat', 'notEmpty', false, false, 'trim'),
array('lang', 'lang', 'notEmpty', false, false, 'trim'),
array('charset', 'charset', 'notEmpty', false, false, 'trim'),
);
var $events = array('save');
function setup() {
$this->smarty->assign('themes', theme_list());
$this->smarty->assign('lang_list', lang_list());
$static_list = array();
foreach(static_getlist() as $id) {
$static_list[$id] = static_parse($id);
}
$this->smarty->assign('static_list', $static_list);
}
function onsave() {
global $fp_config;
$l = explode(',',$_POST['lang']);
$fp_config['general'] = array(
//'BLOG_ROOT' => $_POST['blog_root'],
'www' => $_POST['www'],
'title' => html_entity_decode(stripslashes($_POST['title'])),
'subtitle' => html_entity_decode(stripslashes($_POST['subtitle'])),
'footer' => html_entity_decode(stripslashes($_POST['blogfooter'])),
'author' => $_POST['author'],
'email' => $_POST['email'],
'startpage' => ($_POST['startpage'] == ':NULL:')? null : $_POST['startpage'],
'maxentries' => $_POST['maxentries'],
// 'voting' => $_POST['voting'],
'notify' => isset($_POST['notify']),
/* preserve the following */
'theme' => $fp_config['general']['theme'],
'style' => @$fp_config['general']['style'],
'blogid' => $fp_config['general']['blogid'],
'lang' => 'en-us',
'charset'=> 'utf-8',
);
$fp_config['locale'] = array(
'timeoffset' => $_POST['timeoffset'],
'timeformat' => $_POST['timeformat'],
'dateformat' => $_POST['dateformat'],
'charset' => $_POST['charset'],
'lang' => $_POST['lang']
);
// 'LANG' => $l[0],
// 'CHARSET'=> $l[1],
$success = config_save()? 1: -1;
$this->smarty->assign('success', $success);
return 1;
}
function onerror() {
$this->main();
return 0;
}
function cleartplcache() {
// if theme was switched, clear tpl cache
$tpl =& new tpl_deleter();
$tpl->getList();
}
}
?>

View File

@ -0,0 +1,147 @@
{validate_init form=$admin_panel_id}
{validate id="www" message=$panelstrings.error.www append="error"}
{validate id="title" message=$panelstrings.error.title append="error"}
{validate id="email" message=$panelstrings.error.email append="error"}
{validate id="maxentries" message=$panelstrings.error.maxentries append="error"}
{validate id="timeoffset" message=$panelstrings.error.maxentries append="error"}
{validate id="timeformat" message=$panelstrings.error.maxentries append="error"}
{validate id="dateformat" message=$panelstrings.error.maxentries append="error"}
{validate id="lang" message=$panelstrings.error.maxentries append="error"}
{validate id="charset" message=$panelstrings.error.maxentries append="error"}
{include file='shared:errorlist.tpl'}
{html_form}
<div id="admin-config">
<div id="admin-config-general">
<h2> {$panelstrings.gensetts} </h2>
<dl>
<dt><label for="title"> {$panelstrings.blogtitle} </label></dt>
<dd><input type="text" name="title" id="title" class="textinput{$error.title|notempty:' field-error'}"
value="{$flatpress.TITLE|escape:"html"}" />
</dd>
<dt><label for="subtitle"> {$panelstrings.blogsubtitle} </label></dt>
<dd><input type="text" name="subtitle" id="subtitle" class="bigtextinput" value="{$flatpress.subtitle|escape:"html"}" /></dd>
<dt><label for="blogfooter"> {$panelstrings.blogfooter} </label></dt>
<dd><input type="text" name="blogfooter" id="blogfooter" class="textinput" value="{$flatpress.footer|escape:"html"}" /></dd>
<dt><label for="author"> {$panelstrings.blogauthor} </label></dt>
<dd><input type="text" name="author" id="author" class="textinput" value="{$flatpress.author}" /></dd>
<dt><label for="www"> {$panelstrings.blogurl} </label></dt>
<dd><input type="text" name="www" id="www" class="textinput{$error.www|notempty:" field-error"}"
value="{$flatpress.www|escape:"html"}" /></dd>
<dt><label for="email"> {$panelstrings.blogemail} </label></dt>
<dd><input type="text" name="email" id="email" class="textinput{$error.email|notempty:" field-error"}"
value="{$flatpress.email}" /></dd>
<dt> {$panelstrings.notifications} </dt>
<dd>
<label for="notify">
<input type="checkbox" name="notify" id="notify"{if $flatpress.NOTIFY}checked="checked"{/if} />
{$panelstrings.mailnotify}
</label>
</dd>
<dt><label for="startpage"> {$panelstrings.startpage} </label></dt>
<dd><select name="startpage" id="startpage" class="textinput">
<option value=":NULL:">
{$panelstrings.stdstartpage}
</option>
{foreach from=$static_list key=staticid item=staticpage}
<option value="{$staticid}"{if $staticid == $fp_config.general.startpage} selected="selected"{/if}>
{$staticpage.subject}
</option>
{/foreach}
</select>
</dd>
<dt><label for="maxentries"> {$panelstrings.blogmaxentries} </label></dt>
<dd><input type="text" name="maxentries" id="maxentries"
class="smalltextinput{$error.maxentries|notempty:" field-error"}" value="{$flatpress.maxentries}" /></dd>
</dl>
</div>
<div id="admin-config-intsetts">
<h2> {$panelstrings.intsetts} </h2>
<dl>
<dt> {$panelstrings.utctime} </dt>
{assign var=temp_time value="%b %d %Y %H:%M:%S"}
<dd> <code> {"r"|date:$smarty.now} </code> </dd>
<dt><label for="timeoffset"> {$panelstrings.timeoffset} </label></dt>
<dd><input type="text" name="timeoffset" id="timeoffset"
class="smalltextinput{$error.maxentries|notempty:" field-error"}"
value="{$fp_config.locale.timeoffset}" /> {$panelstrings.hours}
</dd>
<dt><label for="dateformat"> {$panelstrings.dateformat} </label></dt>
<dd> <p> <input type="text" name="dateformat" id="dateformat"
class="textinput{$error.dateformat|notempty:" field-error"}"
value="{$fp_config.locale.dateformat}" /> </p>
<p> {$panelstrings.output}: {$smarty.now|date_format:$fp_config.locale.dateformat} </p>
</dd>
<dt><label for="timeformat"> {$panelstrings.timeformat} </label></dt>
<dd> <p> <input type="text" name="timeformat" id="timeformat"
class="textinput{$error.timeformat|notempty:" field-error"}"
value="{$fp_config.locale.timeformat}" /> </p>
<p> {$panelstrings.output}: {$smarty.now|date_format:$fp_config.locale.timeformat} </p>
</dd>
<dt><label for="lang"> {$panelstrings.langchoice} </label></dt>
<dd>
<select name="lang" id="lang" class="textinput">
{foreach from=$lang_list item=langsetts}
<option value="{$langsetts.locale}"
{if $langsetts.locale == $fp_config.locale.lang}selected="selected"{/if}>
{$langsetts.id}
</option>
{/foreach}
</select>
</dd>
<dt> <label for="charset"> {$panelstrings.charset} </label></dt>
<dd> <p><input type="text" name="charset" id="charset"
class="smalltextinput{$error.dateformat|notempty:" field-error"}"
value="{$fp_config.locale.charset}" /></p>
<p>{$panelstrings.charsettip}</p>
</dd>
</dl>
</div>
</div>
<div class="buttonbar">
{html_submit name="save" id="save" value=$panelstrings.submit}
</div>
{/html_form}

View File

@ -0,0 +1,61 @@
<?php
/**
* plugin control panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
class admin_entry_cats extends AdminPanelActionValidated {
var $validators = array(array('content', 'content', 'notEmpty', false, false, 'trim,stripslashes'));
var $events = array('save');
function main() {
if (isset($_GET['do']) && $_GET['do'] == 'clear') {
$ret1 = fs_delete(CONTENT_DIR . 'categories_encoded.dat') &&
$ret2 = fs_delete(CONTENT_DIR . 'categories.txt');
$ret = ($ret1 && $ret2) ? 2 : -2;
$this->smarty->assign('success', $ret);
}
if (file_exists(CONTENT_DIR . 'categories.txt')) {
$cats = io_load_file(CONTENT_DIR . 'categories.txt');
$this->smarty->assign('catdefs', $cats);
}
do_action('update_categories', true);
return 0;
}
function onsave() {
$str=(stripslashes($_POST['content']));
$success = io_write_file(CONTENT_DIR . 'categories.txt', $str);
entry_categories_encode();
$this->smarty->assign('success', ( $success )? 1 : -1 );
$this->smarty->assign('catdefs', $str);
return PANEL_REDIRECT_CURRENT;
}
}
?>

View File

@ -0,0 +1,27 @@
{validate_init form=$admin_panel_id}
{validate id="content" message=$panelstrings.error.content append="error"}
<h2>{$panelstrings.head}</h2>
{include file=shared:errorlist.tpl}
{$panelstrings.descr}
<p><a href="?p=entry&amp;action=cats&amp;do=clear">{$panelstrings.clear}</a></p>
{html_form}
<p>
<textarea name="content" id="content" rows="20" cols="74">{$catdefs|escape}</textarea><br />
</p>
<div class="buttonbar">
{html_submit name="save" id="save" value=$panelstrings.submit}
</div>
{/html_form}

View File

@ -0,0 +1,45 @@
<?php
/**
* edit entry panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
class admin_entry_commentlist extends AdminPanelAction {
var $commands = array('delete');
function dodelete($commentid) {
$this->smarty->assign('success',
comment_delete($_GET['entry'], $commentid)? 6 : -6
);
return PANEL_REDIRECT_CURRENT;
}
function main() {
global $fpdb;
if (isset($_GET['entry'])) {
$fpdb->query("id:{$_GET['entry']},fullparse:true");
return 0;
}
return 1;
}
}
?>

View File

@ -0,0 +1,60 @@
{entry_block}
{entry}
<h2>{$panelstrings.head} <a href="admin.php?p=entry&amp;action=write&amp;entry={$id}">{$subject}</a></h2>
{include file=shared:errorlist.tpl}
<p>{$panelstrings.descr}</p>
{comment_block}
{html_form}
<script type="text/javascript">
{literal}
function admin_entry_comment_delete() { return confirm({/literal}'{$plang.act_del_confirm}'{literal}); }
{/literal}
</script>
<table class="entrylist">
<thead><tr>
<th>{$panelstrings.date}</th>
<th>{$panelstrings.content}</th>
<th>{$panelstrings.author}</th>
<th>{$panelstrings.email}</th>
<th>{$panelstrings.ip}</th>
<th>{$panelstrings.actions}</th>
</tr></thead>
<tbody>
{comment}
<tr>
{*<td><input type="checkbox" /></td>*}
<td>{$date|date_format:"%D, %T"}</td>
<td class="main_cell">
{$content|strip_tags|truncate:70}
</td>
<td>{if $url}<a href="{$url}">{$name}</a>{else}{$name}{/if}</td>
<td><a href="mailto:{$email}">{$email}</a></td>
<td>{$ip_address}</td>
<td><a class="link-delete" onclick="return admin_entry_comment_delete();"
href="{"`$action_url`&entry=`$entryid`"|cmd_link:delete:$id}">
{$plang.act_del}
</a></td>
</tr>
{/comment}
</tbody></table>
{/html_form}
{/comment_block}
{/entry}
{/entry_block}

View File

@ -0,0 +1,26 @@
<?php
/**
* edit entry panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
$admin_entry_sections = array(
'list',
'new',
'edit',
'delete',
'comms',
'commsdel'
);
?>

View File

@ -0,0 +1,62 @@
<?php
/**
* edit entry panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
class admin_entry_delete extends AdminPanelAction {
var $events = array('delete', 'cancel');
function main() {
global $fpdb;
if (isset($_REQUEST['entry'])){
$id = $_REQUEST['entry'];
if ($a = entry_parse($id));
else
$a = draft_parse($id);
if ($a) {
if (THEME_LEGACY_MODE) {
theme_entry_filters($a, $id);
}
$this->smarty->assign('entry', $a);
$this->smarty->assign('id', $id);
return 0;
}
}
return 1;
}
function ondelete() {
$id=$_REQUEST['entry'];
$ok=draft_delete($id) || entry_delete($id);
$success = $ok? 2 : -2;
$this->smarty->assign('success',$success);
return 1;
}
function oncancel() {
return 1;
}
}
?>

View File

@ -0,0 +1,19 @@
<h2>{$panelstrings.head}</h2>
<p>{$panelstrings.descr}</p>
{entry_block}
{html_form}
<fieldset><legend>{$panelstrings.preview}</legend>
{include file=preview.tpl}
</fieldset>
<p>{$panelstrings.confirm}</p>
<input type="hidden" name="entry" value="{$id}" />
<div class="buttonbar">
{html_submit name="delete" id="delete" value=$panelstrings.ok}
{html_submit name="cancel" id="cancel" value=$panelstrings.cancel}
</div>
{/html_form}
{/entry_block}

View File

@ -0,0 +1,92 @@
<?php
/**
* edit entry panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
//require (ADMIN_DIR . 'panels/entry/shared.entry.form.php');
// ---------------------------------------------------------------------
// utils
// ---------------------------------------------------------------------
function smarty_function_flag_classes($params, &$smarty) {
$flags = entry_flags_get();
($active_flags = array_intersect(
$smarty->get_template_vars('categories'), $flags));
return implode(' ', $active_flags);
}
class admin_entry_list extends AdminPanelActionValidated {
var $actionname = 'list';
function setup() {
$this->smarty->register_function('flag_classes', 'smarty_function_flag_classes');
}
function main() {
parent::main();
//$smarty =& $this->smarty;
// parameters for the list
// start offset and count (now defaults to 8...)
$this->smarty->assign('categories_all', entry_categories_get('defs'));
$this->smarty->assign('saved_flags', entry_flags_get());
$defcount = 8; // <-- no magic numbers! todo: add config option?
global $fpdb;
if (!empty($_REQUEST['entry']))
utils_redirect('admin.php?p=entry&action=write&entry='.$_REQUEST['entry']);
isset($_REQUEST['m'])? $params['m'] = $_REQUEST['m'] : null;
isset($_REQUEST['y'])? $params['y'] = $_REQUEST['y'] : null;
// $params['start'] = isset($_REQUEST['start'])? $_REQUEST['start'] : 0;
$params['count'] = isset($_REQUEST['count'])? $_REQUEST['count'] : $defcount;
$params['page'] = isset($_REQUEST['paged'])? $_REQUEST['paged'] : 1;
isset($_REQUEST['category'])? $params['category'] = $_REQUEST['category'] : $params['category'] = 'all';
$params['fullparse']=true;
$fpdb->query($params);
return 0;
}
function onsubmit() {
parent::onsubmit();
return $this->main();
}
function onfilter() {
return $this->main();
}
function onerror() {
return $this->main();
}
}
?>

View File

@ -0,0 +1,95 @@
<h2>{$panelstrings.head}</h2>
{draft_block}
<div id="admin-drafts">
<p>Your drafts:</p>
<ul>
{draft}
<li>
<a href="admin.php?p=entry&amp;entry={$id}&amp;action=write">{$subject|truncate:70}</a>
</li>
{/draft}
</ul>
</div>
{/draft_block}
{include file=shared:errorlist.tpl}
<p>{$panelstrings.descr}</p>
{html_form}
<fieldset><legend>{$panelstrings.filter}</legend>
<select name="category" class="alignleft">
<option label="Unfiltered" value="all">{$panelstrings.nofilter}</option>
{*html_options options=$lang.entry.flags.short selected=$smarty.request.cat*}
{html_options options=$categories_all selected=$smarty.request.category}
</select>
{html_submit name='filter' id='filter' class="alignright" value=$panelstrings.filterbtn}
</fieldset>
{entry_block}
<table class="entrylist">
<thead><tr>{*<th>{$panelstrings.sel}</th>*}
<th>{$panelstrings.date}</th>
<th class="main-cell">{$panelstrings.title}</th>
<th>{$panelstrings.author}</th>
<th>{$panelstrings.comms}</th>
<th>{$panelstrings.action}</th></tr></thead>
<tbody>
{entry}
<tr>
<td>{$date|date_format:"%D, %T"}</td>
<td class="main-cell">
{if in_array('draft',$categories)}
(<em class="entry-flag">{$lang.entry.flags.short.draft}</em>)
{/if}
{$subject|truncate:70}
</td>
<td>{$author}</td>
<td><a class="link-general"
href="{$panel_url|action_link:commentlist}&amp;entry={$id}">
{* Compatibility with pre-0.702 *}
{$commentcount|default:$comments}</a></td>
<td>
<a class="link-general"
href="{$id|link:post_link}">
{$panelstrings.act_view}
</a>
<a class="link-general"
href="{$panel_url|action_link:write}&amp;entry={$id}">
{$panelstrings.act_edit}
</a>
<a class="link-delete"
href="{$panel_url|action_link:delete}&amp;entry={$id}">
{$panelstrings.act_del}
</a>
</td>
</tr>
{/entry}
</tbody></table>
<div class="navigation">
{prevpage admin=yes}
{nextpage admin=yes}
</div>
{/entry_block}
{/html_form}

View File

@ -0,0 +1,36 @@
<?php
/**
* edit entry panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
class admin_entry extends AdminPanel {
var $panelname = "entry";
var $actions = array(
'list' => true,
'write' => true,
'commentlist' => false,
'delete' => false,
'cats' => true,
'stats' => false
);
var $defaultaction = 'list';
}
?>

View File

@ -0,0 +1,138 @@
<?php
/**
* edit entry panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
class admin_entry_stats extends AdminPanelAction {
function format_number($num, $sep) {
$ss = $sep*$sep;
$i = 0;
while ( $num > $ss ) {
$num = (float) $num / $sep;
$i++;
}
return array(number_format((int)$num), $i);
}
function main() {
global $fpdb;
$fpdb->query(array(
'count' => -1, // show all
'fullparse' => true
));
$q = $fpdb->getQuery();
$comments =
$entries = array(
'count' => 0,
'words' => 0,
'chars' => 0,
'size' => 0,
'topten' => array()
);
$entries['comments'] = 0;
$toplist = array();
while ($q->hasMore()) {
list($id, $e) = $q->getEntry();
$entries['count']++;
$entries['words'] += str_word_count($e['subject']) +
str_word_count($e['content']);
$entries['chars'] += strlen($e['subject']) +
strlen($e['content']);
$entries['size'] += filesize(entry_exists($id));
$cc = $q->hasComments();
$entries['comments'] += $cc;
$toplist[$id] = $cc;
$toplistsubj[$id] = $e['subject'];
$comments['count']+= $cc;
while ($q->comments->hasMore()) {
list($cid, $c) = $q->comments->getComment();
$comments['words'] += str_word_count($c['content']);
$comments['chars'] += strlen($c['content']);
$comments['size'] += filesize(comment_exists($id, $cid));
}
}
arsort($toplist);
$i = 0;
foreach($toplist as $k=>$v) {
if ($i>=10 || $v < 1)
break;
$entries['topten'][$k] = array(
'subject' => $toplistsubj[$k],
'comments' => $v
);
$i++;
}
$decunit = array('', 'Thousand', 'Million', 'Billion', 'Trillion', 'Zillion', 'Gazillion');
$binunit = array('Bytes', 'KiloBytes', 'MegaBytes', 'GigaBytes', 'TeraBytes', 'Many', 'ManyBytes');
list($count, $approx) = $this->format_number($entries['count'], 1000);
$entries['count'] = $count .' '. $decunit[$approx];
list($count, $approx) = $this->format_number($entries['words'], 1000);
$entries['words'] = $count .' '. $decunit[$approx];
list($count, $approx) = $this->format_number($entries['chars'], 1000);
$entries['chars'] = $count .' '. $decunit[$approx];
list($count, $approx) = $this->format_number($entries['comments'], 1000);
$entries['comments'] = $count .' '. $decunit[$approx];
list($count, $approx) = $this->format_number($entries['size'], 1024);
$entries['size'] = $count .' '. $binunit[$approx];
$this->smarty->assign('entries', $entries);
list($count, $approx) = $this->format_number($comments['count'], 1000);
$comments['count'] = $count .' '. $decunit[$approx];
list($count, $approx) = $this->format_number($comments['words'], 1000);
$comments['words'] = $count .' '. $decunit[$approx];
list($count, $approx) = $this->format_number($comments['chars'], 1000);
$comments['chars'] = $count .' '. $decunit[$approx];
list($count, $approx) = $this->format_number($comments['size'], 1024);
$comments['size'] = $count .' '. $binunit[$approx];
$this->smarty->assign('comments', $comments);
}
}

View File

@ -0,0 +1,29 @@
<h2>{"Statistics"}</h2>
<h3>{"Entries"}</h3>
{"<p>You have <strong>%s</strong>
entries using <strong>%s</strong> characters
in <strong>%s</strong> words.</p>
<p>Total disk space is
<strong>%s</strong>.</p>"|sprintf:$entries.count:$entries.chars:$entries.words:$entries.size}
<h3>{"Comments"}</h3>
{"<p>You have <strong>%s</strong>
comments using <strong>%s</strong> characters
in <strong>%s</strong> words.</p>
<p>Total disk space is
<strong>%s</strong>.</p>"|sprintf:$comments.count:$comments.chars:$comments.words:$comments.size}
{if $entries.topten}
<h3> {$entries.topten|@count} {"most commented entries"} </h3>
<ol>
{foreach from=$entries.topten key=id item=this_entry}
<li><a href="{$id|link:post_link}">{$this_entry.subject}</a> ({$this_entry.comments})</li>
{/foreach}
</ol>
{/if}

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,176 @@
<?php
/**
* edit entry panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
class admin_entry_write extends AdminPanelActionValidated {
var $validators = array(
array('subject', 'subject', 'notEmpty', false, false, 'trim,stripslashes'),
array('content', 'content', 'notEmpty', false, false, 'stripslashes'),
);
var $events = array('save', 'preview', 'savecontinue');
function _makePreview($arr, $id=null) {
$arr['subject'] = apply_filters('title_save_pre', $arr['subject']);
$arr['content'] = apply_filters('content_save_pre', $arr['content']);
$this->smarty->assign('post', $arr);
if (THEME_LEGACY_MODE) {
theme_entry_filters($arr, $id);
}
$arr = array_change_key_case($arr, CASE_LOWER);
$this->smarty->assign('entry', $arr);
$this->smarty->assign('preview', true);
}
function makePageTitle($title, $sep) {
global $lang;
return "$title $sep {$lang['admin']['entry']['write']['head']}";
}
function _getCatsFlags() {
//$this->smarty->assign('saved_categories', entry_categories_format());
$this->smarty->assign('saved_flags', entry_flags_get());
}
function setup() {
$this->id = @$_REQUEST['entry'];
$this->smarty->assign('id', $this->id);
}
function main() {
global $lang;
$id = $this->id;
if (isset($_REQUEST['entry'])) {
$arr = draft_parse($id);
if (!$arr)
$arr = entry_parse($id);
else
$this->smarty->assign('draft', true);
// if entry does not exists
if ($arr) {
$this->_makePreview($arr, $id);
}
}
$this->_getCatsFlags();
add_filter('wp_title', array(&$this, 'makePageTitle'), 10, 2);
}
function _getposteddata() {
$arr['version'] = system_ver();
$arr['subject'] = ($_POST['subject']);
$arr['content'] = ($_POST['content']);
$author = user_get();
$arr['author'] = $author['userid'];
$arr['date'] = !empty($_POST['timestamp'])?$_POST['timestamp']:date_time();
$cats = !empty($_POST['cats'])?$_POST['cats']:array();
$flags = !empty($_POST['flags'])?$_POST['flags']:array();
$catids = array_merge(array_keys($flags), array_keys($cats));
if ($catids)
$arr['categories'] = $catids;
return $arr;
}
function onsave($do_preview = false) {
$id = $this->id;
$data = $this->_getposteddata();
if (isset($data['categories']) && in_array('draft', $data['categories'])) {
$success=draft_save($data, $id);
} else {
/* anyway issued */
draft_to_entry($id);
$success=entry_save($data, $id);
}
if ($success) sess_remove('entry');
$this->smarty->assign('success',$success? 1:-1);
if ($do_preview)
$this->_makePreview($data);
return 1;
}
function onpreview() {
global $lang;
$this->_makePreview($this->_getposteddata());
$this->_getCatsFlags();
add_filter('wp_title', array(&$this, 'makePageTitle'), 10, 2);
return 0;
}
function onsavecontinue() {
global $lang;
$this->onsave(true);
$this->_getCatsFlags();
add_filter('wp_title', array(&$this, 'makePageTitle'), 10, 2);
}
function onerror() {
$this->main();
return 0;
}
}
?>

View File

@ -0,0 +1,101 @@
<h2>{$panelstrings.head}</h2>
{html_form}
{validate_init form=$admin_panel_id}
{validate id="subject" message=$panelstrings.error.subject append="error"}
{validate id="content" message=$panelstrings.error.content append="error"}
{include file='shared:errorlist.tpl'}
{entry_block}
{if $preview}
<fieldset id="post-preview"><legend>{$panelstrings.preview}</legend>
{include file=preview.tpl}
</fieldset>
{/if}
{entry content=$post alwaysshow=true}
<div id="admin-editor">
<p><label for="subject">{$panelstrings.subject}</label><br />
<input type="text" {$error.subject|notempty:'class="field-error"'}
name="subject" id="subject"
value="{$subject|default:$smarty.request.subject}" /><br />
<input type="hidden" name="timestamp" value="{$date}" />
<input type="hidden" name="entry" value="{$id}" />
</p>
<p>
<label for="content">{$panelstrings.content}</label>
</p>
{toolbar}
<p>
<textarea name="content" {$error.content|notempty:'class="field-error"'}
id="content" rows="20" cols="74">{$content|default:$smarty.request.content}</textarea><br />
{*here will go a plugin hook*}
{action hook=simple_edit_form}
</p>
</div>
<div id="admin-options">
{* let's disable this for now... *}
{*
<fieldset id="admin-entry-uploader"><legend>{$panelstrings.uploader}</legend>
<iframe id="uploader-iframe" src="{$smarty.const.BLOG_BASEURL}admin.php?p=uploader&amp;mod=inline"></iframe>
</fieldset>
*}
{* end of inline form *}
<fieldset id="admin-entry-categories"><legend>{$panelstrings.archive}</legend>
{list_categories type=form}
</fieldset>
<fieldset id="admin-entry-saveopts"><legend>{$panelstrings.saveopts}</legend>
<p>
{foreach from=$saved_flags item=flag}
<label><input name="flags[{$flag}]" {if $categories and (bool)array_intersect(array($flag),$categories) }checked="checked"{/if} type="checkbox" /> {$lang.entry.flags.long[$flag]} </label><br />
{/foreach}
</p>
</fieldset>
</div>
<div class="buttonbar">
{html_submit name="save" id="save" value=$panelstrings.submit accesskey=s}
{html_submit name="savecontinue" id="savecontinue" value=$panelstrings.savecontinue accesskey=c}
{html_submit name="preview" id="preview" value=$panelstrings.preview accesskey=p}
</div>
{/entry}
{/entry_block}
{/html_form}
{if $smarty.get.entry }
<div id="admin-otheroptions">
<h2>{$panelstrings.otheropts}</h2>
<ul>
{if !$draft}
<li><a href="admin.php?p=entry&amp;entry={$smarty.get.entry}&amp;action=commentlist">
{$panelstrings.commmsg}</a></li>
{/if}
<li><a href="admin.php?p=entry&amp;entry={$smarty.get.entry}&amp;action=delete">
{$panelstrings.delmsg}</a></li>
</ul>
</div>
{/if}

View File

@ -0,0 +1,51 @@
<?php
/**
* shared entry form
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
function shared_entry_form_setup(&$smarty) {
$smarty->assign('form', ABS_PATH.ADMIN_DIR."panels/entry/shared.entry.form.tpl");
admin_entry_cats_flags($smarty);
}
function shared_entry_form_main() {
SmartyValidate::register_validator('subject', 'subject', 'notEmpty', false, false, 'trim');
SmartyValidate::register_validator('content', 'content', 'notEmpty', false, false);
}
function shared_entry_form_onsubmit() {
$arr['version'] = system_ver();
$arr['subject'] = stripslashes($_POST['subject']);
$arr['content'] = stripslashes($_POST['content']);
$author = user_get();
$arr['author'] = $author['NAME'];
$arr['date'] = !empty($_POST['timestamp'])?$_POST['timestamp']:time();
$cats = !empty($_POST['cats'])?$_POST['cats']:array();
$flags = !empty($_POST['flags'])?$_POST['flags']:array();
$arr['categories'] = array_merge(array_keys($flags), array_keys($cats));
//sess_add('entry', $arr);
return $arr;
}
?>

View File

@ -0,0 +1,54 @@
{validate id="subject" message=$panelstrings.error.subject append="error"}
{validate id="content" message=$panelstrings.error.content append="error"}
{if $error}
<ul class="errorlist">
{foreach from=$error key=field item=msg}
<li>{$msg}</li>
{/foreach}
</ul>
{/if}
<fieldset><legend>{$panelstrings.fieldset1}</legend>
<p><label for="subject">{$panelstrings.subject}</label><br />
<input type="text" name="subject" id="subject" value="{$subject|default:$smarty.request.subject}" /><br />
<input type="hidden" name="timestamp" value="{$date}" />
</p>
{toolbar}
<p>
<label for="content">{$panelstrings.content}</label><br />
<textarea name="content" id="content" rows="20" cols="74"{$content|default:$smarty.request.content}</textarea><br />
{*here will go a plugin hook*}
</p>
</fieldset>
<fieldset><legend>Archive</legend>
<p>
{foreach from=$saved_categories key=catId item=cat}
<label><input name="cats[{$catId}]" {if in_array( $catId,(array) $categories ) }checked="checked"{/if} type="checkbox" /> {$cat} </label><br />
{foreachelse}
No categories set. Create your own categories from the main entry panel. Save your entry first.
{/foreach}
</p>
</fieldset>
<fieldset><legend>Save options</legend>
<p>
{foreach from=$saved_flags item=flag}
<label><input name="flags[{$flag}]" {if in_array( $flag,(array) $categories ) }checked="checked"{/if} type="checkbox" /> {$lang.entry.flags.long[$flag]} </label><br />
{/foreach}
</p>
</fieldset>
<fieldset><legend>{$panelstrings.fieldset2}</legend>
{html_submit name="submit" id="submit" value=$panelstrings.submit}
{html_submit name="preview" id="preview" value=$panelstrings.preview}
</fieldset>

View File

@ -0,0 +1,46 @@
<h2>{$panelstrings.head}</h2>
<p>{$panelstrings.descr}</p>
<dl>
<dt class="admin-mainmenu-item">
<img src="{$smarty.const.ADMIN_DIR}imgs/newentry.png" class="alignleft" alt="{$panelstrings.op1}"
title="{$panelstrings.op1}" />
<a href="admin.php?p=entry&amp;action=write">{$panelstrings.op1}</a>
</dt>
<dd class="admin-icon-descr">{$panelstrings.op1d}</dd>
<dt class="admin-mainmenu-item">
<img src="{$smarty.const.ADMIN_DIR}imgs/entries.png" class="alignleft" alt="{$panelstrings.op2}"
title="{$panelstrings.op2}" />
<a href="admin.php?p=entry">{$panelstrings.op2}</a>
</dt>
<dd class="admin-icon-descr">{$panelstrings.op2d}</dd>
<dt class="admin-mainmenu-item">
<img src="{$smarty.const.ADMIN_DIR}imgs/widgets.png" class="alignleft" alt="{$panelstrings.op3}"
title="{$panelstrings.op3}" />
<a href="admin.php?p=widgets">{$panelstrings.op3}</a>
</dt>
<dd class="admin-icon-descr">{$panelstrings.op3d}</dd>
<dt class="admin-mainmenu-item">
<img src="{$smarty.const.ADMIN_DIR}imgs/plugins.png" class="alignleft" alt="{$panelstrings.op4}"
title="{$panelstrings.op4}" />
<a href="admin.php?p=plugin">{$panelstrings.op4}</a>
</dt>
<dd class="admin-icon-descr">{$panelstrings.op4d}</dd>
<dt class="admin-mainmenu-item">
<img src="{$smarty.const.ADMIN_DIR}imgs/config.png" class="alignleft" alt="{$panelstrings.op5}"
title="{$panelstrings.op5}" />
<a href="admin.php?p=config">{$panelstrings.op5}</a>
</dt>
<dd class="admin-icon-descr">{$panelstrings.op5d}</dd>
<dt class="admin-mainmenu-item">
<img src="{$smarty.const.ADMIN_DIR}imgs/maintain.png" class="alignleft" alt="{$panelstrings.op6}"
title="{$panelstrings.op6}" />
<a href="admin.php?p=maintain">{$panelstrings.op6}</a>
</dt>
<dd class="admin-icon-descr">{$panelstrings.op6d}</dd>
</dl>

View File

@ -0,0 +1,152 @@
<?php
/**
* add entry panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
/* utility class */
class tpl_deleter extends fs_filelister {
function tpl_deleter() {
//$this->smarty = $GLOBALS['_FP_SMARTY'];
$this->_directory = CACHE_DIR;
parent::fs_filelister();
}
function _checkFile($directory, $file) {
if ($file != CACHE_FILE) {
array_push($this->_list, $file);
fs_delete("$directory/$file");
}
//trigger_error($file, E_USER_NOTICE);
return 0;
}
}
/*********************/
class admin_maintain extends AdminPanel {
var $panelname = 'maintain';
var $actions = array('default'=>false, 'updates'=>false);
}
class admin_maintain_updates extends AdminPanelAction {
var $web = 'http://www.nowhereland.it/fp/VERSION';
var $fpweb = 'http://flatpress.nowhereland.it/downloads.php';
var $sfweb = 'http://sourceforge.net/project/showfiles.php?group_id=157089';
function main() {
$success = -1;
$ver = array(
'stable'=>'unknown',
'unstable'=>'unknown',
);
$f = @fopen($this->web, 'r');
if ($f) {
$file='';
while(!feof($f)) {
$file .= fgets($f);
}
if ($file){
$ver = utils_kexplode($file);
if (strcmp($ver['STABLE'], SYSTEM_VER)>0)
$success = 1;
else
$success = 2;
$ver = array_change_key_case($ver, CASE_LOWER);
}
}
$this->smarty->assign('updates', $ver);
$this->smarty->assign('fpweb', $this->fpweb);
$this->smarty->assign('sfweb', $this->sfweb);
$this->smarty->assign('success', $success);
}
}
class admin_maintain_default extends AdminPanelAction {
var $commands = array('do');
function dodo($do) {
switch ($do) {
case 'purgecache': {
$obj =& entry_init();
$obj->purge();
if (!file_exists(CACHE_DIR))
fs_mkdir(CACHE_DIR);
$this->smarty->assign('success', 1);
return PANEL_REDIRECT_CURRENT;
}
case 'restorechmods': {
$this->smarty->assign('files',fs_chmod_recursive());
$this->smarty->assign('success', 1);
return PANEL_NOREDIRECT;
}
case 'purgetplcache': {
$tpldel = new tpl_deleter;
unset($tpldel);
$this->smarty->cache_dir = CACHE_DIR.'cache/';
$this->smarty->caching = 0;
$this->smarty->clear_all_cache();
$this->smarty->clear_compiled_tpl();
$this->smarty->compile_check = true;
$this->smarty->force_compile = true;
$this->smarty->assign('success', 1);
if (!file_exists(CACHE_DIR))
fs_mkdir(CACHE_DIR);
return PANEL_NOREDIRECT;
}
case 'phpinfo': {
ob_start();
phpinfo();
$info = ob_get_contents();
ob_end_clean();
$this->smarty->assign('phpinfo', preg_replace('%^.*<body>(.*)</body>.*$%ms', '$1', $info));
}
return PANEL_NOREDIRECT;
}
}
function main() {
}
}
?>

View File

@ -0,0 +1,25 @@
<h2>{$panelstrings.head}</h2>
{include file=shared:errorlist.tpl}
{if $files}
<p>{$panelstrings.chmod_info}</p>
<p><a href="admin.php?p=maintain">{$panelstrings.opt0}</a></p>
<ul>
{foreach from=$files item=file}
<li>{$file}</li>
{/foreach}
</ul>
<p><a href="admin.php?p=maintain">{$panelstrings.opt0}</a></p>
{elseif $phpinfo}
<p><a href="admin.php?p=maintain">{$panelstrings.opt0}</a></p>
{$phpinfo}
<p><a href="admin.php?p=maintain">{$panelstrings.opt0}</a></p>
{else}
<p>{$panelstrings.descr}</p>
<ul>
<li><a href="{$action_url|cmd_link:do:purgecache}">{$panelstrings.opt1}</a></li>
<li><a href="{$action_url|cmd_link:do:purgetplcache}">{$panelstrings.opt2}</a></li>
<li><a href="{$action_url|cmd_link:do:restorechmods}">{$panelstrings.opt3}</a></li>
<li><a href="{$action_url|cmd_link:do:phpinfo}">{$panelstrings.opt4}</a></li>
<li><a href="{$panel_url|action_link:updates}">{$panelstrings.opt5}</a></li>
</ul>
{/if}

View File

@ -0,0 +1,7 @@
<h2>{$panelstrings.head}</h2>
{include file=shared:errorlist.tpl}
{$panelstrings.list|sprintf:$smarty.const.SYSTEM_VER:$sfweb:$updates.stable:$fpweb:$updates.unstable}
{if $updates.notice}
<h5>{$panelstrings.notice}</h5>
<p>{$updates.notice}</p>
{/if}

View File

@ -0,0 +1,144 @@
<?php
/**
* plugin control panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
/*
function admin_plugin_adminheader() {
$f = ADMIN_DIR . '/panels/plugin/admin.plugin.js';
echo <<<SCP
<script src="$f" type="text/javascript"></script>
SCP;
}
add_action('wp_head', 'admin_plugin_adminheader');
*/
class admin_plugin extends AdminPanel {
var $panelname = 'plugin';
var $actions = array('default'=>true);
}
class admin_plugin_default extends AdminPanelAction {
var $commands = array('enable', 'disable');
var $errors = array();
function setup() {
$this->pluginid = isset($_GET['plugin'])? $_GET['plugin'] : null;
$pi =& new plugin_indexer;
$this->smarty->assign('pluginlist', $pi->getList());
$this->errors = @$pi->getEnableds(true);
$this->fp_plugins = $pi->enabledlist;
}
function dodisable($id) {
$fp_plugins = $this->fp_plugins;
$success = -1;
if (plugin_exists($id)) {
$success = 1;
if (false !== $i = array_search($id, $fp_plugins)) {
unset($fp_plugins[$i]);
sort($fp_plugins); /* compact indices */
do_action('deactivate_'.$id);
$success = system_save(CONFIG_DIR . 'plugins.conf.php', compact('fp_plugins'));
} else {
$success = -1;
}
}
if ($success)
$this->smarty->assign('success', $success);
return PANEL_REDIRECT_CURRENT;
}
function doenable ($id) {
$success = -1;
$fp_plugins = $this->fp_plugins;
if (plugin_exists($id)) {
$success = 1;
if (!in_array($id, $fp_plugins)) {
$fp_plugins[] = $id;
plugin_load($id, true, false);
do_action('activate_'.$id);
$success = system_save(CONFIG_DIR . 'plugins.conf.php', compact('fp_plugins'));
} else {
$success = -1;
}
}
if ($success)
$this->smarty->assign('success', $success);
return PANEL_REDIRECT_CURRENT;
}
function main() {
//$conf = io_load_file(CONFIG_DIR . 'plugins.conf.php');
$this->smarty->assign('warnings', $this->errors);
$this->smarty->assign('enabledlist', $this->fp_plugins);
lang_load('admin.plugin');
return 0;
}
function onsave() {
$fp_plugins = array_keys($_POST['plugin_enabled']);
$success = system_save(CONFIG_DIR . 'plugins.conf.php', compact('fp_plugins'));
$retval = ( $success )? 1 : -1 ;
$this->smarty->assign('success', $retval);
//$this->smarty->assign('pluginconf', $str);
return $retval;
}
}
?>

View File

@ -0,0 +1,46 @@
<h2>{$panelstrings.head}</h2>
<p>{$panelstrings.descr}</p>
{include file='shared:errorlist.tpl'}
{html_form}
<table id="plugin-table">
<thead id="plugin-table-head">
<tr>
<th>{$panelstrings.name}</th>
<th class="main-cell">{$panelstrings.description}</th>
<th>{$panelstrings.author}</th>
<th>{$panelstrings.version}</th>
<th>{$panelstrings.action}</th>
</tr>
</thead>
<tbody id="plugin-table-body">
{foreach from=$pluginlist item=plugin}
{assign var=inarr value=$plugin|in_array:$enabledlist}
{$plugin|plugin_getinfo}
<tr{if $inarr} class="enabled" {/if}>
<td> {$name} </td>
<td class="main-cell"> {$description} </td>
<td> {$author} </td>
<td> {$version} </td>
<td> {if $inarr}
<a class="link-disable"
href="{$action_url|cmd_link:disable:$plugin}">
{$panelstrings.disable}
</a>
{else}
<a class="link-enable"
href="{$action_url|cmd_link:enable:$plugin}">
{$panelstrings.enable}
</a>
{/if}
</td>
</tr>
{/foreach}
</tbody>
</table>
{/html_form}

View File

@ -0,0 +1,52 @@
<?php
/**
* edit entry panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
class admin_static_delete extends AdminPanelAction {
var $events = array('delete', 'cancel');
function setup() {
$this->page = @($_REQUEST['page']);
$this->smarty->assign('pageid', $this->page);
}
function main() {
if ($this->page) {
$arr = static_parse($this->page);
if (THEME_LEGACY_MODE)
theme_entry_filters($arr, null);
$this->smarty->assign('entry', $arr);
} else return 1;
}
function ondelete() {
$id=$this->page;
$success=static_delete($id);
$this->smarty->assign('success',$success? 2 : -2);
return 1;
}
function oncancel() {
return 1;
}
}
?>

View File

@ -0,0 +1,18 @@
<h2>{$panelstrings.head}</h2>
<p>{$panelstrings.descr}</p>
{statics}
<fieldset><legend>{$panelstrings.preview}</legend>
{include file=previewstatic.tpl}
</fieldset>
{/statics}
<p>{$panelstrings.confirm}</p>
{html_form}
<input type="hidden" name="page" value="{$pageid}" />
<div class="buttonbar">
{html_submit name="delete" id="delete" value=$panelstrings.ok}
{html_submit name="cancel" id="cancel" value=$panelstrings.cancel}
</div>
{/html_form}

View File

@ -0,0 +1,54 @@
<?php
/**
* edit entry panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
// ---------------------------------------------------------------------
// utils
// ---------------------------------------------------------------------
class admin_static_list extends AdminPanelActionValidated {
var $actionname = 'list';
function main() {
parent::main();
$this->smarty->assign('statics', $assign = static_getlist());
return 0;
}
function onsubmit() {
parent::onsubmit();
return $this->main();
}
function onfilter() {
return $this->main();
}
function onerror() {
return $this->main();
}
}
?>

View File

@ -0,0 +1,50 @@
<h2>{$panelstrings.head}</h2>
{include file='shared:errorlist.tpl'}
<p>{$panelstrings.descr}</p>
{static_block}
{html_form}
<table class="entrylist">
<thead><tr>{*<th>{$panelstrings.sel}</th>*}
<th>{$panelstrings.name}</th>
<th class="main-cell">{$panelstrings.title}</th>
<th>{$panelstrings.author}</th>
<th>{$panelstrings.action}</th></tr></thead>
<tbody>
{static}
<tr>
{*<td><input type="checkbox" /></td>*}
<td>{$id}</td>
<td class="main-cell">
{$subject|truncate:70}
</td>
<td>{$author}</td>
<td>
<a class="link-general"
href="{$panel_url|link:page_link}&amp;page={$id}">
{$panelstrings.act_view}
</a>
<a
class="link-general"
href="{$panel_url|action_link:write}&amp;page={$id}">
{$panelstrings.act_edit}
</a>
<a class="link-delete"
href="{$panel_url|action_link:delete}&amp;page={$id}">
{$panelstrings.act_del}
</a>
</td>
</tr>
{/static}
</tbody></table>
{/html_form}
{/static_block}

View File

@ -0,0 +1,33 @@
<?php
/**
* edit entry panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
class admin_static extends AdminPanel {
var $panelname = "static";
var $actions = array(
'list' => true,
'delete' => false,
'write' => true,
);
var $defaultaction = 'list';
}
?>

View File

@ -0,0 +1,129 @@
<?php
/**
* edit entry panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
class admin_static_write extends AdminPanelActionValidated {
var $validators = array(
array('subject', 'subject', 'notEmpty', false, false, 'trim'),
array('content', 'content', 'notEmpty', false, false, 'stripslashes'),
array('id', 'id', 'isValidEntryId', false, false, 'stripslashes'),
);
var $events = array('save', 'preview');
function _makePreview($arr, $id=null) {
$arr['subject'] = apply_filters('title_save_pre', $arr['subject']);
$arr['content'] = apply_filters('content_save_pre', $arr['content']);
$this->smarty->assign('post', $arr);
if (THEME_LEGACY_MODE) {
theme_entry_filters($arr, $id);
}
$arr = array_change_key_case($arr, CASE_LOWER);
$this->smarty->assign('entry', $arr);
$this->smarty->assign('preview', true);
$this->smarty->assign('id', $id);
}
function makePageTitle($title, $sep) {
global $lang;
return "$title $sep {$lang['admin']['static']['write']['head']}";
}
function main() {
global $lang;
$this->smarty->assign('static_id', 'static'.date_time());
if (isset($_GET['page'])) {
$id = $_GET['page'];
$arr = static_parse($id);
// if entry does not exists,
// we print the list
if ($arr) {
$this->_makePreview($arr, $id);
}
}
add_filter('wp_title', array(&$this, 'makePageTitle'), 10, 2);
}
function _getposteddata() {
$arr['version'] = system_ver();
$arr['subject'] = stripslashes($_POST['subject']);
$arr['content'] = stripslashes($_POST['content']);
$author = user_get();
$arr['author'] = $author['userid'];
$arr['date'] = !empty($_POST['timestamp'])?$_POST['timestamp']:date_time();
$cats = !empty($_POST['cats'])?$_POST['cats']:array();
$flags = !empty($_POST['flags'])?$_POST['flags']:array();
//$arr['categories'] = array_merge(array_keys($flags), array_keys($cats));
return $arr;
}
function onsave() {
$oldid = isset($_GET['page'])? $_GET['page'] : null;
$id = $_POST['id'];
$success=static_save($this->_getposteddata(), $id, $oldid);
$this->smarty->assign('success',$success? 1:-1);
return $success;
}
function onpreview() {
global $lang;
$this->_makePreview($this->_getposteddata());
return 0;
}
function onerror() {
$this->main();
return 0;
}
}
?>

View File

@ -0,0 +1,58 @@
<h2>{$panelstrings.head}</h2>
{validate_init form=$admin_panel_id}
{validate id="subject" message=$panelstrings.error.subject append="error"}
{validate id="content" message=$panelstrings.error.content append="error"}
{validate id="id" message=$panelstrings.error.id append="error"}
{include file='shared:errorlist.tpl'}
{static_block}
{if $preview}
<fieldset id="post-preview"><legend>{$panelstrings.preview}</legend>
{include file=preview.tpl}
</fieldset>
{/if}
{html_form}
{static content=$post alwaysshow=true}
<p><label for="subject">{$panelstrings.subject}</label><br />
<input type="text" name="subject" id="subject" {$error.subject|notempty:'class="field-error"'}
value="{$subject|default:$smarty.request.subject|default:$smarty.request.page}" /><br />
<input type="hidden" name="timestamp" value="{$date}" />
</p>
<p>
<label for="content">{$panelstrings.content}</label>
</p>
{toolbar}
<p>
<textarea name="content" {$error.content|notempty:'class="field-error"'} id="content"
rows="20" cols="74">{$content|default:$smarty.request.content}</textarea><br />
{*here will go a plugin hook*}
</p>
<fieldset id="admin-static-filename"><legend>{$panelstrings.fieldset2}</legend>
<input type="hidden" name="oldid" id="oldid" value="{$id|default:$smarty.request.oldid}" />
<p><label for="id">{$panelstrings.pagename}</label><br />
<input type="text" name="id" id="id" class="maxsize{$error.id|notempty:' field-error'}"
value="{$smarty.request.id|default:$smarty.request.page|default:$static_id}" /></p>
{html_submit name="save" id="save" value=$panelstrings.submit accesskey=s}
{html_submit name="preview" id="preview" value=$panelstrings.preview accesskey=p}
</fieldset>
{/static}
{/html_form}
{/static_block}

View File

@ -0,0 +1,159 @@
<?php
class admin_themes extends AdminPanel {
var $panelname = 'themes';
var $actions = array('default' => true);
function admin_themes(&$smarty) {
global $theme;
if ($theme['version'] > 0.703)
$this->actions['style'] = true;
parent::AdminPanel($smarty);
}
}
function admin_theme_data( $theme_file, $theme_id, $defprev ) {
$theme_data = io_load_file($theme_file);
$theme_data = str_replace ( '\r', '\n', $theme_data );
preg_match( '/(Theme|Style) Name:(.*)/i', $theme_data, $theme_name );
preg_match( '/(Theme|Style) URI:(.*)/i', $theme_data, $theme_uri );
preg_match( '|Description:(.*)|i', $theme_data, $description );
preg_match( '|Author:(.*)|i', $theme_data, $author_name );
preg_match( '|Author URI:(.*)|i', $theme_data, $author_uri );
preg_match( '|Template:(.*)|i', $theme_data, $template );
if ( preg_match( '|Version:(.*)|i', $theme_data, $version ) )
$version = trim( $version[1] );
else
$version ='';
if ( preg_match('|Status:(.*)|i', $theme_data, $status) )
$status = trim($status[1]);
else
$status = 'publish';
$description = @wptexturize( trim( $description[1] ) );
$name = @$theme_name[1]? $theme_name[2] : $theme_id;
$name = trim( $name );
$theme = $name;
$theme_uri = trim( @$theme_uri[2] );
if ( '' == @$author_uri[1] ) {
$author = trim( @$author_name[1] );
} else {
$author = '<a href="' . trim( $author_uri[1] ) . '">' .
trim( $author_name[1] ) . '</a>';
}
if (file_exists($f = dirname($theme_file). '/preview.png'))
$prev = $f;
else
$prev = $defprev;
//$theme['name'] = isset($theme['name'])? $theme['name'] : ($thm);
return
array( 'name' => $name,
'id' => $theme_id,
'title' => $theme,
'www' => $theme_uri,
'description' => $description,
'author' => $author,
'version' => $version,
'template' => $template,
'status' => $status,
'preview' => $prev
);
}
class admin_themes_default extends AdminPanelAction {
var $defprev = '';
var $commands = array('select');
function theme_list() {
global $fp_config;
$list = theme_list();
$info = array();
foreach ($list as $thm) {
// don't show current theme
if ($fp_config['general']['theme'] == $thm)
continue;
$theme = array();
$d = THEMES_DIR . $thm;
$f = $d . '/theme.conf.php';
$theme = admin_theme_data($d . '/theme.conf.php', $thm, $this->defprev);
$info[] = $theme;
}
return $info;
}
function setup() {
$this->defprev = BLOG_BASEURL . ADMIN_DIR . 'panels/'. ADMIN_PANEL .'/preview-default.png';
$current_theme = admin_theme_data(THEMES_DIR . THE_THEME . '/theme.conf.php', THE_THEME, $this->defprev);
$this->smarty->assign('current_theme', $current_theme);
$this->smarty->assign('available_themes', $this->theme_list());
}
function doselect($id) {
global $fp_config;
//$id = isset($_GET['select'])? $_GET['select'] : null;
if ($id) {
$id = sanitize_title($id);
if (theme_exists($id)) {
$fp_config['general']['theme'] = $id;
unset($fp_config['general']['style']);
//$t = theme_loadsettings();
//$fp_config['general']['style'] = $t['default_style'];
$return = config_save() ? 1 : -1;
} else {
$return = -2;
}
$this->smarty->assign('success', $return);
return 1;
}
}
function onerror() {
$this->main();
return 0;
}
function cleartplcache() {
// if theme was switched, clear tpl cache
$tpl =& new tpl_deleter();
$tpl->getList();
}
}
?>

View File

@ -0,0 +1,99 @@
<?php
class admin_themes_obj_style_idx extends fs_filelister {
function admin_themes_obj_style_idx() {
$this->_directory = THEMES_DIR . THE_THEME;
parent::fs_filelister();
}
function _checkFile($d, $f) {
$p = "$d/$f";
if (is_dir($p) && file_exists($p.'/style.conf.php'))
$this->_list[] = $f;
}
}
class admin_themes_style extends AdminPanelAction {
var $defprev = '';
var $commands = array('select');
function style_list() {
global $fp_config;
$o =& new admin_themes_obj_style_idx;
$list = $o->getList();
$info = array();
$based = THEMES_DIR . THE_THEME;
foreach ($list as $sty) {
// don't show current theme
//if ($fp_config['general']['theme'] == $thm)
// continue;
$style = array();
$d = "$based/$sty";
$f = $d . '/style.conf.php';
$style = admin_theme_data($f, $sty, $this->defprev);
$info[] = $style;
}
return $info;
}
function setup() {
global $fp_config;
$this->defprev = BLOG_BASEURL . ADMIN_DIR . 'panels/'. ADMIN_PANEL .'/preview-default.png';
$this->smarty->assign('current_style',
admin_theme_data(THEMES_DIR . THE_THEME . '/' .$fp_config['general']['style'] .'/style.conf.php', THE_THEME, $this->defprev));
$this->smarty->assign('available_styles', $this->style_list());
}
function doselect($id) {
global $fp_config;
if ($id) {
$id = sanitize_title($id);
if (theme_style_exists($id)) {
$fp_config['general']['style'] = $id;
$return = config_save() ? 1 : -1;
} else {
$return = -2;
}
$this->smarty->assign('success', $return);
return 2;
}
}
function onerror() {
$this->main();
return 0;
}
function cleartplcache() {
// if theme was switched, clear tpl cache
$tpl =& new tpl_deleter();
$tpl->getList();
}
}
?>

View File

@ -0,0 +1,33 @@
{include file=shared:errorlist.tpl}
<div id="current-theme">
<h2>{$panelstrings.head1}</h2>
<img src="{$current_style.preview}" alt="{$current_style.name}" />
<h5>{$current_style.title} &#8212; {$current_style.author|default:$panelstrings.noauthor}</h5>
{$current_style.description|default:$panelstrings.nodescr}
</div>
<div id="available-themes">
<h2>{$panelstrings.head2}</h2>
<p>{$panelstrings.descr}</p>
{if $available_styles}
<ul >
{foreach from=$available_styles item=thm}
<li>
<h5><a href="{$action_url|cmd_link:select:$thm.id}">{$thm.title}</a></h5>
<a href="{$action_url|cmd_link:select:$thm.id}"><img src="{$thm.preview}" alt="{$thm.name}" /></a>
<p>{$thm.description|default:$panelstrings.nodescr}</p>
</li>
{/foreach}
</ul>
{/if}
</div>

View File

@ -0,0 +1,33 @@
{include file=shared:errorlist.tpl}
<div id="current-theme">
<h2>{$panelstrings.head1}</h2>
<img src="{$current_theme.preview}" alt="{$current_theme.name}" />
<h5>{$current_theme.title} &#8212; {$current_theme.author|default:$panelstrings.noauthor}</h5>
{$current_theme.description|default:$panelstrings.nodescr}
</div>
<div id="available-themes">
<h2>{$panelstrings.head2}</h2>
<p>{$panelstrings.descr}</p>
{if $available_themes}
<ul>
{foreach from=$available_themes item=thm}
<li>
<h5><a href="{$action_url|cmd_link:select:$thm.id}">{$thm.title}</a></h5>
<a href="{$action_url|cmd_link:select:$thm.id}"><img src="{$thm.preview}" alt="{$thm.name}" /></a>
<p>{$thm.description|default:$panelstrings.nodescr}</p>
</li>
{/foreach}
</ul>
{/if}
</div>

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

View File

@ -0,0 +1,146 @@
<?php
/**
* uploader control panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
class uploader_lister extends fs_filelister {
var $_dirlist = array();
var $_filelist = array();
function uploader_lister($d, $pd) {
$this->urldir = $pd;
$this->basepanelurl =
BLOG_BASEURL .
"admin.php?p=uploader&amp;action=browse&amp;dir=";
$this->thumburl =
BLOG_BASEURL .
'admin.php?p=uploader&amp;action=thumb&amp;f=';
return parent::fs_filelister($d);
}
function _checkFile($d, $f) {
$p = "{$d}{$f}";
if (is_dir($p)) {
$this->_dirlist[$f]="{$this->basepanelurl}$f";
} else {
$lbl = $f;
$this->_filelist[$f]="{$this->thumburl}{$this->urldir}$f";
}
return parent::_checkFile($d,$f);
}
function getDirs() {
ksort($this->_dirlist);
return $this->_dirlist;
}
function getFiles() {
ksort($this->_filelist);
return $this->_filelist;
}
}
class admin_uploader_browse extends AdminPanelAction {
var $events = array('upload');
function main() {
if (!empty($_GET['dir'])) {
$dir = $_GET['dir'];
if (substr($_GET['dir'], -1)!= '/')
$dir.= '/';
} else {
$dir = './';
}
$pd = $dir;
$dir = ABS_PATH.IMAGES_DIR.$dir;
$o = new uploader_lister($dir, $pd);
if ($dir != '')
$this->smarty->assign('parent', $o->basepanelurl.dirname($dir));
$this->smarty->assign('dirs', $o->getDirs());
$this->smarty->assign('files', $o->getFiles());
}
function onupload() {
$success = false;
if (!file_exists(IMAGES_DIR))
fs_mkdir(IMAGES_DIR);
if (!file_exists(ATTACHS_DIR))
fs_mkdir(ATTACHS_DIR);
$imgs = array('.jpg','.gif','.png', '.jpeg');
//intentionally
//I've not put BMPs
$uploaded_files=array();
foreach ($_FILES["upload"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["upload"]["tmp_name"][$key];
$name = $_FILES["upload"]["name"][$key];
$dir = ATTACHS_DIR;
$ext = strtolower(strrchr($name,'.'));
if (in_array($ext,$imgs)) {
$dir = IMAGES_DIR;
}
$name = sanitize_title(substr($name, 0, -strlen($ext))) . $ext;
$target = "$dir/$name";
@umask(022);
$success = move_uploaded_file($tmp_name, $target);
@chmod($target,0766);
$uploaded_files[] = $name;
$success &= $success;
}
}
if ($uploaded_files) {
$this->smarty->assign('success', $success? 1 : -1);
sess_add('admin_uploader_files', $uploaded_files);
}
return 1;
}
}
?>

View File

@ -0,0 +1,59 @@
<h2>{$panelstrings.head}</h2>
<p>{$panelstrings.descr}</p>
{include file='shared:errorlist.tpl'}
<form method="post"
action="{$smarty.const.BLOG_BASEURL}admin.php?{$smarty.server.QUERY_STRING|escape:"html"}"
enctype="multipart/form-data">
{*<fieldset><legend>{$panelstrings.fset1}</legend>
<input type="file" name="upload[]" />
<div class="alignright">
{html_submit name="upload" id="upload" value=$panelstrings.submit}
</div>
</fieldset>
*}
<div>
{foreach from=$dirs item=dirpath key=dirname}
<ul><li> <a href="{$dirpath}"> {$dirname} </a> </li></ul>
{/foreach}
{if $files}
<ul id="admin-uploader-thumbs">
{foreach from=$files item=filepath key=filename}
<li class="thumb">
<h5>{$filename}</h5>
<a href="{$filepath}"><img src="{$filepath}" alt="{$filename}" /></a>
</li>
{/foreach}
</ul>
{/if}
</div>
{*
<table>
<thead><tr><th> name </th><th> date </th></tr></thead>
<tbody>
<tr><td> <a href="{$parent}"> .. </a> </td> <td> ... </td></tr>
{foreach from=$dirs item=dirpath key=dirname}
<tr><td> <a href="{$dirpath}">{$dirname} </a> </td> <td> ... </td></tr>
{/foreach}
{foreach from=$files item=filepath key=filename}
<tr><td> {$filename} </td> <td> ... </td></tr>
{/foreach}
</tbody>
</table>
*}
</form>

View File

@ -0,0 +1,89 @@
<?php
/**
* uploader control panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
class admin_uploader extends AdminPanel {
var $panelname = 'uploader';
var $actions = array('default'=>true);
}
class admin_uploader_default extends AdminPanelAction {
var $events = array('upload');
function main() {
if ($f = sess_remove('admin_uploader_files'))
$this->smarty->assign('uploaded_files', $f);
}
function onupload() {
$success = false;
if (!file_exists(IMAGES_DIR))
fs_mkdir(IMAGES_DIR);
if (!file_exists(ATTACHS_DIR))
fs_mkdir(ATTACHS_DIR);
$imgs = array('.jpg','.gif','.png', '.jpeg');
//intentionally
//I've not put BMPs
$uploaded_files=array();
foreach ($_FILES["upload"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["upload"]["tmp_name"][$key];
$name = $_FILES["upload"]["name"][$key];
$dir = ATTACHS_DIR;
$ext = strtolower(strrchr($name,'.'));
if (in_array($ext,$imgs)) {
$dir = IMAGES_DIR;
}
$name = sanitize_title(substr($name, 0, -strlen($ext))) . $ext;
$target = "$dir/$name";
@umask(022);
$success = move_uploaded_file($tmp_name, $target);
@chmod($target,0766);
$uploaded_files[] = $name;
// one failure will make $success == false :)
$success &= $success;
}
}
if ($uploaded_files) {
$this->smarty->assign('success', $success? 1 : -1);
sess_add('admin_uploader_files', $uploaded_files);
}
return 1;
}
}
?>

View File

@ -0,0 +1,84 @@
<?php
/*
// useful snippet http://ontosys.com/php/cache.html, but looks like it doesn't in this case
$if_modified_since = preg_replace('/;.*$/', '', @$_SERVER['HTTP_IF_MODIFIED_SINCE']);
$mtime = filemtime($fpath);
$gmdate_mod = gmdate('D, d M Y H:i:s', $mtime) . ' GMT';
if ($if_modified_since == $gmdate_mod) {
header("HTTP/1.0 304 Not Modified");
exit;
}
header("Last-Modified: $gmdate_mod");
*/
function thumb_send($fpath) {
$MAX = 100;
// we support only jpeg's, png's and gif's
$infos = getimagesize($fpath);
list($w, $h) = $infos;
if ($w<=$MAX && $h<=$MAX) {
switch ($infos[2]) {
case 1: header('Content-Type: image/gif'); break;
case 2: header('Content-Type: image/jpeg'); break;
case 3: header('Content-Type: image/png'); break;
}
readfile($fpath);
return;
}
switch($infos[2]) {
case 1: $image = imagecreatefromgif($fpath); break;
case 2: $image = imagecreatefromjpeg ($fpath); break;
case 3: $image = imagecreatefrompng($fpath);
}
if ($w>$h) {
$ratio = $w/$h;
$new_width = $MAX;
$new_height = (int)($MAX/$ratio);
} else {
$ratio = $h/$w;
$new_height = $MAX;
$new_width = (int)($MAX/$ratio);
}
$scaled = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($scaled, $image, 0, 0, 0, 0, $new_width, $new_height, $infos[0], $infos[1]);
header('Content-Type: image/jpeg');
imagejpeg($scaled);
}
if (isset($_GET['f'])) {
$f = ABS_PATH . IMAGES_DIR . $_GET['f'];
if ( strpos ($f, '..') !== false)
return;
if (file_exists($f)) {
thumb_send($f);
}
}
exit();
?>

View File

@ -0,0 +1,46 @@
{if $smarty.request.mod != 'inline'}
<h2>{$panelstrings.head}</h2>
<p>{$panelstrings.descr}</p>
{/if}
{include file='shared:errorlist.tpl'}
{if $success}
<ul id="admin-uploader-filelist">
{foreach from=$uploaded_files item=file}
{*
memo: this did the trick in the panel
<a href="javascript:window.parent.window.insImage('{$file}');">
*}
<li>{$file}</li>
{/foreach}
</ul>
{/if}
{html_form}
{if $smarty.request.mod != 'inline'}
<fieldset><legend>{$panelstrings.fset1}</legend>
{/if}
<input type="file" name="upload[]" />
<input type="file" name="upload[]" />
<input type="file" name="upload[]" />
<input type="file" name="upload[]" />
<input type="file" name="upload[]" />
<input type="file" name="upload[]" />
<input type="file" name="upload[]" />
<input type="file" name="upload[]" />
{if $smarty.request.mod != 'inline'}
</fieldset>
{/if}
<div class="buttonbar">
{html_submit name="upload" id="upload" value=$panelstrings.submit}
</div>
{/html_form}

View File

@ -0,0 +1,119 @@
<?php
function admin_widgets_head() {
echo '<script type="text/javascript" src="'.BLOG_BASEURL.ADMIN_DIR.'panels/widgets/admin.widgets.js"></script>';
}
add_action('wp_footer', 'admin_widgets_head');
class admin_widgets_default extends AdminPanelAction {
//var $validators = array(array('content', 'content', 'notEmpty', false, false));
var $events = array('save');
function get_widget_lists($wlist, $wpos, &$widget_list, $registered_w, $add_empties) {
if (!isset($wlist[$wpos]))
return;
$widget_list[$wpos] = array();
foreach($wlist[$wpos] as $idx => $wdg) {
$widget_list[$wpos][$idx] = array();
@list($newid, $params) = explode(":", $wdg);
$widget_list[$wpos][$idx]['id'] = $newid;
if (isset($registered_w[$newid])){
$thiswdg =& $registered_w[$newid];
$widget_list[$wpos][$idx]['name'] = $thiswdg['name'];
if ($thiswdg['nparams'] > 0) {
$widget_list[$wpos][$idx]['params'] = $params;
}
/*
* here should go the check for
* limited parameters: parameters limited to a
* particular set would mean using a <select> control
* in the template
*
*/
} else {
$widget_list[$wpos][$idx]['name'] = $newid;
$widget_list[$wpos][$idx]['class'] = 'warnings';
}
}
if (!$widget_list[$wpos] && !$add_empties)
unset($widget_list[$wpos]);
}
function main() {
lang_load('admin.widgets');
$this->smarty->assign('warnings', admin_widgets_checkall());
global $fp_widgets;
$registered_w = get_registered_widgets();
$registered_ws = get_registered_widgetsets(null);
$this->smarty->assign('fp_registered_widgets', $registered_w);
$wlist = $fp_widgets->getList();
$widget_list = array();
foreach($registered_ws as $wpos) {
$widget_list[$wpos] = array();
$this->get_widget_lists($wlist, $wpos, $widget_list, $registered_w, true);
unset($wlist[$wpos]);
}
$oldwidget_list = array();
foreach($wlist as $wpos => $c){
$this->get_widget_lists($wlist, $wpos, $oldwidget_list, $registered_w, false);
}
$this->smarty->assign('widgetlist', $widget_list);
$this->smarty->assign('oldwidgetlist', $oldwidget_list);
$conf = io_load_file(CONFIG_DIR . 'widgets.conf.php');
$this->smarty->assign('pluginconf', $conf);
return 0;
}
function onsave() {
$fp_widgets = isset($_POST['widgets'])? $_POST['widgets'] : array();
$success = system_save(CONFIG_DIR . 'widgets.conf.php', compact('fp_widgets'));
$this->smarty->assign('success', ( $success )? 1 : -1 );
return 1;
}
}
?>

View File

@ -0,0 +1,326 @@
/*
* DISCLAIMER
*
* a lot of this is just spaghetti (pizza and mandolino) code,
* it's my first attempt at JS, and I know it's just a mess...
*
* if you want, you can clean it up and then send it back to me :P
* otherwise I'll just do it myself once I'm done with the rest ;)
*
*/
/*
new Drag.Move(
$('available-widgets'),
{'handle': $$('#available-widgets h3')[0]}
);
*/
Drag.MultiDrop = Drag.Move.extend({
drag: function(event) {
this.droppables = Widgets.droppables;
this.parent(event);
return this;
},
checkAgainst: function(el) {
// console.log(this);
if (this.element == el)
return false;
return this.parent(el);
}
});
var fx = [];
var wtrash = $('widget-trashcan');
var mydropp = $$('#admin-widgetset-list li.admin-widgetset li.widget-instance');
var avail = $$('li.widget-class');
var Widgets = {
'droppables' : [wtrash].extend(mydropp),
'available' : avail,
'inputPlaceHld': '<insert text here>',
'inputChange': function() {
this_input = this;
input = this_input.getParent().getChildren().filterByClass('widget-id')[0];
regex = /^([^:]+)/;
id = regex(input.value);
if (this_input.value.trim() == ''){
this_input.value=Widgets.inputPlaceHld;
return;
}
input.set({
'value' : id[1] + ':' + this_input.value
});
},
'doDrag': function(drag) {
var input = drag.getChildren().filterByClass('textinput')[0];
if (input) {
input.addEvent('blur', Widgets.inputChange);
}
drag.addEvents({
'mousedown' : function(e, el) {
e = new Event(e).stop();
// console.log($type(e.target));
if (e.target.getTag() == 'input'){
if (e.target.getValue() == Widgets.inputPlaceHld)
e.target.value = '';
e.target.focus();
e.target.select();
return;
}
ghost = this.clone();
ghost.ghostParent = this;
ghost.setStyles(drag.getCoordinates());
ghost.setStyles({
'position': 'absolute',
'opacity' : 0.7,
'background-color' : '#b31'
});
ghost.inject($$('body')[0]);
ghost.addClass('widget-dragger');
dragger = new Drag.MultiDrop(ghost, {
'onStart' : function(el) {
Widgets.scroller.start();
}
});
ghost.addEvent('emptydrop', function(el) {
this.remove();
Widgets.scroller.stop();
});
dragger.start(e);
}
});
},
'doDrop' : function(drop, index){
drop.fx = drop.effects({'transition': Fx.Transitions.linear });
drop.addEvents({
'over': function(el, obj){
this.setStyle('background-color', '#78ba91');
},
'leave': function(el, obj){
this.setStyle('background-color', '#fff');
},
'drop': function(el, obj){
original = el.ghostParent;
el.remove();
dropper = drop;
if (original.hasClass('widget-class')) {
var newclone = original.clone();
newclone.removeClass('widget-class');
newclone.addClass('widget-instance');
Widgets.doDrag(newclone);
Widgets.droppables.include(newclone);
newindex = Widgets.droppables.indexOf(newclone)
Widgets.doDrop(newclone, newindex);
newclone.injectAfter(drop);
dropped = newclone;
parentid = drop.getParent().id;
widgetsetid = /^widgetsetid-(.*)$/(parentid);
input = dropped.getChildren().filterByClass('widget-id')[0];
input.set({
'name' : 'widgets[' + widgetsetid[1] + '][]'
});
txtinput = dropped.getChildren().filterByClass('textinput')[0];
if (txtinput){
txtinput.set({
// 'name' : 'widgets[' + widgetsetid[1] + '][]'
'type': 'text',
'value': Widgets.inputPlaceHld
});
}
} else {
newindex = Widgets.droppables.indexOf(original);
par = original.getParent();
original.injectAfter(drop);
dropped = original;
newparent = dropped.getParent();
parentid = newparent.id;
input = dropped.getChildren().filterByClass('widget-id')[0];
widgetsetid = /^widgetsetid-(.*)$/(parentid);
input.set({
'name' : 'widgets[' + widgetsetid[1] + '][]'
});
if (par.getChildren().length <= 0) {
newe = new Element('li', {
'class' : 'widget-placeholder'
});
newe.setText('Drop here');
Widgets.droppables.include(newe);
// newindex = Widgets.droppables.indexOf(newe);
Widgets.doDrop(newe, newindex);
newe.inject(par);
// dropper = newe;
};
}
if (drop.hasClass('widget-placeholder')) {
Widgets.droppables.remove(drop);
drop.remove();
}
dropped.fx.start({
'background-color' : ['#78ba91', '#fff']
});
// dropped
dropper.fx.start({
'background-color' : ['#b31', '#fff']
});
Widgets.scroller.stop();
}
});
},
'doTrash' : function(drop, index){
drop.fx = drop.effects({'transition': Fx.Transitions.linear });
drop.addEvents({
'over': function(el, obj){
if (el.ghostParent.hasClass('widget-instance'))
this.setStyle('background-color', '#faa');
},
'leave': function(el, obj){
if (el.ghostParent.hasClass('widget-instance'))
this.setStyle('background-color', '#a22');
},
'drop': function(el, obj){
Widgets.scroller.stop();
original = el.ghostParent;
el.remove();
if (original.hasClass('widget-class')) {
return;
} else {
dropper = drop;
newindex = Widgets.droppables.indexOf(original);
par = original.getParent();
original.remove();
if (par.getChildren().length <= 0) {
newe = new Element('li', {
'class' : 'widget-placeholder'
});
newe.setText('Drop here');
Widgets.droppables.include(newe);
// newindex = Widgets.droppables.indexOf(newe);
Widgets.doDrop(newe, newindex);
newe.inject(par);
// dropper = newe;
};
}
dropper.fx.start({
'background-color' : ['#faa', '#a22']
});
}
});
},
'scroller' : new Scroller(window, {'velocity': 0.5}),
'palette' : $('available-widgets')
};
mydropp.each(Widgets.doDrop);
mydropp.each(Widgets.doDrag);
Widgets.doTrash(wtrash);
var placeholders = $$('li.widget-placeholder');
placeholders.each(Widgets.doDrop);
Widgets.droppables.extend(placeholders);
avail.each(Widgets.doDrag);
/*
Widgets.palette.fx =
Widgets.palette.effects({'transition': Fx.Transitions.linear});
Widgets.palette.startTop = Widgets.palette.getTop();
Widgets.palette.setStyles(Widgets.palette.getCoordinates());
Widgets.palette.setStyle('position', 'absolute');
Widgets.palette.injectInside(document.body);
window.addEvent('scroll',
function() {
top = window.getScrollTop();
if (top > Widgets.palette.startTop)
Widgets.palette.setStyle('top', top);
}
);
*/

View File

@ -0,0 +1,47 @@
<?php
/**
* plugin control panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
class admin_widgets extends AdminPanel {
var $panelname = "widgets";
var $actions = array('default' => true, 'raw' => true);
}
function admin_widgets_checkall() {
global $fp_widgets, $lang;
$list = $fp_widgets->getList();
if (!($list)) return array();
$errs = array();
foreach ($list as $pos => $group) {
if (is_array($group)) {
foreach ($group as $id) {
list($newid) = explode(":", $id);
$var = 'plugin_' . $newid . '_widget';
if (!function_exists($var)) {
$errs = sprintf($lang['admin']['widgets']['errors']['generic'], $newid);
}
}
}
}
return $errs;
}
?>

View File

@ -0,0 +1,60 @@
<?php
/**
* plugin control panel
*
* Type:
* Name:
* Date:
* Purpose:
* Input:
*
* @author NoWhereMan <real_nowhereman at users dot sf dot com>
*
*/
class admin_widgets_raw extends AdminPanelActionValidated {
var $validators = array(array('content', 'content', 'notEmpty', false, false));
var $events = array('save');
function main() {
lang_load('admin.widgets');
$this->smarty->assign('warnings', admin_widgets_checkall());
$conf = io_load_file(CONFIG_DIR . 'widgets.conf.php');
$this->smarty->assign('pluginconf', $conf);
return 0;
}
function onsave() {
$str=stripslashes($_POST['content']);
$tmp = $str;
$tmp = str_replace('<?php', '', $tmp);
$tmp = str_replace('<?', '', $tmp);
$tmp = str_replace('?>', '', $tmp);
if (@eval($tmp) !== false)
$success = io_write_file(CONFIG_DIR . 'widgets.conf.php', $str);
else
$success = false;
$this->smarty->assign('success', ( $success )? 1 : -1 );
$this->smarty->assign('pluginconf', $str);
return $success;
}
}
?>

View File

@ -0,0 +1,25 @@
{*assign var=panelstrings value=`$panelstrings.raw`*}
{validate id="content" message=$panelstrings.error.content append="error"}
<h2>{$panelstrings.head}</h2>
<p>{$panelstrings.descr}</p>
{include file='shared:errorlist.tpl'}
<form method="post"
action="{$smarty.const.BLOG_BASEURL}admin.php?{$smarty.server.QUERY_STRING|escape:"html"}"
enctype="multipart/form-data">
<p>
<textarea name="content" id="content"
class="code" rows="20" cols="74">{$pluginconf|escape}</textarea><br />
</p>
<div class="buttonbar">
{html_submit name="save" id="save" value=$panelstrings.submit}
</div>
</form>

View File

@ -0,0 +1,107 @@
<h2>{$panelstrings.head}</h2>
<p>{$panelstrings.descr}</p>
{include file='shared:errorlist.tpl'}
{html_form}
<div id="available-widgets">
<h2>{$panelstrings.availwdgs}</h2>
<div id="widget-trashcan">
{$panelstrings.trashcan}
</div>
<ul>
{foreach from=$fp_registered_widgets key=widgetid item=widget}
<li class="widget-class widget-id-{$widgetid}">
{* those are actually dummies just to have two inputs ready, but they might come handy *}
<input class="widget-id" type="hidden" name="avalwidg[]" value="{$widgetid}" />
{if $widget.nparams > 0}
{* class is for javascript: this input will be converted into a type="text" :) *}
<input class="textinput" style="float:right" type="hidden" />
{/if}
<p>{$widget.name}</p>
</li>
{/foreach}
</ul>
<div class="buttonbar">
<input type="submit" name="save" value="{$panelstrings.submit}" />
</div>
</div>
<div id="admin-widgetset-list">
<h2>{$panelstrings.themewdgs}</h2>
<p>{$panelstrings.themewdgsdescr}</p>
<ul>
{foreach from=$widgetlist key=widgetset item=widgetarr}
<li class="admin-widgetset">
<h3 class="widgetset-name">
{$panelstrings.stdsets[$widgetset]|default:$widgetset}
</h3>
<ul id="widgetsetid-{$widgetset}">
{foreach from=$widgetarr item=widget}
<li class="widget-instance widget-id-{$widget.id}">
<input class="widget-id" type="hidden" name="widgets[{$widgetset}][]"
value="{$widget.id}{if $widget.params}:{$widget.params}{/if}" />
{if $widget.params}
{* this will be hooked from javascript *}
<input class="textinput" style="float:right"
type="text" value="{$widget.params}"/>
{/if}
<p> {$widget.name} </p>
</li>
{foreachelse}
<li class="widget-placeholder"> Drop here </li>
{/foreach}
</ul>
</li>
{/foreach}
</ul>
{if $oldwidgetlist}
<h2>{$panelstrings.oldwdgs}</h2>
<p>{$panelstrings.oldwdgsdescr}</p>
{foreach from=$oldwidgetlist key=widgetset item=widgetarr}
<li class="admin-widgetset">
<h3 class="widgetset-name">
{$panelstrings.stdsets[$widgetset]|default:$widgetset}
</h3>
<ul id="widgetsetid-{$widgetset}">
{foreach from=$widgetarr item=widget}
<li class="widget-instance widget-id-{$widget.id}">
<input class="widget-id" type="hidden" name="widgets[{$widgetset}][]"
value="{$widget.id}{if $widget.params}:{$widget.params}{/if}" />
{if $widget.params}
{* this will be hooked from javascript *}
<input class="textinput" style="float:right"
type="text" value="{$widget.params}"/>
{/if}
<p> {$widget.name} </p>
</li>
{foreachelse}
<li class="widget-placeholder"> Drop here </li>
{/foreach}
</ul>
</li>
{/foreach}
{/if}
</div>
<div class="buttonbar">
{html_submit name="save" id="save" value=$panelstrings.submit}
</div>
{/html_form}

197
admin/res/admin.css Executable file
View File

@ -0,0 +1,197 @@
/*
compatibility for old themes, soon
this hackish and ugly css will be
DROPPED
*/
#admin-tabmenu {
text-align: left;
padding-right: 0px;
padding-left: 0px;
z-index: 1;
padding-bottom: 0px;
margin: 12px 0px 0px;
padding-top: 0px;
border-bottom: black 2px solid;
font-size: 80%;
_font-size: 90%;
font-weight: normal;
}
#admin-tabmenu li {
display: inline;
overflow: hidden;
list-style-type: none;
padding-left: -10px
}
#admin-tabmenu a {
border-right: black 2px solid;
padding-right: 5px;
border-top: black 2px solid;
padding-left: 5px;
background: #f9f9f9;
padding-bottom: 0px;
margin: 0px;
border-left: black 2px solid;
padding-top: 2px;
border-bottom: black 2px solid;
text-decoration: none
}
#cpmain ul, #main li{
list-style-type:none;
}
#cpmain ul li:before {
content: none;
}
#admin-tabmenu a#admin-tab-current {
background: #f9f9f9;
color: black;
border-bottom: #f9f9f9 3px solid;
}
.admin-mainmenu-item {
clear:both;
display:block;
padding:1em;
}
#admin-content {
border-right: black 2px solid;
padding-right: 20px;
border-top: black 2px;
padding-left: 20px;
z-index: 2;
padding-bottom: 20px;
border-left: black 2px solid;
padding-top: 20px;
border-bottom: black 2px solid;
_font-size: 1em;
}
#admin-content table {
border-collapse: collapse;
width: 100%;
_width: 470px;
_font-size:100%;
}
#admin-content td {
border-bottom: solid 1px black;
width: 8px;
font-size: 0.8em;
_font-size:1em;
padding: 4px;
}
#admin-content td.main_cell {
text-align: left;
font-weight: bold;
width: 20%;
}
#admin-content th {
border-bottom: solid 2px black;
padding: 4px;
font-size: 0.75em;
_font-size: 100%;
font-style: italic;
}
#subject {
font-size: 18px;
font-weight: bold;
width: 99%;
}
.underOpt {
font-size: 80%;
font-style: oblique;
margin: .5em 0 0 0
}
.maxsize {
width: 99%;
}
input.maxsize { width: 99% }
.msg {
font-weight: bold;
}
.error {
color: red;
padding-left: 10px;
}
.disabled {
background-color: red;
}
.enabled {
background-color: green;
}
.locked {
background-color: grey;
}
.draft {
background-color: lightgrey;
}
/* ===== NOTIFICATION ===== */
#main ul.msgs, ul.msgs {
margin-top: 1em;
margin-left: 0em;
padding: 1em 2em
}
.errors {
color: #901d1d;
border-top: 1px solid;
border-bottom: 1px solid;
border-color: #ffbbbb;
background: #ffdddd
}
.errors a {
color: #901d1d;
text-decoration: underline;
font-weight: normal
}
.notifications {
color : #1d901d;
border-top: 1px solid #bbffbb;
border-bottom: 1px solid #bbffbb;
background: #ddffdd
}
.field-error {
border: red 1px solid;
background: #fdd
}

10
blog.php Executable file
View File

@ -0,0 +1,10 @@
<?php
// Example of use
require_once 'defaults.php';
require_once (INCLUDES_DIR.'includes.php');
@utils_status_header(301);
@utils_redirect('?'.$_SERVER['QUERY_STRING']);
?>

223
comments.php Normal file
View File

@ -0,0 +1,223 @@
<?php
if (!defined('MOD_INDEX')) {
include 'defaults.php';
include INCLUDES_DIR . 'includes.php';
@utils_status_header(301);
@utils_redirect("?entry={$_GET['page']}&comments");
}
$module = comment_main($module);
function comment_main($module) {
global $fpdb;
// hackish solution to get title before fullparse starts dunno, I don't like it
$q =& $fpdb->getQuery();
list($id, $entry) = $q->peekEntry();
if (!empty($_GET['feed'])){
switch($_GET['feed']) {
case 'atom':
header('Content-type: application/atom+xml');
$module = SHARED_TPLS . 'comment-atom.tpl';
break;
case 'rss2':
default:
header('Content-type: application/rss+xml');
$module = SHARED_TPLS . 'comment-rss.tpl';
}
} elseif (!in_array('commslock', $entry['categories'])) {
commentform();
}
return $module;
}
function comment_feed() {
echo "\n<link rel=\"alternate\" type=\"application/rss+xml\" title=\"Get Comments RSS 2.0 Feed\" href=\"".
theme_comments_feed_link('rss2', $_GET['entry'])
."\" />";
echo "\n<link rel=\"alternate\" type=\"application/atom+xml\" title=\"Get Comments Atom 1.0 Feed\" href=\"".
theme_comments_feed_link('atom', $_GET['entry'])
."\" />\n";
}
add_action('wp_head', 'comment_feed');
function comment_validate() {
$arr['version'] = system_ver();
$arr['name'] = $_POST['name'];
$loggedin = false;
if (user_loggedin()) {
$loggedin = $arr['loggedin']=true;
}
if (!$loggedin)
setcookie('comment_author_' . COOKIEHASH,
$arr['name'], time() + 30000000, COOKIEPATH, COOKIE_DOMAIN);
if (!empty($_POST['email'])) {
($arr['email'] = $_POST['email']);
if (!$loggedin)
setcookie('comment_author_email_' . COOKIEHASH,
$arr['email'], time() + 30000000, COOKIEPATH, COOKIE_DOMAIN);
}
if (!empty($_POST['url'])) {
($arr['url'] = ( $_POST['url'] )) ;
if (!$loggedin)
setcookie('comment_author_url_' . COOKIEHASH,
$arr['url'], time() + 30000000, COOKIEPATH, COOKIE_DOMAIN);
}
$arr['content'] = $_POST['content'];
$arr['ip-address'] = utils_ipget();
if (apply_filters('comment_validate', true, $arr))
return $arr;
else return false;
}
function commentform() {
global $smarty, $lang, $fpdb;
$comment_formid = 'fp-comments';
$smarty->assign('comment_formid', $comment_formid);
if(empty($_POST)) {
if(!SmartyValidate::is_registered_form($comment_formid)) {
// new form, we (re)set the session data
SmartyValidate::connect($smarty, true);
SmartyValidate::register_form($comment_formid, true);
// register our validators
SmartyValidate::register_validator('name', 'name', 'notEmpty', false, false, 'trim,stripslashes', $comment_formid);
SmartyValidate::register_validator('email','email', 'isEmail', true, false, 'trim,stripslashes', $comment_formid);
SmartyValidate::register_validator('www', 'url', 'isURL', true, false, 'trim,stripslashes', $comment_formid);
SmartyValidate::register_validator('comment', 'content', 'notEmpty', false, false, 'stripslashes', $comment_formid);
}
} else {
utils_nocache_headers();
// validate after a POST
SmartyValidate::connect($smarty, true);
// add http to url
if (!empty($_POST['url']) && strpos($_POST['url'], 'http://')===false)
$_POST['url'] = 'http://'.$_POST['url'];
// custom hook here!!
if( SmartyValidate::is_valid($_POST, $comment_formid) && ($arr=comment_validate())) {
//SmartyValidate::disconnect();
global $fp_config;
$id = comment_save($_GET['entry'], $arr);
do_action('comment_post', $_GET['entry'], array($id, $arr));
if ($fp_config['general']['notify'] && !user_loggedin()) {
$comm_mail = isset($arr['email'])? "<{$arr['email']}>" : '';
$from_mail = $comm_mail? $arr['email'] : $fp_config['general']['email'];
$q =& new FPDB_Query(array('entry'=>$_GET['entry'],'fullparse'=>false), null);
list($id, $e) = $q->getEntry();
$lang = lang_load('comments');
$mail = str_replace(
array(
'%toname%',
'%fromname%',
'%frommail%',
'%entrytitle%',
'%commentlink%',
'%content%',
'%blogtitle%'
),
array(
$fp_config['general']['author'],
$arr['name'],
$comm_mail,
$e['subject'],
get_comments_link($_GET['entry']) . '#'.$id,
$arr['content'],
$fp_config['general']['title']
),
$lang['comments']['mail']
);
@utils_mail($from_mail, "New comment on {$fp_config['general']['title']}",
$mail);
}
// if comment is valid, this redirect will clean the postdata
$location = str_replace(
'&amp;', '&',
apply_filters(
'comments_link',
'',
$_GET['entry'])
) . '#'.$id;
utils_redirect($location,true);
exit();
} else {
$smarty->assign('values', $_POST);
}
}
// Cookies
$smarty->assign('cookie', array(
'name' => @$_COOKIE['comment_author_' . COOKIEHASH],
'email' => @$_COOKIE['comment_author_email_' . COOKIEHASH],
'url' => @$_COOKIE['comment_author_url_' . COOKIEHASH]
));
}
?>

111
contact.php Executable file
View File

@ -0,0 +1,111 @@
<?php
require_once 'defaults.php';
require_once (INCLUDES_DIR.'includes.php');
require SMARTY_DIR . 'SmartyValidate.class.php';
function contact_form_validate() {
$arr['version'] = system_ver();
$arr['name'] = $_POST['name'];
if (!empty($_POST['email']))
($arr['email'] = $_POST['email']);
if (!empty($_POST['url']))
($arr['url'] = $_POST['url']);
$arr['content'] = $_POST['content'];
$arr['ip-address'] = utils_ipget();
if (apply_filters('comment_validate', true, $arr))
return $arr;
else return false;
}
function contact_form() {
global $smarty, $lang;
$smarty->assign('notifications',system_geterr('contact'));
if(empty($_POST)) {
// new form, we (re)set the session data
SmartyValidate::connect($smarty, true);
// register our validators
SmartyValidate::register_validator('name', 'name', 'notEmpty', false, false, 'trim');
SmartyValidate::register_validator('email', 'email', 'isEmail', true, false, 'trim');
SmartyValidate::register_validator('www', 'url', 'isURL', true, false, 'trim');
SmartyValidate::register_validator('content', 'content', 'notEmpty', false, false);
} else {
utils_nocache_headers();
// validate after a POST
SmartyValidate::connect($smarty);
if (!empty($_POST['url']) && strpos($_POST['url'], 'http://')===false) $_POST['url'] = 'http://'.$_POST['url'];
// custom hook here!!
// we'll use comment actions, anyway
if(SmartyValidate::is_valid($_POST) && $arr=contact_form_validate()) {
$msg = "Name: \n{$arr['name']} \n\n";
if (isset($arr['email']))
$msg .= "Email: {$arr['email']}\n\n";
if (isset($arr['url']))
$msg .= "WWW: {$arr['url']}\n\n";
$msg .= "Content:\n{$arr['content']}\n";
@utils_mail(
(
isset($arr['email'])?
$arr['email']
:
$this->config['EMAIL']
),
"Contact sent through {$fp_config['general']['title']} ", $msg );
system_seterr('contact', 1);
utils_redirect();
} else {
$smarty->assign('values', $_POST);
}
}
}
function contact_main() {
global $smarty;
$lang = lang_load('contact');
$smarty->assign('subject', $lang['contact']['head']);
$smarty->assign('content', 'shared:contact.tpl');
contact_form();
}
function contact_display() {
global $smarty;
contact_main();
theme_init($smarty);
$smarty->display('default.tpl');
unset($smarty);
do_action('shutdown');
}
system_init();
contact_display();
?>

108
defaults.php Executable file
View File

@ -0,0 +1,108 @@
<?php
// defaults.php
// this file defines standard positions of some important
// dirs or files.
// For security reasons
// these can't be modified in the common settings panels
// but only through this file.
// If you want to change these constants, just change
// the second parameter.
// We suggest not to define here your owns, but instead
// inmplementing them as plugins
// legacy mode; needed with some ill-formed spb files
define('DUMB_MODE_ENABLED', false);
// first some webserver setup...
// here's where your server save session-related stuff.
// If you don't experience any session-related problem, you
// you can leave it blank and it will default to standard webserver config
define('SESSION_PATH', '');
// absolute path to your webserver dir; if you don't experience any problem
// you can leave this as it is
define('ABS_PATH', dirname(__FILE__).'/');
// here was blog root in earlier versions. This has been moved to config_load()
// here are default config files
define('FP_DEFAULTS', 'fp-defaults/');
// all writable directories go here.
define('FP_CONTENT', 'fp-content/'); //must be chmodded to 0777
// blog configurations files
define('CONFIG_DIR', FP_CONTENT . 'config/'); //must be chmodded to 0777
define('CONFIG_FILE', CONFIG_DIR . 'settings.conf.php');
define('CONFIG_DEFAULT', FP_DEFAULTS. 'settings-defaults.php');
define('USERS_DIR', FP_CONTENT . 'users/');
// here we'll store all your entries, comments, static pages and blocks
// comments are stored automatically in subdirs of the dir CONTENT_DIR
define('CONTENT_DIR', FP_CONTENT . 'content/');
//define('BLOCKS_DIR', CONTENT_DIR . 'blocks/');
// !!! CRITICAL !!!
// all includes file
define('FP_INCLUDES', 'fp-includes/');
// core include scripts
define('INCLUDES_DIR', FP_INCLUDES . 'core/');
// smarty engine
define('SMARTY_DIR', ABS_PATH . FP_INCLUDES . 'smarty/');
define('FP_INTERFACE', 'fp-interface/');
// theme dir
define('THEMES_DIR', FP_INTERFACE . 'themes/');
// language files
define('LANG_DIR', FP_INTERFACE . 'lang/');
// misc forms
define('SHARED_TPLS', ABS_PATH . FP_INTERFACE . 'sharedtpls/');
// here is where all plugins are saved
define('PLUGINS_DIR', 'fp-plugins/');
define('ADMIN_DIR', 'admin/');
// cache file name and path.
define('CACHE_DIR', FP_CONTENT . 'cache/');
define('CACHE_FILE', '%%cached_list.php');
define('LOCKFILE', FP_CONTENT . '%%setup.lock');
// these will be probably moved soon to plugins
// here is where all the uploaded images will be saved
define('IMAGES_DIR', FP_CONTENT . 'images/');
// here is where all the attachments will be saved
define('ATTACHS_DIR', FP_CONTENT . 'attachs/');
define('LANG_DEFAULT', 'en-us');
set_include_path(ABS_PATH);
// compatibility with ISS
if (!isset($_SERVER['REQUEST_URI']))
$_SERVER['REQUEST_URI'] = 'http://localhost/flatpress/';
#define('BLOG_ROOT', dirname($_SERVER['PHP_SELF']) . '/');
define('BLOG_ROOT', ('/'==($v=dirname($_SERVER['PHP_SELF']))? $v : $v.'/') );
define('BLOG_BASEURL', 'http://'.$_SERVER['HTTP_HOST']. BLOG_ROOT);
?>

1089
docs/README-SmartyValidate Executable file

File diff suppressed because it is too large Load Diff

35
docs/spb_db.txt Executable file
View File

@ -0,0 +1,35 @@
==========================================================
CONSIDERATIONS AROUND SIMPLEPHPBLOG AND ITS STORING SYSTEM
==========================================================
- SimplePHPBlog flat "db" structure
[$content]
|
|-- [$year] // two-digit year ID (05 stands for 2005)
| |
| |-- [$month] //two-digit month ID (01 stands for January)
| |
| |-- entryYYMMDD-HHMMSS.txt
| |-- [entryYYMMDD-HHMMSS]
| |
| |-- rating.txt
| |-- view_counter.txt
| |-- [comments]
| |
| |-- commentYYMMDD-HHMMSS.txt
|
|-- [static]
|
|-- $filename.txt
Due to its nature of name of a file, entryYYMMDD-HHMMSS.txt must be
univocal, and therefore it can be considered as the ID field of a DB
table.
Comment DBs are associated to the entries using the file name (ID) of
the entry, deprived of its extension (.txt) as the name of the directory
which will contain them.

1
fp-content/delete.me Normal file
View File

@ -0,0 +1 @@
dummy

32
fp-defaults/plugins.conf.php Executable file
View File

@ -0,0 +1,32 @@
<?php
$fp_plugins = array(
// to disable put // or # before the plugin name
// remove it to enable :)
'jsutils', //needed by ligthbox (quite heavy in size)
'lightbox', //fancy usable img overlay effect, needs jsutils
'thumb', //creates thumbnails adding scale=NN% to [img] tags :)
'bbcode', // bbcode-style formatting; if you disable this
// you'll loose some features, but you will be able to use xhtml
// as a default
//'syntaxhighlighter',//fancy js to color code
'accessibleantispam',
'qspam', // quick spam filter
// 'akismet', // powerful antispam; requires you to have a wordpress api key
// open the plugin file to set your key
'adminarea',
'archives',
//'calendar', //time consuming, not really recommended :p
'lastentries',
//'lastcomments', // cache-based last-comments block
//'prettyurls', //rename htaccess.txt in BLOG_ROOT to enable EXPERIMENTAL
'categories',
'searchbox',
'blockparser',
'readmore',
);
?>

View File

@ -0,0 +1,31 @@
<?php
$fp_config = array (
'general' =>
array (
'www' => 'http://localhost',
'title' => 'FlatPress',
'subtitle' => 'My FlatPress blog',
'footer' => '',
'author' => 'admin',
'email' => 'webmaster@localhost.com',
'startpage' => 'about',
'maxentries' => '5',
'notify' => true,
'theme' => 'leggero',
'style' => 'leggero',
'blogid' => 'fpdefid',
'lang' => 'en-us',
'charset' => 'utf-8',
),
'locale' =>
array (
'timeoffset' => '2',
'timeformat' => '%H:%M:%S',
'dateformat' => '%A, %B %e, %Y',
'charset' => 'utf-8',
'lang' => 'en-us',
)
);
?>

45
fp-defaults/widgets.conf.php Executable file
View File

@ -0,0 +1,45 @@
<?php
$fp_widgets = array (
// to disable put // or # before the plugin name
// remove it to enable :)
'top' =>
array (
// (no widgets)
),
// Left side widgets. Put here blocks which will appear
// on the left side
// (Theme dependant)
'left' =>
array (
// (no widgets)
),
// Right side widgets
'right' =>
array (
'adminarea',
'blockparser:menu',
'categories',
'archives',
//'calendar', // quite time consuming, not really recommended
'lastentries',
// 'lastcomments',
'searchbox',
),
'bottom' =>
array (
// (no widgets)
),
);
?>

View File

@ -0,0 +1,64 @@
<?php
function admin_getpanellink($page, $action, $command='') {
$link = BLOG_BASEURL . 'admin.php?p=' . $page . '&action=' .$action;
if ($command)
$link .= '&' . $command;
return wp_specialchars(
apply_filter('admin_panel_link',
$link,
$page,
$action,
$command)
);
}
function admin_addpanel($page) {
global $fpadminpanels;
$fpadminpanels[] = $page;
}
function admin_getpanels() {
global $fpadminpanels;
return $fpadminpanels;
}
function admin_addpanelaction($panel, $action, $showpanel = true) {
global $fpadminpanelactions;
if (admin_panelexists($panel)) {
$fpadminpanelactions[$panel][$action] = $showpanel;
}
}
function admin_getpanelactions($panel) {
global $fpadminpanelactions;
if (isset($fpadminpanelactions[$panel])) {
return $fpadminpanelactions[$panel];
} else {
return array();
}
}
function admin_panelexists($panel) {
global $fpadminpanels;
return in_array($panel, $fpadminpanels);
}
function admin_getpaneldir($id) {
global $fpadminpanels;
if (array_intersect( $fpadminpanels, array( array($id, true) ) ) ) // is plugin
return ABS_PATH . plugin_getdir($id);
else return ABS_PATH . ADMIN_DIR . $id;
}
?>

144
fp-includes/core/core.blogdb.php Executable file
View File

@ -0,0 +1,144 @@
<?php
/**
* Blogdb lib
* provides access to the blog.
*
* @author NoWhereMan <nowhereman@phreaker.net>
*/
/**
* entry id prefix and identifier
*/
define('BDB_ENTRY', 'entry');
/**
* comment id prefix and identifier
*/
define('BDB_COMMENT', 'comment');
/**
* default file extension
*/
define('EXT', '.txt');
/**
* function bdb_idtofile
*
* <p>Takes the id $id and returns a filepath</p>
*
* @param string $id string formatted like "prefixYYMMDD-HHMMSS.EXT"
* @return string
*/
function bdb_idtofile($id,$type=null) {
$fname = $id.EXT;
$date = date_from_id($id);
if (!$date)
return false;
$path = CONTENT_DIR . $date['y'] . '/' . $date['m'] . '/';
if ($type == null || $type == BDB_ENTRY) {
$path .= $fname;
} elseif ($type == BDB_COMMENT) {
$path .= $id . '/comments/';
}
return $path;
}
/**
* function bdb_idfromtime
*
* <p>Returns a well formatted id for entry type specified in $type
* and date eventually specified in $date; </p>
*
* @param string $type one of the BDB_ constants
* @param int $timestamp UNIX timestamp
* @return string
*/
function bdb_idfromtime($type, $timestamp=null) {
if (!$timestamp)
$timestamp=time();
/*if (!ctype_digit($timestamp)) {
trigger_error("bdb_idfromtime():
$timestamp Not a valid timestamp", E_USER_WARNING);
}*/
return $type . date('ymd-His', $timestamp);
}
/**
* function bdb_filetoid
*
* <p>Cosmetic wrapper to basename($file, EXT)</p>
*
* @param string $file filepath of the blogdb entry
* @return string
*
* @todo validate returned id
*/
function bdb_filetoid($file) {
return basename($file, EXT);
}
/**
* function bdb_parse_entry
*
* <p>Parses the entry file passed as parameter; returns an associative array
* of the file content</p>
* Tipically, entry arrays are usually made of these keys
* - VERSION : SimplePHPBlog or compatible blogs' version identifier string
* - SUBJECT : Subject of the entry
* - CONTENT : Content of the entry
* - DATE : UNIX filestamp to format by {@link date_format()}.
*
* comments usually provide also
* - NAME : author name
* - EMAIL : author email (if any)
* - URL : author website url (if any)
*
* A common usage of the function could be
* <code>
* <?php
* $entry = bdb_parse_entry(bdb_filetoid($myid));
* ?>
* </code>
*
* @param string $file filepath of the blogdb entry
* @return string
*
* @todo validate returned id
*/
function bdb_parse_entry($id, $type=null) {
if (file_exists($id))
$file = $id;
else
$file = bdb_idtofile($id, $type);
if (file_exists($file)) {
$contents = io_load_file($file);
// TODO: here we must add compatibility to encoding conversion!
// if "dumb" (legacy :D) mode is enabled (set to true in default.php, then we set parsing
// to ignore array key case (defaults to true i.e. check them to be uppercase or failing otherwise
$entry = utils_kexplode($contents, '|', !DUMB_MODE_ENABLED);
return $entry;
} else return false;
}
?>

94
fp-includes/core/core.cache.php Executable file
View File

@ -0,0 +1,94 @@
<?php
define('FP_SORTING', SORT_DESC);
class cache_filelister extends fs_filelister {
var $_cachefile = null;
// sub-classes will fill the above variables on constructing
function cache_filelister() {
if (!$this->_cachefile)
trigger_error('CACHE: no cache file specified');
$varname = $this->_varname;
if (file_exists($this->_cachefile)) {
//include($this->_cachefile);
$var = io_load_file($this->_cachefile);
$this->_list = unserialize($var);
} else {
parent::fs_filelister();
$this->save();
}
return $this->_list;
}
function checksorting() {
list($k1) = each($this->_list);
list($k2) = each($this->_list);
// decreasing order
if ((FP_SORTING==SORT_DESC) & (strcmp($k1, $k2) < 0)) {
$this->save;
}
}
function save() {
// TODO: re-think this :)
// reverse sorting on save is an acceptable overhead,
// still this is quite an hack
krsort($this->_list);
$succ = io_write_file($this->_cachefile, serialize($this->_list));
if (!$succ){
trigger_error("Error while saving data in {$this->_cachefile}",
E_USER_WARNING);
return false;
} else return $this->_list;
}
function getList() {
return $this->_list;
}
function get($id) {
return isset($this->_list[$id])? $this->_list[$id] : false;
}
function add($id, $val) {
$this->_list[$id]=$val;
return $this->save();
}
function delete($entryid) {
$cache =& $this->_list;
unset($cache[$entryid]); // if id found, it is deleted
return $this->save();
}
function purge() {
return fs_delete($this->_cachefile);
}
}
?>

154
fp-includes/core/core.comment.php Executable file
View File

@ -0,0 +1,154 @@
<?php
class comment_indexer extends fs_filelister {
function comment_indexer($id) {
$f = bdb_idtofile($id,BDB_COMMENT); //todo change
$this->_directory = $f;
parent::fs_filelister();
//substr(bdb_idtofile($id), -strlen(EXT));
}
function _checkFile($directory, $file) {
$f = "$directory/$file";
if (fnmatch('comment*'.EXT, $file)) {
array_push($this->_list, basename($file,EXT));
return 0;
}
}
// overrides parent method to return sorted results
function getList() {
sort($this->_list);
return parent::getList();
}
}
/**
* function bdb_get_comments
*
* <p>On success returns an array containing the comment <b>IDs</b>, associated to
* the entry ID in $id</p>
* <p>On failure returns false</p>
*
* @param string $id string formatted like "prefixYYMMDD-HHMMSS.EXT"
* @return mixed
*
* @see bdb_idtofile()
*/
function comment_getlist($id) {
$obj =& new comment_indexer($id); //todo change syntax
return $obj->getList();
}
function comment_parse($entryid, $id) {
$f = comment_exists($entryid, $id);
if (!$f) return false;
$fc = io_load_file($f);
$arr = utils_kexplode($fc);
//$arr['EMAIL'] = apply_filters('comment_email', $arr['EMAIL']);
// hackish: dash to underscore for ip-address :( todo: clean this up here or somewhere else
//$arr['ip_address'] = $arr['ip-address'];
return array_change_key_case($arr, CASE_LOWER);
}
function comment_exists($entryid, $id) {
if (!preg_match('|^comment[0-9]{6}-[0-9]{6}$|', $id))
return false;
$f = entry_exists($entryid);
if (!$f) return false;
$f2 = substr($f, 0, -strlen(EXT)) . '/comments/' . $id.EXT;
if (!file_exists($f2)) return false;
return $f2;
}
function comment_clean(&$arr) {
$arr['name'] = apply_filters('pre_comment_author_name', stripslashes($arr['name']));
if (isset($arr['email']))
$arr['email'] = apply_filters('pre_comment_author_email', $arr['email']);
if (isset($arr['url']))
$arr['url'] = apply_filters('pre_comment_author_url', $arr['url']);
$arr['content'] = apply_filters('pre_comment_content', stripslashes($arr['content']));
return $arr;
}
/**
* function bdb_save_comment
*
* <p>Saves the content of the $comment array, associating it to the entry-ID $id.</p>
* <p>$comment must be formatted as the one returned by {@link bdb_parse_entry()}.</p>
* <p>Returns true on success, or false on failure</p>
*
* @param string $id string formatted like "prefixYYMMDD-HHMMSS"
* @param array $comment array formatted as the one returned by {@link bdb_parse_entry()}
* @return bool
*
* @see bdb_parse_entry()
*/
function comment_save($id, $comment) {
comment_clean($comment);
$comment = array_change_key_case($comment, CASE_UPPER);
$comment_dir = bdb_idtofile($id,BDB_COMMENT);
$comment['DATE'] = date_time();
$id = bdb_idfromtime(BDB_COMMENT, $comment['DATE']);
$f = $comment_dir . $id . EXT;
$str = utils_kimplode($comment);
if (io_write_file($f, $str))
return $id;
return false;
}
/**
* function comment_delete
*
* <p>Deletes the $id comment</p>
* <p>Returns true on success, or false on failure</p>
*
* @param string $id string formatted like "entryYYMMDD-HHMMSS"
* @param string $comment_id string representig comment id as in "commentYYMMDD-HHMMSS"
* @return bool
*
* @see entry_delete()
*/
function comment_delete($id, $comment_id) {
$comment_dir = bdb_idtofile($id,BDB_COMMENT);
$f = $comment_dir . $comment_id .EXT;
return fs_delete($f);
}
function dummy_comment($val) {
return $val;
}
add_filter('comment_validate', 'dummy_comment');
?>

View File

@ -0,0 +1,53 @@
<?php
function config_read($fullpath) {
if ($fullpath{0}!='/')
trigger_error('config_read: syntax error. Path must begin with a /');
$last_slash = strrpos($fullpath, '/');
$option = substr($fullpath, $last_slash + 1);
$path = substr($fullpath, 1, $last_slash);
$file = str_replace('/', '.', $path) . 'conf.php';
$f = CONFIG_DIR . $file;
if (file_exists($f)) {
include($f);
}
$arr = explode('/', $fullpath);
/* todo finire */
}
// a cosmetic wrapper around an include :D
// plus, loads the defaults if CONFIG_FILE is not found
function config_load($conffile=CONFIG_FILE) {
if ( !file_exists($conffile) && ($conffile==CONFIG_FILE) )
$conffile = CONFIG_DEFAULT;
include $conffile;
// todo CHANGE
//$fp_config['general'] = array_change_key_case($blog_confi);
return $fp_config;
}
// $conf_arr can have a variable number of args
// they are the same of system_save(), as this is in fact
// a wrapper to that ;)
// so:
// $conf_arr[ 'myvariable' ] = $myvariable;
function config_save($conf_arr=null, $conffile=CONFIG_FILE) {
if ($conf_arr==null) {
global $fp_config;
$conf_arr=$fp_config;
}
//print_r($conf_arr);
$arr = array('fp_config' => $conf_arr);
return system_save($conffile, $arr);
}
?>

View File

@ -0,0 +1,169 @@
<?php
function cookie_setup() {
global $fp_config;
// md5(BLOG_BASEURL);
if ( !defined('COOKIEHASH') )
define('COOKIEHASH', $fp_config['general']['blogid']);
if ( !defined('USER_COOKIE') )
define('USER_COOKIE', 'fpuser_'. COOKIEHASH);
if ( !defined('PASS_COOKIE') )
define('PASS_COOKIE', 'fppass_'. COOKIEHASH);
if ( !defined('SESS_COOKIE') )
define('SESS_COOKIE', 'fpsess_'. COOKIEHASH);
if ( !defined('COOKIEPATH') )
define('COOKIEPATH', preg_replace('|https?://[^/]+|i', '', BLOG_BASEURL ) );
if ( !defined('SITECOOKIEPATH') )
define('SITECOOKIEPATH', preg_replace('|https?://[^/]+|i', '', BLOG_BASEURL ) );
if ( !defined('COOKIE_DOMAIN') )
define('COOKIE_DOMAIN', false);
}
// Cookie safe redirect. Works around IIS Set-Cookie bug.
// http://support.microsoft.com/kb/q176113/
if ( !function_exists('wp_redirect') ) :
function wp_redirect($location, $status = 302) {
global $is_IIS;
$location = apply_filters('wp_redirect', $location, $status);
if ( !$location ) // allows the wp_redirect filter to cancel a redirect
return false;
$location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%]|i', '', $location);
# $location = wp_kses_no_null($location);
$location = preg_replace('/\0+/', '', $location);
$location = preg_replace('/(\\\\0)+/', '', $location);
$strip = array('%0d', '%0a');
$location = str_replace($strip, '', $location);
if ( $is_IIS ) {
header("Refresh: 0;url=$location");
} else {
if ( php_sapi_name() != 'cgi-fcgi' )
status_header($status); // This causes problems on IIS and some FastCGI setups
header("Location: $location");
}
}
endif;
if ( !function_exists('wp_get_cookie_login') ):
function wp_get_cookie_login() {
if ( empty($_COOKIE[USER_COOKIE]) || empty($_COOKIE[PASS_COOKIE]) )
return false;
return array('login' => $_COOKIE[USER_COOKIE], 'password' => $_COOKIE[PASS_COOKIE]);
}
endif;
function cookie_set($username, $password, $already_md5 = false, $home = '', $siteurl = '', $remember = false) {
if ( !$already_md5 )
$password = md5( md5($password) ); // Double hash the password in the cookie.
if ( empty($home) )
$cookiepath = COOKIEPATH;
else
$cookiepath = preg_replace('|https?://[^/]+|i', '', $home . '/' );
if ( empty($siteurl) ) {
$sitecookiepath = SITECOOKIEPATH;
$cookiehash = COOKIEHASH;
} else {
$sitecookiepath = preg_replace('|https?://[^/]+|i', '', $siteurl . '/' );
$cookiehash = md5($siteurl);
}
if ( $remember )
$expire = time() + 31536000;
else
$expire = 0;
setcookie(USER_COOKIE, $username, $expire, $cookiepath, COOKIE_DOMAIN);
setcookie(PASS_COOKIE, $password, $expire, $cookiepath, COOKIE_DOMAIN);
if ( $cookiepath != $sitecookiepath ) {
setcookie(USER_COOKIE, $username, $expire, $sitecookiepath, COOKIE_DOMAIN);
setcookie(PASS_COOKIE, $password, $expire, $sitecookiepath, COOKIE_DOMAIN);
}
}
function cookie_clear() {
setcookie(USER_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
setcookie(PASS_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
setcookie(USER_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
setcookie(PASS_COOKIE, ' ', time() - 31536000, SITECOOKIEPATH, COOKIE_DOMAIN);
}
if ( !function_exists('wp_login') ) :
function wp_login($username, $password, $already_md5 = false) {
global $wpdb, $error;
$username = sanitize_user($username);
if ( '' == $username )
return false;
if ( '' == $password ) {
$error = __('<strong>ERROR</strong>: The password field is empty.');
return false;
}
$login = get_userdatabylogin($username);
//$login = $wpdb->get_row("SELECT ID, user_login, user_pass FROM $wpdb->users WHERE user_login = '$username'");
if (!$login) {
$error = __('<strong>ERROR</strong>: Invalid username.');
return false;
} else {
// If the password is already_md5, it has been double hashed.
// Otherwise, it is plain text.
if ( ($already_md5 && md5($login->user_pass) == $password) || ($login->user_login == $username && $login->user_pass == md5($password)) ) {
return true;
} else {
$error = __('<strong>ERROR</strong>: Incorrect password.');
$pwd = '';
return false;
}
}
}
endif;
if ( !function_exists('is_user_logged_in') ) :
function is_user_logged_in() {
$user = wp_get_current_user();
if ( $user->id == 0 )
return false;
return true;
}
endif;
if ( !function_exists('auth_redirect') ) :
function auth_redirect() {
// Checks if a user is logged in, if not redirects them to the login page
if ( (!empty($_COOKIE[USER_COOKIE]) &&
!wp_login($_COOKIE[USER_COOKIE], $_COOKIE[PASS_COOKIE], true)) ||
(empty($_COOKIE[USER_COOKIE])) ) {
nocache_headers();
wp_redirect(get_option('siteurl') . '/wp-login.php?redirect_to=' . urlencode($_SERVER['REQUEST_URI']));
exit();
}
}
endif;
?>

73
fp-includes/core/core.date.php Executable file
View File

@ -0,0 +1,73 @@
<?php
function date_strformat($timestamp=null, $offset=0, $format='l dS F Y h:i:s A') {
if ( strpos( $timestamp, ',' ) !== false ) {
// This is an hack for compatibility with the time
// format from versions < 0.3.3. In 0.3.3 spb switched
// to the unix timestamp for storing times.
//
// Before that it was in this format:
// date( 'F j, Y, g:i a', $time_stamp );
// 'May 10, 2004, 3:57 pm'
$time_stamp = str_replace( ',', '', $time_stamp );
$time_stamp = strtotime( $time_stamp );
}
$timestamp = ($timestamp != null) ? $timestamp : time();
$time_stamp = intval($timestamp) + intval($offset) * 60 * 60;
return date($format, $time_stamp);
}
function date_time($offset=null) {
global $fp_config;
if (is_null($offset)) {
$offset = $fp_config['locale']['timeoffset'];
}
$timestamp = time();
return $timestamp + $offset * 3600;
}
/*
function date_now($offset=0) {
$timestamp = gmtime();
$time_stamp = intval($timestamp) + intval($offset) * 60 * 60;
return date($format, $time_stamp);
}
*/
// I really DON'T LIKE THIS, looks like an hack, yech...
// Takes filename and extension as a parameter, strips
// alphabetic chars (ascii) from filename and "parses" the date;
// In fact it's just a substr, counting on the fact filename should be
// "prefix%y%m%d-%H%M%S.ext"
function date_from_id($id) {
$strdate = substr($id, -13);
if (!preg_match('/[0-9]{6}-[0-9]{6}/', $strdate))
return array();
$arr[ 'y' ] = substr($strdate, 0, 2);
$arr[ 'm' ] = substr($strdate, 2, 2);
$arr[ 'd' ] = substr($strdate, 4, 2);
$arr[ 'H' ] = substr($strdate, 7, 2);
$arr[ 'M' ] = substr($strdate, 9, 2);
$arr[ 'S' ] = substr($strdate, 11, 2);
$arr['ymd'] = $arr['y'] . $arr['m'] . $arr['d'];
$arr['HMS'] = $arr['H'] . $arr['M'] . $arr['S'];
$arr['time'] = mktime($arr['H'], $arr['M'], $arr['S'],
$arr['y'], $arr['m'], $arr['d']);
return $arr;
}
?>

View File

@ -0,0 +1,227 @@
<?php
define('DRAFT_DIR', CONTENT_DIR . 'drafts/');
class draft_indexer extends fs_filelister {
var $_varname = 'cache';
var $_cachefile = null;
var $_directory = DRAFT_DIR;
function draft_indexer() {
$this->_cachefile = CACHE_DIR . 'draft_index.php';
return parent::fs_filelister();
}
function _checkFile($directory, $file) {
$f = "$directory/$file";
if ( is_dir($f) && ctype_digit($file)) {
return 1;
}
if (fnmatch('entry*'.EXT, $file)) {
$id=basename($file,EXT);
$arr=draft_parse($id);
//$this->add($id, $arr['subject']);
$this->_list[$id] = $arr['subject'];
return 0;
}
}
}
function &draft_init() {
global $draftdb;
if (!isset($draftdb))
$draftdb =& new draft_indexer;
return $draftdb;
}
function draft_getlist() {
static $list = array();
if (!$list) {
$obj =& draft_init();
$list = $obj->getList();
krsort($list);
}
return $list;
}
function draft_parse($id) {
if ($fname=draft_exists($id)) {
$entry = io_load_file($fname);
$entry = array_change_key_case(utils_kexplode($entry));
if (!isset($entry['categories']))
$entry['categories'] = array();
else
$entry['categories'] = explode(',', $entry['categories']);
return $entry;
}
return array();
}
function draft_save($entry, $id=null, $update_date=false) {
if (!$id) {
$id = bdb_idfromtime('entry', $entry['date']);
}
$ed = entry_dir($id);
$dd = draft_dir($id);
if (file_exists($ed.EXT)) {
// move collateral files
@rename($ed, $dd);
// delete normal entry
fs_delete($ed.EXT);
// remove from normal flow
$o =& entry_init();
$o->delete($id);
}
$entry = array_change_key_case($entry, CASE_UPPER);
if (isset($entry['CATEGORIES'])) {
if (is_array($entry['CATEGORIES']))
$entry['CATEGORIES'] = implode(',',$entry['CATEGORIES']);
else
trigger_error("Failed saving draft. Expected 'categories' to be
an array, found " . gettype($entry['CATEGORIES']), E_USER_ERROR);
}
$string = utils_kimplode($entry);
if (!io_write_file($dd.EXT, $string)) {
return false;
} else return $id;
return false;
}
function draft_dir($id) {
if (!preg_match('|^entry[0-9]{6}-[0-9]{6}$|', $id))
return false;
//$date = date_from_id($id);
//$f = CONTENT_DIR . "{$date['y']}/{$date['m']}/$id";
return DRAFT_DIR . $id;
//return $f;
}
function draft_exists($id) {
if (!user_loggedin())
return false;
$dir = draft_dir($id);
if (!$dir)
return false;
$f = $dir .EXT;
if (file_exists($f))
return $f;
return false;
}
function draft_delete($id) {
$dir = draft_dir($id);
$f=$dir.EXT;
if (!file_exists($f))
return false;
//$draftdb =& draft_init();
//$draftdb->delete($id);
fs_delete_recursive($dir);
return fs_delete($f);
}
/*
function draft_from_entry($entryid) {
$dir = entry_dir($entryid);
//$dir2 = str_replace('entry', 'draft', $dir);
$dir2 = draft_dir($entryid);
@rename($dir, $dir2);
@rename($dir.EXT, $dir2.EXT);
}
*/
function draft_to_entry($draftid) {
$dir = draft_dir($draftid);
$dir2 = entry_dir($draftid);
@rename($dir, $dir2);
draft_delete($draftid);
}
function smarty_block_draftlist($params, $content, &$smarty, &$repeat) {
global $fpdb;
if ($list = draft_getlist()) {
$smarty->assign('draft_list', $list);
return $content;
}
}
function smarty_block_draft($params, $content, &$smarty, &$repeat) {
static $list = array();
$smarty->assign(array( 'subject'=>'',
'content'=>'',
'date'=>'',
'author'=>'',
'version'=>'',
'id'=>''
)
);
$arr =& $smarty->get_template_vars('draft_list');
list($id, $subject)=each($arr);
if ($id){
$smarty->assign('subject', $subject);
$smarty->assign('id', $id);
}
$repeat = (bool) $id;
return $content;
}
$smarty->register_block('draft_block', 'smarty_block_draftlist');
$smarty->register_block('draft', 'smarty_block_draft');
?>

508
fp-includes/core/core.entry.php Executable file
View File

@ -0,0 +1,508 @@
<?php
class entry_indexer extends cache_filelister {
var $_varname = 'cache';
var $_cachefile = null;
var $_directory = CONTENT_DIR;
function entry_indexer() {
$this->_cachefile = CACHE_DIR . CACHE_FILE;
return parent::cache_filelister();
}
function _checkFile($directory, $file) {
$f = "$directory/$file";
if ( is_dir($f) && ctype_digit($file)) {
return 1;
}
if (fnmatch('entry*'.EXT, $file)) {
$id=basename($file,EXT);
$arr=entry_parse($id);
$this->addEntry($id, $arr);
return 0;
}
}
function addEntry($id, $arr) {
if ($arr) {
// do_action('publish_post', $id, $arr);
$this->_list[$id]=array(
'subject' => $arr['subject'],
'categories' =>
(
isset($arr['categories'])?
$arr['categories']
:
array()
)
);
}
}
function save() {
do_action('cache_save');
return parent::save();
}
function add($id, $val) {
$this->_list[$id]=array('subject' => $val['SUBJECT'],
'categories' =>
(isset($val['CATEGORIES'])?
$val['CATEGORIES'] : array()));
return $this->save();
}
function get($id) {
if (isset($this->_list[$id]))
return $this->_list[$id];
else {
//trigger_error("entry_lister: No such element \"$id\" in
//list", E_USER_WARNING);
return false;
}
}
}
class entry_archives extends fs_filelister {
var $_directory = CONTENT_DIR;
var $_y = null;
var $_m = null;
var $_d = null;
var $_count = 0;
var $_filter = 'entry*';
function entry_archives($y, $m = null, $d = null) {
$this->_y = $y;
$this->_m = $m;
$this->_d = $d;
$this->_directory .= "$y/";
if ($m){
$this->_directory .= "$m/";
if ($d) {
$this->_filter = "entry$y$m$d*";
}
}
return parent::fs_filelister();
}
function _checkFile($directory, $file) {
$f = "$directory/$file";
if ( is_dir($f) && ctype_digit($file)) {
return 1;
}
if (fnmatch($this->_filter.EXT, $file)) {
$id=basename($file,EXT);
$this->_count++;
array_push($this->_list, $id);
return 0;
}
}
function getList() {
rsort($this->_list);
return parent::getList();
}
function getCount() {
return $this->_count;
}
}
/* //work in progress
class entry {
var $_indexer;
var $id;
function entry($id, $content) {
//$this->_indexer =& $indexer;
}
function get($field) {
$field = strtolower($field);
if (!isset($this->$field)) {
// if it is not set
// tries to fetch from the database
$arr = entry_parse($id);
while(list($field, $val) = each($arr))
$this->$field = $val;
// if still is not set raises an error
if (!isset($this->$field))
trigger_error("$field is not set", E_USER_NOTICE);
return;
}
return $this->$field;
}
function set($field, $val) {
$field = strtolower($field);
$this->$field = $val;
}
}
*/
/**
* function entry_init
* fills the global array containing the entry object
*/
function &entry_init() {
global $fpdb;
$fpdb->init();
return $fpdb->_indexer;
}
/*
function entry_query($params=array()){
global $fpdb;
$queryid = $fpdb->query($params);
$fpdb->doquery($queryid);
}
function entry_hasmore() {
global $fpdb;
return $fpdb->hasmore();
}
function entry_get() {
$fpdb->get();
}
*/
function entry_list() {
$obj =& entry_init();
$entry_arr = $obj->getList();
if ($entry_arr) {
krsort($entry_arr);
return $entry_arr;
}
}
function entry_exists($id) {
$f = entry_dir($id).EXT;
return $f;file_exists($f)? $f : false;
}
function entry_dir($id) {
if (!preg_match('|^entry[0-9]{6}-[0-9]{6}$|', $id))
return false;
$date = date_from_id($id);
$f = CONTENT_DIR . "{$date['y']}/{$date['m']}/$id";
return $f;
}
function entry_parse($id, $incrViews=false) {
$f = entry_exists($id);
if (!$f)
return array();
$fc = io_load_file($f);
if (!$fc)
return array();
$arr = utils_kexplode($fc);
// propagates the error if entry does not exist
if (isset($arr['CATEGORIES']) && // fix to bad old behaviour:
(trim($arr['CATEGORIES']) != '')) {
$cats = (array)explode(',',$arr['CATEGORIES']);
$arr['CATEGORIES'] = (array) $cats;
} else $arr['CATEGORIES'] = array();
// if (!is_array($arr['CATEGORIES'])) die();
if (!isset($arr['AUTHOR'])) {
global $fp_config;
$arr['AUTHOR'] = $fp_config['general']['author'];
}
return array_change_key_case($arr, CASE_LOWER);
}
/**
* function entry_get_comments
*
* @param string id entry id
* @param array entry entry content array by ref; 'commentcount' field is added to the array
*
* @return object comment_indexer as reference
*
*/
function &entry_get_comments($id, &$count) {
$obj =& new comment_indexer($id);
$count = count($obj->getList());
return $obj;
}
function entry_categories_encode() {
if ($string = io_load_file(CONTENT_DIR . 'categories.txt')) {
$lines = explode("\n", trim($string));
$idstack = $result = $indentstack=array();
while (!empty($lines)) {
$v = array_pop($lines);
$vt = trim($v);
if ($vt) {
$text='';
$indent = utils_countdashes($vt, $text);
$val = explode(':', $text);
$id = trim($val[1]);
$label = trim($val[0]);
if (empty($indentstack)) {
array_push($indentstack,$indent);
array_push($idstack, $id);
$indent_old = $indent;
} else {
$indent_old = end($indentstack);
}
if ($indent < $indent_old) {
array_push($indentstack, $indent);
array_push($idstack, $id);
} elseif ($indent > $indent_old) {
$idstack = array($id);
$indentstack = array($indent);
} else {
array_pop($idstack);
$idstack = array($id);
}
$result['rels'][$id] = $idstack;
$result['defs'][$id] = $label;
}
}
ksort($result['rels']);
ksort($result['defs']);
//print_r($result);
return io_write_file(CONTENT_DIR . 'categories_encoded.dat', serialize($result));
}
return false;
}
/*
function entry_categories_print(&$lines, &$indentstack, &$result, $params) {
}
*/
function entry_categories_get($what=null) {
global $fpdb;
$categories = array();
if (isset($fpdb->_categories)) {
$categories = $fpdb->_categories;
} else {
$f = CONTENT_DIR . 'categories_encoded.dat';
if (file_exists($f)) {
if ($c = io_load_file($f))
$categories = unserialize($c);
}
}
if ($categories) {
if ($what=='defs' || $what=='rels')
return $categories[$what];
else
return $categories;
}
return array();
}
/**
flags are actually special categories
which are usually hidden.
they can be set when editing your entries
to let flatpress perform special actions
draft: Draft entry (hidden, awaiting publication)
static: Static entry (allows saving an alias, so you can reach it with
?page=myentry)
commslock: Comments locked (comments disallowed for this entry)
*/
function entry_flags_get() {
return array(
'draft',
//'static',
'commslock'
);
}
function entry_save($entry_cont, $id=null, $update_index = true) {
$obj =& entry_init();
if (!isset($entry_cont['date'])) {
$entry_cont['date']=date_time();
}
$entry = array_change_key_case($entry_cont, CASE_UPPER);
if (!$id) {
$id = bdb_idfromtime(BDB_ENTRY, $entry['DATE']);
}
do_action('publish_post', $id, $entry_cont);
$f = bdb_idtofile($id);
$entry['CONTENT'] = apply_filters('content_save_pre', $entry['CONTENT']);
$entry['SUBJECT'] = apply_filters('title_save_pre', $entry['SUBJECT']);
$ok = ($update_index) ? $obj->add($id, $entry) : true;
if ($ok) {
if (isset($entry['CATEGORIES'])) {
if (is_array($entry['CATEGORIES']))
$entry['CATEGORIES'] = implode(',',$entry['CATEGORIES']);
else
trigger_error("Failed saving entry. Expected 'categories' to be
an array, found " . gettype($entry['CATEGORIES']), E_USER_ERROR);
}
$str = utils_kimplode($entry);
if (!io_write_file($f, $str)) {
if ($update_index)
$obj->delete($id);
return false;
} else return $id;
}
return false;
}
function entry_delete($id) {
if ( ! $f = entry_exists($id) )
return;
/*
$d = bdb_idtofile($id,BDB_COMMENT);
fs_delete_recursive("$d");
// thanks to cimangi for noticing this
$f = dirname($d) . '/view_counter' .EXT;
fs_delete($f);
$f = bdb_idtofile($id);
*/
$d = entry_dir($id);
fs_delete_recursive($d);
$obj =& entry_init();
$obj->delete($id);
do_action('delete_post', $id);
return fs_delete($f);
}
function entry_purge_cache() {
$obj =& entry_init();
$obj->purge();
}
//add_action('init',
?>

View File

@ -0,0 +1,58 @@
<?php
// fileio.php
// low-level io-handling functions
function io_write_file($filename, $data) {
@umask(0);
$dir = dirname($filename);
if (fs_mkdir($dir)) {
$f = fopen($filename, "w");
if ($f) {
if (!flock($f, LOCK_EX))
return -1;
$length = strlen($data);
$done = fwrite($f, $data);
flock($f, LOCK_UN);
fclose($f);
@chmod($filename, 0666);
//returns true on success
return($length == $done);
}
}
return false;
}
function io_load_file($filename) {
if (file_exists($filename)) {
if (function_exists('file_get_contents'))
return file_get_contents($filename);
$f = fopen($filename, "r");
if ($f) {
if (!flock($f, LOCK_SH))
return -1;
$contents = fread($f, filesize($filename));
flock($f, LOCK_UN);
fclose($f);
//returns contents as string on success
return($contents);
}
}
//trigger_error("io_load_file: $filename does not exists", E_USER_ERROR);
return false;
}
?>

View File

@ -0,0 +1,285 @@
<?php
/**
* Filesystem lib
* provides basic filesystem handling functions.
*
* @author NoWhereMan <nowhereman@phreaker.net>
*/
class fs_filelister {
var $_list = array();
var $_directory = null;
//constructor
function fs_filelister($directory = null) {
if ($directory) $this->_directory = $directory;
$this->_listFiles($this->_directory);
}
function _checkFile($directory, $file) {
if (!is_dir("$directory/$file"))
array_push($this->_list, $file);
return 0;
}
function _exitingDir($directory, $file) {
}
function _listFiles($directory) {
// Try to open the directory
if (!file_exists($directory)) return array();
if($dir = opendir($directory)) {
// Add the files
while($file = readdir($dir)) {
if ($file != '.' && $file != '..') {
$action = $this->_checkFile($directory,$file);
// $action == 0: ok, go on
// $action == 1: recurse
// $action == 2: exit function
switch ($action) {
case (1): {
$this->_listFiles("$directory/$file");
$this->_exitingDir($directory, $file);
break;
}
case (2): {
return false;
}
}
}
}
// Finish off the function
closedir($dir);
return true;
}
else return false;
}
function getList() {
//$this->_listFiles($this->_directory);
return $this->_list;
}
}
class fs_pathlister extends fs_filelister {
function _checkFile($directory, $file) {
$f = "$directory/$file";
if (!is_dir($f))
array_push($this->_list, $f);
else
return 1;
}
}
// dir list
function fs_list_dirs($dir) {
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
if ( ($filename[0] != '.') ) {
$id = lang_id($filename);
$files[] = $filename;
}
}
sort($files);
return $files;
}
/**
* function fs_mkdir
*
* <p>Function from : {@link http://www.php.net/function.mkdir.php}</p>
*
* <p>Recursively creates dirs.</p>
* <p>Returns true on success, else false</p>
*
* @param string $path Directory or directories to create
* @param int $mode octal mode value; same as UNIX chmod; defaults to 0777 (rwrwrw);
* @return bool
*
* @todo cleanup & check bool return value
*
*/
function fs_mkdir($dir, $mode=0777) {
if (is_dir($dir) || (@mkdir($dir,$mode))) {@chmod($dir, $mode); return TRUE;}
if (!fs_mkdir(dirname($dir),$mode)) return FALSE;
return (@mkdir($dir,$mode) && @chmod($dir, $mode));
}
/**
* function fs_delete
*
* Deletes a file and recursively deletes dirs, if they're empty
*
*/
function fs_delete($path) {
if (file_exists($path)) {
$fsuccess = unlink($path);
$dsuccess = true;
while ($dsuccess) {
$path = dirname($path);
$dsuccess = @rmdir($path);
}
// unlink can return both 0 and false -__-'
return ($fsuccess);
}
// in our particular implementation
// you can always delete a non existent file;
// anyway, we'll return a value != true
// so that we can anyway track it back
return 2;
}
/**
* function fs_recursive_chmod
*
* Perform a recursive reset of file permission in the given $path
* and its subdirectories to 0777
*
* @param $fpath dir path
* @return bool
*
*/
class fs_chmodder extends fs_filelister {
var $_chmod=0777;
function fs_chmodder($directory, $octal=0777) {
$this->_directory = $directory;
$this->_chmod = $octal;
parent::fs_filelister();
}
function _checkFile($directory, $file) {
$retval = 0;
$path = "$directory/$file";
if (is_dir($path))
$retval = 1;
if (!@chmod($path, $this->_chmod))
array_push($this->_list, $path);
return $retval;
}
}
function fs_chmod_recursive($fpath=FP_CONTENT) {
$obj = new fs_chmodder($fpath);
return $obj->getList();
}
/**
* recursive deletion
* deletes all files and directories recursively in the given $path
* @param $fpath dir path
* @return bool
*/
/*class fs_deleter extends fs_filelister {
function fs_deleter($directory) {
$this->_directory = $directory;
parent::fs_filelister();
}
function _checkFile($directory, $file) {
$path = "$directory/$file";
/*
* open dir handle prevents directory deletion of php5 (and probably win)
* thanks to cimangi <cimangi (at) yahoo (dot) it> for noticing and
* giving a possible solution:
*
* filenames are cached and then deleted
//
if ( is_dir($path) ) {
return 1;
} elseif ( file_exists($path) ) {
array_push($this->_list, $path);
return 0;
} else {
return 2;
}
}
}
*/
/*
* open dir handle prevents directory deletion of php5 (and probably win)
* thanks to cimangi <cimangi (at) yahoo (dot) it> for noticing and
* giving a possible solution;
*
* paths are now cached and then deleted
*/
function fs_delete_recursive($path) {
if (file_exists($path)) {
$obj =& new fs_pathlister($path);
$list = ($obj->getList());
unset($obj);
$elem = null;
while($elem = array_pop($list)) {
$elem;
fs_delete($elem);
}
}
return true;
}
function fs_copy($source, $dest) {
if ($contents = io_load_file($source)) {
return io_write_file($dest, $contents);
}
return false;
}
?>

View File

@ -0,0 +1,854 @@
<?php
class FPDB_QueryParams {
var $id = null;
var $d = null;
var $m = null;
var $y = null;
var $start = 0;
var $count = -1;
var $random = 0;
var $category = 0;
var $page = 1;
var $fullparse = false;
function FPDB_QueryParams($params) {
if (is_string($params)) {
$this->parse_string($params);
} elseif (is_array($params)) {
$this->validate_array($params);
} else {
trigger_error("FPDB_QueryParams: parameters were not in a valid form",
E_USER_ERROR);
}
}
function pad_date($date) {
if (is_numeric($date) && strlen($date)<=2){
return str_pad($date,2,'0', STR_PAD_LEFT);
}
return null;
}
function validate_array($params) {
global $fp_config;
if (isset($params['id'])) {
if (entry_exists($params['id'])) {
$this->id = $params['id'];
}
}
if (isset($params['fullparse'])) {
$this->fullparse =
is_string($params['fullparse'])?
($params['fullparse'] != 'false')
:
$params['fullparse'];
}
if (isset($params['y'])) {
$this->y = $this->pad_date($params['y']);
if ($this->y && isset($params['m'])) {
$this->m = $this->pad_date($params['m']);
if ($this->m && isset($params['d'])) {
$this->d = $this->pad_date($params['d']);
}
}
}
if (isset($params['random'])) {
$this->random = intval($params['random']);
$this->count = $this->random;
}
if (isset($params['page'])) {
$this->page = $params['page'];
} else {
$this->page = 1;
}
if ($this->page<1) {
$this->page=1;
}
if (isset($params['count'])) {
$this->count = intval($params['count']);
} else {
$this->count = intval($fp_config['general']['maxentries']);
}
$this->start = ($this->page - 1) * $this->count;
if (isset($params['start'])) {
$this->start = intval($params['start']);
}
if (isset($params['category'])) {
$this->category = intval($params['category']);
}
}
function parse_string($str) {
$params = utils_kexplode(strtolower($str), ',:', false);
$this->validate_array($params);
}
}
class FPDB_Query {
var $counter = -1;
var $params = null;
var $single = false;
var $pointer = 1; /* pointer points always to NEXT element */
var $processed = false;
var $ID = 0; /* query id */
var $lastentry = array(null, array());
var $nextid = '';
var $previd = '';
var $currentid = '';
function FPDB_Query($params, $ID) {
global $current_query;
$this->params =& new FPDB_QueryParams($params);
$this->ID = $ID;
if ($this->params->id) {
$this->single = true;
}
$GLOBALS['current_query'] =& $this;
}
function prepare() {
global $fpdb;
$fpdb->init();
$entry_index = $fpdb->entry_index;
if ($this->single) {
$this->_prepare_single($entry_index);
} else {
$this->_prepare_list($entry_index);
if ($this->params->random>0) {
$this->_randomize_list();
}
}
$this->counter++;
}
function _prepare_single(&$entry_index) {
/*
* this should never happen
*/
if (!$this->params->id)
trigger_error("FPDB: no ID found for query {$this->ID}", E_USER_ERROR);
$qp =& $this->params;
if (!isset($entry_index[$qp->id])){
trigger_error("FPDB: no entry found for {$qp->id}", E_USER_WARNING);
return;
}
if ($this->counter < 0) {
$idlist = array_keys($entry_index);
$fliplist = array_flip($idlist);
$this->local_index =& $entry_index;
$this->local_list =& $idlist;
$qp->start = $fliplist[$qp->id];
$qp->count = 1;
}
$this->pointer = $qp->start;
}
function _prepare_list(&$entry_index) {
//global $blog_config;
$qp =& $this->params;
$entry_num = 0;
if (!$qp->y){
$this->local_list = array_keys($entry_index);
$this->local_index =& $entry_index;
/* @todo MUST CACHE THIS COUNT! (MUST STRUCT CACHE)*/
$index_count = count($entry_index);
} else {
$obj =& new entry_archives($qp->y, $qp->m, $qp->d);
$filteredkeys = $obj->getList();
$index_count = $obj->getCount();
$this->local_list =& $filteredkeys;
}
if ($qp->count < 0) {
$qp->count = $index_count;
} elseif (($qp->start + $qp->count) > $index_count) {
if ($index_count > 0)
$qp->count = $index_count - $qp->start;
else
$index_count = $qp->start = $qp->count = 0;
}
$this->pointer = $qp->start;
if ($qp->category==0)
return;
/* category */
/* this just SUCKS. need a separate cache... */
$relations = entry_categories_get('rels');
if (!isset($relations[$qp->category]))
return;
$catrel = $relations[$qp->category];
/* need to search for one more to know if we need a nextpage link */
$fill = $qp->start + $qp->count + 1;
$i = 0;
$tmp = array();
while ($i <= $fill && (list($K, $V) = each($this->local_list))) {
if (array_intersect($catrel, $this->local_index[$V]['categories'])) {
// in_array($qp->category, $this->local_index[$V]['categories']))
$tmp[] =& $this->local_list[$K];
$i++;
}
}
$this->local_list =& $tmp;
if ($qp->start + $qp->count > $i) {
$qp->count = $i - $qp->start;
}
}
function _randomize_list() {
$qp =& $this->params;
$i = $qp->random - 1;
$nums = array_keys($this->local_list);
if ($qp->random == 1) {
$i = mt_rand(0, end($nums));
$this->single = true;
$qp->id = $this->local_list[ $i ];
$this->_prepare_single($this->local_index);
return;
}
shuffle($nums);
$newlocal = array();
do {
$newlocal[ $i ] = $this->local_list[ $nums[$i] ];
} while($i--);
$this->local_list = $newlocal;
if ($qp->count > $qp->random) {
$qp->count = $qp->random;
}
}
/* reading functions */
function hasMore() {
$GLOBALS['current_query'] =& $this;
if ($this->counter < 0)
$this->prepare();
return $this->pointer < $this->params->start + $this->params->count;
}
function &peekEntry() {
global $post;
$qp =& $this->params;
if ($this->counter < 0)
$this->prepare();
$this->_fillPrevId();
$this->_fillNextId();
$id = $this->_fillCurrentId();
if ($qp->fullparse && $this->counter <= 0) {
$cont = array();
$cont = entry_parse($id);
if ($cont) {
$this->comments =& new FPDB_CommentList($id, comment_getlist($id));
$cont['comments'] = $this->comments->getCount();
/* index is updated with full-parsed entry */
$this->local_index[$id] = $cont;
}
} else {
$cont = $this->local_index[$id];
}
$post = $cont;
$post['id'] = $id;
$var = array(&$id, &$cont);
return $var;
}
function &getEntry() {
if (!$this->hasMore())
return false;
$var =& $this->peekEntry();
$this->lastentry = $var;
$this->pointer++;
return $var;
}
function getLastEntry() {
return $this->lastentry;
}
function hasComments() {
return $this->comments->getCount();
}
function _getOffsetId($offset, $assume_pointer=null) {
if (is_int($assume_pointer))
$i = $assume_pointer + $offset;
else
$i = $this->pointer + $offset;
return isset($this->local_list [ $i ])? $this->local_list [ $i ] : false;
}
function _fillCurrentId() {
return $this->currentid = $this->_getOffsetId(0);
}
function _fillNextId() {
return $this->nextid = $this->_getOffsetId(1);
}
function _fillPrevId() {
return $this->previd = $this->_getOffsetId(-1);
}
function getCurrentId() {
return $this->currentid;
}
function getNextId() {
return $this->nextid;
}
function getPrevId() {
return $this->previd;
}
function getNextPage() {
if ($this->single){
$id = $this->_getOffsetId(-1, $this->params->start);
if ($id)
$label = $this->local_index[$id]['subject'];
else
return false;
return array($label, $id);
}
if ($this->params->page) {
if ($this->_getOffsetId(0, ($this->params->start + $this->params->count)))
return array($GLOBALS['lang']['main']['nextpage'], $this->params->page + 1);
}
}
function getPrevPage() {
if ($this->single) {
$id = $this->_getOffsetId(1, $this->params->start);
if ($id)
$label = $this->local_index[$id]['subject'];
else
return false;
return array($label, $id);
}
if ($this->params->page > 1) {
return array($GLOBALS['lang']['main']['prevpage'], $this->params->page - 1);
}
}
}
class FPDB_CommentList {
var $count = 0;
var $list = array();
var $current = '';
var $entryid = '';
function FPDB_CommentList($ID, $array) {
if (is_array($array)) {
$this->list = $array;
$this->count = count($array);
$this->entryid = $ID;
}
}
function getCount() {
return $this->count;
}
function hasMore() {
if ($this->count) {
return current($this->list) !== false;
}
return false;
}
function &getComment() {
if (!$this->hasMore())
return false;
list($k,$id) = each($this->list);
$comment = comment_parse($this->entryid, $id);
$couplet = array(&$id, &$comment);
return $couplet;
}
}
class FPDB {
var $_indexer = null;
var $queries = array();
function FPDB() {
// constructor
}
function init() {
if (!$this->_indexer) {
$this->_indexer =& new entry_indexer();
$this->_categories = entry_categories_get();
$obj =& $this->_indexer;
$this->entry_index =& $obj->getList();
}
}
function reset($queryId=null) {
switch ($queryId) {
case null: $this->_query = array(); break;
default: unset($this->_query[$queryId]);
}
}
/**
* function query
* @param mixed params
* $params may be an associative array or a query string with the following syntax:
* 'key:val,key:val,key:val';
* example: <code>$params = 'start:0,count:5';<br />
* is a convenient way to express
* $params = array('start'=>0,'count'=>5);</code>
*
* Valid parameters:
*
* start (int) first entry to show (counting from 0
* to the total number of entries).
* Defaults to 0.
*
* count (int) offset from start (e.g. for the first 5 entries,
* you'll have start=0 and count=5).
* Defaults to $blog_config['MAXENTRIES']
*
* page (int) page number (counting from 1 to
* n=ceil(num_entries/maxentries_setting))
* This is a shortcut for setting both start and count
* and overrides them, if they're set too
*
* id (string) entry or static page id
*
* get (string) 'entry' or 'static' defaults to 'entry'. <-- not anymore
*
* y (string) two digit year (06 means 2006)
* m (string) two digit month (06 means June); 'y' must be set
* d (string) two digit for day; 'y' and 'm' must be set
*
*
* fullparse (bool) non-full-parsed entries get their values
* right from the indexed list (or <em>cache</em>).
* These values are 'subject', 'content' and 'categories'.
* If you need any of the other values, you'll need to
* set fullparse=true; defaults to false.
*
*/
function query($params=array()) {
static $queryId=-1;
$queryId++;
$this->queries[$queryId] =& new FPDB_Query($params, $queryId);
$this->init();
return $queryId;
}
function doquery($queryId=0) {
if (isset($this->queries[$queryId])) {
$q =& $this->queries[$queryId];
} else {
return false;
trigger_error("FPDB: no such query ID ($queryId)", E_USER_WARNING);
}
if (!$q)
return false;
//$this->init();
/**
@todo return true/false
*/
return $q->prepare($this->entry_index);
}
// "get" functions. todo: move out?
function &getQuery($queryId=0) {
$o = null;
if (isset($this->queries[$queryId]))
$o =& $this->queries[$queryId];
return $o;
}
}
// SMARTY FUNCTIONS ----------------------------------------------------
function smarty_block_entries($params, $content, &$smarty, &$repeat) {
global $fpdb;
return $content;
$show = false;
$smarty->assign('prev_entry_day', '');
if ($repeat) {
if (isset($params['alwaysshow']) && $params['alwaysshow']) {
//$fpdb->doquery();
$repeat = false;
return $content;
}
//$show = @$fpdb->doquery();
} else {
if (!isset($fpdb->queries[0]->comments) || !$fpdb->queries[0]->comments)
$fpdb->reset(0);
$show = true;
}
$show = true;
if ($show)
return $content;
}
function smarty_block_entry($params, $content, &$smarty, &$repeat) {
global $fpdb;
// clean old variables
$smarty->assign(array( 'subject'=>'',
'content'=>'',
'categories' =>array(),
'filed_under'=>'',
'date'=>'',
'author'=>'',
'version'=>'',
'ip-address'=>''
)
);
if (isset($params['content']) && is_array($params['content']) && $params['content']) {
//foreach ($params['entry'] as $k => $val)
$smarty->assign(array_change_key_case($params['content'], CASE_LOWER));
return $content;
}
if (isset($params['alwaysshow']) && $params['alwaysshow']) {
return $content;
}
$q =& $fpdb->getQuery();
if($repeat=$q->hasMore()) {
$couplet =& $q->getEntry() ;
$id =& $couplet[0];
$entry =& $couplet[1];
if (THEME_LEGACY_MODE) {
$entry = theme_entry_filters($entry, $id);
}
foreach($entry as $k=>$v)
$smarty->assign_by_ref($k, $entry[$k]);
$smarty->assign_by_ref('id', $id);
do_action('entry_block');
}
return $content;
}
function smarty_block_comment($params, $content, &$smarty, &$repeat) {
global $fpdb;
// clean old variables
$smarty->assign(array(
'subject'=>'',
'content'=>'',
'date'=>'',
'name'=>'',
'url'=>'',
'email'=>'',
'version'=>'',
'ip-address'=>'',
'loggedin'=>'',
)
);
$q =& $fpdb->getQuery();
if($repeat=$q->comments->hasMore()) {
$couplet =& $q->comments->getComment();
$id =& $couplet[0];
$comment =& $couplet[1];
foreach($comment as $k=>$v) {
$kk = str_replace('-', '_', $k);
$smarty->assign_by_ref($kk, $comment[$k]);
}
if (THEME_LEGACY_MODE) {
$comment = theme_comments_filters($comment, $id);
}
$smarty->assign('id', $id);
}
return $content;
}
function smarty_block_comments($params, $content, &$smarty, &$repeat) {
global $fpdb;
$q =& $fpdb->getQuery();
$show = $q->comments->getCount();
$smarty->assign('entryid', $q->comments->entryid);
if ($show) {
return $content;
} else {
$repeat = false;
}
}
function smarty_function_nextpage($params) {
list ($caption, $link) = get_nextpage_link();
if (!$link)
return;
if (isset($params['admin'])) {
$qstr=strstr($link, '?');
$link = BLOG_BASEURL . 'admin.php' . $qstr;
}
return "<div class=\"alignright\"><a href=\"$link\">$caption</a></div>";
}
function smarty_function_prevpage($params) {
list($caption, $link) = get_prevpage_link();
if (!$link)
return;
if (isset($params['admin'])) {
$qstr=strstr($link, '?');
$link = BLOG_BASEURL .'admin.php' . $qstr;
}
return "<div class=\"alignleft\"><a href=\"$link\">$caption</a></div>";
}
$_FP_SMARTY->register_block('comment','smarty_block_comment');
$_FP_SMARTY->register_block('comments','smarty_block_comments');
$_FP_SMARTY->register_block('comment_block','smarty_block_comments');
$_FP_SMARTY->register_block('entries','smarty_block_entries');
$_FP_SMARTY->register_block('entry_block','smarty_block_entries');
$_FP_SMARTY->register_block('entry','smarty_block_entry');
$_FP_SMARTY->register_function('nextpage','smarty_function_nextpage');
$_FP_SMARTY->register_function('prevpage','smarty_function_prevpage');
?>

View File

@ -0,0 +1,127 @@
<?php
function lang_load($postfix=null) {
global $fp_config;
$pluginpath='';
// checks if we already loaded this lang file
$vals = explode('.', $postfix); // my.file.name ---> my, file, name
$old_lang =& $GLOBALS['lang'];
if (!$old_lang)
$old_lang = array();
if ($postfix) {
if (strpos($postfix, 'plugin:')===0) {
$pluginpath = substr($postfix, 7);
}
$file = "lang.$postfix.php";
} else {
$postfix='default';
$file = "lang.default.php";
}
$fpath=LANG_DIR."{$fp_config['general']['lang']}/$file";
$fallback=LANG_DIR.LANG_DEFAULT."/$file";
$path = '';
$plugin=$pluginpath;
if ($pluginpath) {
if (($n = strpos($pluginpath, '/'))!==false) {
$plugin = substr($plugin, 0, $n-1);
$path = substr($plugin, $n+1);
$path = str_replace('/', '.', $path);
}
$dir = plugin_getdir($plugin);
$fpath = $dir . "lang/lang.{$fp_config['general']['lang']}{$path}.php";
$fallback = $dir . "lang/lang.".LANG_DEFAULT."{$path}.php";
}
if (!file_exists($fpath)) {
/* if file does not exist, we fall back on English */
if (!file_exists($fallback)) {
trigger_error("No suitable language file was found <b>$postfix</b>", E_USER_WARNING);
return;
}
$fpath = $fallback;
}
/* load $lang from file */
/*
* utf encoded files may output whitespaces known as BOM, we must
* capture this chars
*/
//ob_start();
include_once ($fpath);
if (!isset($lang)){
return $GLOBALS['lang'];
}
//$v = ob_get_contents();
//ob_end_clean();
// if ($v) trigger_error("[lang] <strong>$fpath</strong> produced output", E_USER_WARNING);
$GLOBALS['lang'] = array_merge_recursive($lang, $old_lang);
return $GLOBALS['lang'];
}
function lang_getconf($id) {
global $lang;
$fpath=LANG_DIR."$id/lang.conf.php";
if (file_exists($fpath)) {
include ($fpath);
return $langconf;
} else
trigger_error("Error loading config for language \"$file\"", E_USER_WARNING);
}
class lang_indexer extends fs_filelister {
var $_directory=LANG_DIR;
function _checkFile($directory, $file) {
if (is_dir("$directory/$file")) {
$this->_list[$file] = lang_getconf($file);
}
return 0;
}
}
function lang_list() {
$obj =& new lang_indexer();
return $obj->getList();
}
?>

View File

@ -0,0 +1,137 @@
<?php
class LayoutDefault {
var $content;
var $fpdb;
var $fp_widgets;
var $smarty;
var $config;
var $lang;
var $tpl = 'index.tpl';
var $message_queue = array();
function LayoutDefault($content=array()) {
$this->pagecontent = $content;
$this->fpdb =& new FPDB;
$GLOBALS['fpdb'] =& $this->fpdb;
$this->fp_widgets =& new widget_indexer;
$GLOBALS['fp_widgets'] =& $this->fp_widgets;
$this->smarty =& $GLOBALS['_FP_SMARTY'];
$GLOBALS['fp_config'] =& $this->config;
$this->config = $GLOBALS['fp_config']['general'];
$this->theme = theme_loadsettings();
$GLOBALS['theme'] =& $this->theme;
$this->lang = lang_load();
$GLOBALS['lang'] =& $this->lang;
// user_loggedin() or sess_setup();
plugin_loadall();
// init smarty
$this->smarty->compile_dir = CACHE_DIR;
$this->smarty->cache_dir = SMARTY_DIR . 'cache/';
$this->smarty->caching = 0;
do_action('init');
}
function display() {
$this->main();
theme_init($this->smarty, $this);
$this->smarty->display($this->tpl);
unset($this->smarty);
do_action('shutdown');
}
/*
function post_message($module, $ring, $message) {
$this->message_queue[$module][$ring][]=$message;
}
function flush_messages($module, $ring=-1) {
$msg_arr=array();
if ($ring<0)
$ring_arr =
array_keys($this->message_queue[$module]);
else
$ring_arr = array($ring);
foreach($ring_arr as $this_ring) {
$localq=& $this->message_queue[$module][$this_ring];
foreach ($localq as $msg) {
$msg_arr[]=$msg;
}
}
$this->smarty->append('err', $msg_arr);
return $msg_arr;
}
*/
}
class Abstract_LayoutIndex extends LayoutDefault {
var $tpl = 'index.tpl';
}
class Abstract_LayoutComment extends LayoutDefault {
var $tpl = 'comments.tpl';
}
class Abstract_LayoutDialog extends LayoutDefault {
var $tpl = 'default.tpl';
function page($subject, $content, $rawcontent=false) {
$this->pagecontent = array(
'subject'=>$subject,
'content'=>$content
);
if ($rawcontent) $this->smarty->assign('rawcontent', true);
}
function pagecontent($params, $content, &$smarty, &$repeat) {
if ($this->pagecontent) {
$this->smarty->assign($this->pagecontent);
return $content;
} else return;
}
function display() {
$this->smarty->register_block('page', array(&$this, 'pagecontent'));
parent::display();
}
}
?>

View File

@ -0,0 +1,243 @@
<?php
//define('PLUG_BLOCK', 'block');
class plugin_indexer extends fs_filelister {
var $_varname = 'fp_plugins';
var $_enabledlist = null;
var $_directory = PLUGINS_DIR;
function plugin_indexer() {
$this->_enabledlist = CONFIG_DIR . 'plugins.conf.php';
parent::fs_filelister();
}
function _checkFile($directory, $file) {
$f = "$directory/$file";
if (is_dir($f) && file_exists("$f/plugin.$file.php")) {
array_push($this->_list, $file);
}
return 0;
}
/*
*
* @param $checkonly bool if false will load all the plugins,
* if true will check if the plugin exist
*/
function getEnableds($checkonly) {
$lang =& $GLOBALS['lang'];
$errors = array();
if (!file_exists($this->_enabledlist))
return false;
include($this->_enabledlist);
$var = $this->_varname;
$this->enabledlist = $$var;
foreach ($$var as $plugin) {
$e = plugin_load($plugin, $checkonly);
if ($e)
$errors[] = $e;
}
return $errors;
}
}
function plugin_loadall($check=false){
// this is done during init process
// all the plugin are loaded
$pluginlister =& new plugin_indexer;
$enab = $pluginlister->getEnableds($check);
include_once (INCLUDES_DIR . 'core.wp-pluggable-funcs.php');
return $enab;
}
function plugin_get($id=null){
$pluginlister =& new plugin_indexer;
return $pluginlister->getList();
}
function plugin_loaded($id) {
if (file_exists(PLUGINS_DIR . $id. '/plugin.'. $id.".php")) {
return true;
}
return false;
}
function plugin_load($plugin, $checkonly=true, $langload=true) {
global $lang;
$errno = 0;
$errors = false;
if (file_exists($f = PLUGINS_DIR . "$plugin/plugin.$plugin.php")){
$errno = 1; // 1 means exists
}elseif (file_exists($f = PLUGINS_DIR . "$plugin/$plugin.php")){
$errno = 2; // 2 means exists but filename is oldstyle
}
if ($errno > 0){
include_once($f);
}
if ($langload)
@lang_load("plugin:{$plugin}");
if ($checkonly) {
$func = "plugin_{$plugin}_setup";
if (is_callable($func)){
$errno = $func();
}
if ($errno<=0) {
if (isset($lang['plugin'][$plugin]['errors'][$errno])) {
$errors = "[<strong>{$plugin}</strong>] {$lang['plugin'][$plugin]['errors'][$errno]}";
} elseif($errno<0) {
$errors = "[<strong>$plugin</strong>] " .
sprintf($lang['admin']['plugin']['errors']['generic'], $errno);
} else {
$errors = "[<strong>$plugin</strong>] " .
$lang['admin']['plugin']['errors']['notfound'];
}
}
}
return $errors;
}
function plugin_exists($id) {
return file_exists($f = PLUGINS_DIR . $id . '/plugin.'. $id.".php");
}
function plugin_do($id, $type=null){
$entry = null;
if (file_exists($f = PLUGINS_DIR . 'plugin.'. $id.".php")) {
include_once($f);
} else return false;
}
function plugin_require($id) {
return !plugin_loaded($id);
/*
global $_FP_SMARTY;
$_FP_SMARTY->trigger_error("A plugin required <strong>$id</strong> to be loaded to work properly, but $id ".
"does not appear to be loaded. Maybe the plugins have been loaded in the wrong sequence. ".
"Check your <a href=\"admin.php?p=plugins\">plugin config</a> in the control panel");
*/
}
function plugin_getdir($id) {
return PLUGINS_DIR . $id . '/';
}
function plugin_geturl($id) {
return BLOG_BASEURL . PLUGINS_DIR . $id . '/';
}
/*
*
* plugin options system might
* change
*
*/
function plugin_getoption($plugin, $key) {
global $fp_config;
return $fp_config['plugins'][ $plugin ][ $key ];
}
function plugin_addoption($plugin, $key, $val) {
global $fp_config;
return $fp_config['plugins'][ $plugin ][ $key ][ $val ];
}
function plugin_saveoptions($null=null) {
return config_save();
}
function smarty_function_plugin_getdir($params, &$smarty) {
if (!isset($params['plugin'])) //todo complete here
$smarty->trigger_error('You must set plugin= parameter to a valid id!');
return plugin_getdir($id);
}
function plugin_getinfo($plugin) {
$plugin_data = io_load_file(plugin_getdir($plugin) . "plugin.$plugin.php");
preg_match("|Plugin Name:(.*)|i", $plugin_data, $plugin_name);
preg_match("|Plugin URI:(.*)|i", $plugin_data, $plugin_uri);
preg_match("|Description:(.*)|i", $plugin_data, $description);
preg_match("|Author:(.*)|i", $plugin_data, $author_name);
preg_match("|Author URI:(.*)|i", $plugin_data, $author_uri);
if (preg_match("|Version:(.*)|i", $plugin_data, $version))
$version = trim($version[1]);
else
$version = '';
$description = wptexturize(trim($description[1]));
$name = $plugin_name[1];
$name = trim($name);
$plugin = $name;
if ('' != $plugin_uri[1] && '' != $name) {
// '" title="'.__('Visit plugin homepage').'">'.
$plugin = '<a href="' . trim($plugin_uri[1]) . $plugin.'</a>';
}
if ('' == $author_uri[1]) {
$author = trim($author_name[1]);
} else {
// . '" title="'.__('Visit author homepage').
$author = '<a href="' . trim($author_uri[1]) . '">' . trim($author_name[1]) . '</a>';
}
global $smarty;
$smarty->assign(
array (
'name' => $name,
'title' => $plugin,
'description' => $description,
'author' => $author,
'version' => $version,
'template' => $template[1]
)
);
}
$_FP_SMARTY->register_function('plugin_getdir','smarty_function_plugin_getdir');
?>

View File

@ -0,0 +1,54 @@
<?php
function sess_setup($lifetime=3600) {
if (SESSION_PATH != '')
session_save_path(SESSION_PATH);
global $fp_config;
$cparams=session_get_cookie_params();
if ($cparams['lifetime']>0 && $lifetime==0 )
$lifetime = $cparams['lifetime'];
session_set_cookie_params($lifetime);
session_name(SESS_COOKIE);
session_start();
// echo '<pre>', print_r($cparams,1), '</pre>';
}
function sess_add($key, $val) {
$_SESSION[$key] = $val;
}
function sess_remove($key) {
if (isset($_SESSION[$key])) {
$oldval=$_SESSION[$key];
unset($_SESSION[$key]);
return $oldval;
}
}
function sess_get($key) {
if (isset($_SESSION[$key]))
return $_SESSION[$key];
else return false;
}
function sess_close() {
unset($_SESSION);
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
session_set_cookie_params(-42000);
}
session_destroy();
}
?>

138
fp-includes/core/core.static.php Executable file
View File

@ -0,0 +1,138 @@
<?php
define('STATIC_DIR', CONTENT_DIR . 'static/');
class static_indexer extends fs_filelister {
var $_directory = STATIC_DIR;
function _checkfile($directory, $file) {
array_push($this->_list, basename($file,EXT));
return 0;
}
}
function static_getlist() {
$obj =& new static_indexer;
$list = $obj->getList();
return $list;
}
function static_parse($id) {
if ($fname=static_exists($id)) {
$entry = io_load_file($fname);
return array_change_key_case(utils_kexplode($entry));
}
return array();
}
function static_save($entry, $id, $oldid=null) {
$fname = STATIC_DIR . $id . EXT;
$str = utils_kimplode(array_change_key_case($entry, CASE_UPPER));
if (io_write_file($fname, $str)) {
if ( $oldid && $id!=$oldid && $fname = static_exists($oldid)) {
$succ = static_delete($oldid) ;
return ($succ !== false && $succ !== 2);
}
return true;
}
return false;
}
function static_exists($id) {
$fname = STATIC_DIR . $id . EXT;
if (file_exists($fname))
return $fname;
return false;
}
function static_delete($id) {
return fs_delete(STATIC_DIR . $id . EXT);
}
function smarty_block_statics($params, $content, &$smarty, &$repeat) {
global $fpdb;
/*
$show = false;
if (isset($params['alwaysshow']) && $params['alwaysshow']) {
return $content;
}
*/
return $content;
}
function smarty_block_static($params, $content, &$smarty, &$repeat) {
global $fpdb;
static $pointer = 0;
// clean old variables
$smarty->assign(array( 'subject'=>'',
'content'=>'',
'date'=>'',
'author'=>'',
'version'=>'',
'id'=>''
)
);
if ($arr=$smarty->get_template_vars('static_page')){
$smarty->assign('id', $smarty->get_template_vars('static_id'));
if (THEME_LEGACY_MODE)
theme_entry_filters($arr);
$smarty->assign($arr);
return $content;
}
if (isset($params['content']) && is_array($params['content']) && $params['content']) {
//foreach ($params['entry'] as $k => $val)
$smarty->assign(array_change_key_case($params['content'], CASE_LOWER));
return $content;
}
if (isset($params['alwaysshow']) && $params['alwaysshow']) {
return $content;
}
$list = $smarty->get_template_vars('statics');
if(isset($list[$pointer])) {
//foreach ($entry as $k => $val)
$smarty->assign(static_parse($list[$pointer]));
$smarty->assign('id', $list[$pointer]);
$pointer++;
$repeat = true;
} else {
$repeat = false;
}
return $content;
}
$_FP_SMARTY->register_block('statics', 'smarty_block_statics');
$_FP_SMARTY->register_block('static_block', 'smarty_block_statics');
$_FP_SMARTY->register_block('static', 'smarty_block_static');
?>

177
fp-includes/core/core.system.php Executable file
View File

@ -0,0 +1,177 @@
<?php
/**
* system.php
* string-to-php and general system functions
*/
/**
* function system_save
*
* This function saves a list of variables provided after $file
* encapsulated in an array where KEY is the var name
* in a php file.
*
* Example usage:
* <code>
* <?php
* // Let's suppose you want to save an array called $my_arr
* // in file $my_file
* $my_file = 'path/to/file'
* $my_arr = array ('val1', 'val2', 'val3');
* $save_arr = array('$my_arr' => $my_arr); //same as: $save_arr['$my_arr'] = $my_arr);
* system_save($my_file, $my_arr);
* // now the file $my_file will contain the following lines:
* // global $my_arr;
* // $my_arr = array (
* // '$my_arr' => val1',
* // '$my_arr' => 'val2',
* // '$my_arr' => 'val3'
* // );
* ?>
* </code>
*
* @param string $file file path where $array contents will be saved
* @array $var_list list of vars to be saved
* @return bool
*
* @see config_save, config_load
*
*/
function system_save($file, $array ) {
//if ( ( $numargs = func_num_args() ) > 1) {
$string = "<?php\n\n";
//$arg_list = func_get_args();
foreach ($array as $key => $arg) {
//$vname = utils_vname ($arg);
//var_export($arg);
$s = /*" global {$key};\n*/ "\${$key} = " .
var_export($arg, true) . ";\n";
$string .= $s;
}
$string .= "\n?>";
return io_write_file($file, $string);
//} else die('Wrong number of parameters!');
}
define('SYSTEM_VER', '0.704');
function system_ver() {
return 'fp-' . SYSTEM_VER;
}
function system_generate_id($string) {
return 'fp-'.dechex(crc32($string) ^ mt_rand());
}
function system_guessblogroot() {
return substr($_SERVER['REQUEST_URI'], 0,strrpos($_SERVER['REQUEST_URI'],'/')+1);
}
function system_guessbaseurl() {
return 'http://'.$_SERVER['HTTP_HOST']. BLOG_ROOT;
}
function system_getindex() {
if (MOD_BLOG != INDEX)
return MOD_BLOG;
else
return 'index.php';
}
function system_unregister_globals() {
$v = @ini_get('register_globals');
// on error we unregister anyway
if ($v || is_null($v)) {
foreach ($_REQUEST as $var => $val) {
unset($GLOBALS[$var]);
}
}
}
function system_sanitizequery() {
$err = false;
foreach ($_GET as $k => $v) {
if (preg_match('![<>]|://!', $v)) {
$err = true;
break;
}
}
if ($err) {
// @todo add log handler
utils_redirect();
}
}
function system_init() {
system_sanitizequery();
system_unregister_globals();
$GLOBALS['fpdb'] =& new FPDB;
$GLOBALS['fp_widgets'] =& new widget_indexer;
$GLOBALS['smarty'] =& $GLOBALS['_FP_SMARTY'];
$smarty =& $GLOBALS['smarty'];
$GLOBALS['fp_config'] =& config_load();
$GLOBALS['theme'] =& theme_loadsettings();
$GLOBALS['lang'] =& lang_load();
cookie_setup();
sess_setup();
user_loggedin();
plugin_loadall();
// init smarty
$smarty->compile_dir = CACHE_DIR;
$smarty->cache_dir = SMARTY_DIR . 'cache/';
$smarty->caching = 0;
do_action('init');
}
function system_seterr($module, $val) {
if ($module)
$elem = 'success_'.$module;
else
$elem = 'success';
sess_add($elem, $val);
}
function system_geterr($module='') {
if ($module)
$elem = 'success_'.$module;
else
$elem = 'success';
return sess_remove($elem);
}
/* delayed print */
function system_dpr($action, $content) {
$p = print_r($content,1);
$f = create_function('', "echo '<pre style=\'position:absolute\'>$p</pre>';");
add_action($action, $f);
}
?>

View File

@ -0,0 +1,596 @@
<?php
function theme_loadsettings() {
global $fp_config, $theme, $FLATPRESS;
$theme = array(
// name of the theme
'name' => 'theme',
// author of the theme
'author' => 'anonymous',
// theme website
'www' => 'http://flatpress.nowhereland.it',
// fp version
'version' => -1,
// default style (must be in res/ dir
'style' => array(
'style_def' => 'style.css',
// default style for admin panel (usually it's the same of the theme)
'style_admin' => 'style.css',
),
// if false a default css is used to style some elements of the panel
// if true, we'll suppose these elements are already styled in your own css's
'admin_custom_interf' => false
);
if (!defined('THE_THEME'))
define('THE_THEME', $fp_config['general']['theme']);
// backward compatibility:
$conf1 = THEMES_DIR . THE_THEME . '/theme_conf.php';
// new naming convention. Yeah, I know, just an underscore
// instead of the dot, so? It is more "consistent" :D
$conf2 = THEMES_DIR . THE_THEME . '/theme.conf.php';
if (file_exists($conf2)) {
include($conf2);
} elseif (file_exists($conf1)) {
include($conf1);
}
if (!defined('THEME_LEGACY_MODE')) {
if ($theme['version'] < 0.702) {
define('THEME_LEGACY_MODE', true);
theme_register_default_widgetsets();
} else {
define('THEME_LEGACY_MODE', false);
if ($theme['version'] > 0.704) {
if (!isset($fp_config['general']['style']))
$fp_config['general']['style'] = $theme['default_style'];
include(THEMES_DIR . THE_THEME . "/{$fp_config['general']['style']}/style.conf.php");
$theme['style'] = $style;
} else {
theme_register_default_widgetsets();
}
}
}
return $theme;
}
function theme_register_default_widgetsets() {
register_widgetset('left');
register_widgetset('right');
register_widgetset('top');
register_widgetset('bottom');
}
function theme_exists($id) {
$f = THEMES_DIR . ($id) . '/';
if (file_exists($f))
return $f;
return '';
}
function theme_style_exists($id, $themeid=THE_THEME) {
if ($f = theme_exists($themeid)) {
$fs = $f . ($id) . '/';
if (file_exists($fs))
return $fs;
}
return '';
}
function theme_geturl($id = THE_THEME) {
return BLOG_BASEURL . THEMES_DIR . $id . '/';
}
function theme_style_geturl($style, $id=THE_THEME) {
return theme_geturl($id) . $style . '/';
}
function theme_list() {
$dir = THEMES_DIR;
$dh = opendir($dir);
$i = 0;
while (false !== ($filename = readdir($dh))) {
if ( ($filename != '.') && ($filename != '..') ) {
$files[$i++] = $filename;
}
}
sort($files);
return $files;
}
function theme_wp_head() {
global $fp_config;
echo "\n<!-- FP STD HEADER -->\n";
// echo "\n<link media=\"screen\" href=\"interface/templates/form.css\" type=\"text/css\" rel=\"stylesheet\" />";
echo "\n<meta name=\"generator\" content=\"FlatPress ". system_ver() ."\" />\n";
//echo "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"Get RSS 2.0 Feed\" href=\"{$fp_config['general']['www']}rss.php\" />\n";
echo "<link rel=\"alternate\" type=\"application/rss+xml\" title=\"Get RSS 2.0 Feed\" href=\"".
theme_feed_link('rss2')
."\" />\n";
echo "<link rel=\"alternate\" type=\"application/atom+xml\" title=\"Get Atom 1.0 Feed\" href=\"".
theme_feed_link('atom')
."\" />\n";
echo "<!-- EOF FP STD HEADER -->\n";
}
function theme_head_stylesheet() {
global $fp_config, $theme;
echo "\n<!-- FP STD STYLESHEET -->\n";
echo '<link media="screen" href="';
echo BLOG_BASEURL . THEMES_DIR . THE_THEME;
$css = class_exists('adminpanel')?
$theme['style']['style_admin'] : $theme['style']['style_def'];
$substyle = '/'. (isset($fp_config['general']['style'])? $fp_config['general']['style'].'/' : '');
echo $substyle . 'res/'. $css .'" type="text/css" rel="stylesheet" />';
echo "\n<!-- FP STD STYLESHEET -->\n";
}
function admin_head_action() {
global $theme;
if (!$theme['admin_custom_interface'])
echo '<link media="screen" href="'.BLOG_BASEURL.'admin/res/admin.css" type="text/css" rel="stylesheet" />';
}
add_filter('admin_head', 'admin_head_action');
add_action('wp_head', 'theme_wp_head');
add_action('wp_head', 'theme_head_stylesheet');
function get_wp_head() {
do_action('wp_head');
if (class_exists('AdminPanel'))
do_action('admin_head');
}
$smarty->register_function('header', 'get_wp_head');
function theme_wp_footer() {
global $fp_config;
echo $fp_config['general']['footer'];
}
add_action('wp_footer', 'theme_wp_footer');
function get_wp_footer() {
do_action('wp_footer');
}
$smarty->register_function('footer', 'get_wp_footer');
function theme_charset() {
global $fp_config;
header('Content-Type: text/html; charset='. $fp_config['general']['charset']);
}
add_action('init', 'theme_charset');
function theme_init(&$smarty) { /* &$mode */
global $fp_config;
global $lang;
global $theme;
// avoid compiled tpl collision (i.e. change theme without this and cry)
$smarty->compile_id = md5($fp_config['general']['theme']);
$smarty->template_dir = THEMES_DIR . $fp_config['general']['theme'] . '/';
$loggedin = user_loggedin();
$flatpress = $fp_config['general'];
// retained for compatibility
// todo: ugly, clean this up
// smarty has constant facilities included ^_^
//$flatpress['FP_INTERFACE'] = FP_INTERFACE;
//$flatpress['BLOGURL'] = BLOG_BASEURL;
$flatpress['loggedin'] = $loggedin;
if ($loggedin)
$flatpress['user'] = user_get();
// useful shorthand for themes
// e.g. {$flatpress.themeurl}imgs/myimage.png
if (isset($fp_config['general']['style'])) {
$themeurl = theme_style_geturl($fp_config['general']['style']);
} else {
$themeurl = theme_geturl();
}
$flatpress['themeurl'] = $themeurl;
$flatpress_upper = array_change_key_case($flatpress, CASE_UPPER);
$flatpress = array_merge($flatpress, $flatpress_upper);
$smarty->assign('flatpress', $flatpress);
$smarty->assign('lang', $lang);
$smarty->assign('blogtitle', $fp_config['general']['title']);
$smarty->assign('pagetitle',
apply_filters('wp_title', "", '&raquo;'));
$smarty->assign_by_ref('fp_config', $fp_config);
$smarty->register_modifier('tag', 'theme_apply_filters_wrapper');
$smarty->register_modifier('link', 'theme_apply_filters_link_wrapper');
$smarty->register_modifier('filed', 'theme_entry_categories');
if (!isset($_GET['feed']) || empty($_GET['feed'])) {
$smarty->register_modifier('date_format_daily', 'theme_smarty_modifier_date_format_daily');
$smarty->register_modifier('date_format', 'theme_smarty_modifier_date_format');
}
$smarty->register_modifier('date_rfc3339', 'theme_smarty_modifier_date_rfc3339');
$smarty->register_function('action', 'theme_smarty_function_action');
}
function smarty_block_page($params, $content) {
return $content;
}
$smarty->register_block('page', 'smarty_block_page');
function theme_apply_filters_wrapper($var, $hook) {
$args = func_get_args();
$tmp = $args[0];
$args[0] = $args[1];
$args[1] = $tmp;
return call_user_func_array('apply_filters', $args);
}
function theme_apply_filters_link_wrapper($var, $hook) {
return apply_filters($hook, '', $var);
}
function theme_smarty_function_action($params, &$smarty) {
if (isset($params['hook']))
do_action($params['hook']);
}
function theme_smarty_modifier_date_format( $string,
$format = null,
$default_date = ''
) {
global $lang;
if ($string != '') {
$timestamp = $string; // smarty_make_timestamp($string);
} elseif ($default_date != '') {
$timestamp = $default_date; // smarty_make_timestamp($default_date);
} else {
return;
}
if (is_null($format)) {
global $fp_config;
$format = $fp_config['locale']['timeformat'];
}
// D l day
if ( strpos($format, '%a') !== false ) {
$i = strftime('%u', $timestamp);
$format = str_replace('%a', $lang['date']['weekday_abbr'][$i], $format);
}
if ( strpos($format, '%A') !== false ) {
$i = strftime('%u', $timestamp);
$format = str_replace('%A', $lang['date']['weekday'][$i], $format);
}
// F M month
if ( strpos($format, '%b') !== false ) {
$i = intval(strftime('%m', $timestamp))-1;
$format = str_replace('%b', $lang['date']['month_abbr'][$i], $format);
}
if ( strpos($format, '%B') !== false ) {
$i = intval(strftime('%m', $timestamp))-1;
$format = str_replace('%B', $lang['date']['month'][$i], $format);
}
if (DIRECTORY_SEPARATOR == '\\') {
$_win_from = array('%D', '%h', '%n', '%r', '%R', '%t', '%T');
$_win_to = array('%m/%d/%y', '%b', "\n", '%I:%M:%S %p', '%H:%M', "\t", '%H:%M:%S');
if (strpos($format, '%e') !== false) {
$_win_from[] = '%e';
$_win_to[] = sprintf('%\' 2d', date('j', $timestamp));
}
if (strpos($format, '%l') !== false) {
$_win_from[] = '%l';
$_win_to[] = sprintf('%\' 2d', date('h', $timestamp));
}
$format = str_replace($_win_from, $_win_to, $format);
}
return strftime($format, $timestamp);
}
function theme_smarty_modifier_date_format_daily(
$string,
$format = null,
$default_date = ''
) {
global $THEME_CURRENT_DAY, $lang, $fp_config;
if (is_null($format))
$format = $fp_config['locale']['dateformat'];
$current_day = theme_smarty_modifier_date_format($string, $format, $default_date);
if (!isset($THEME_CURRENT_DAY) || $THEME_CURRENT_DAY != $current_day) {
$THEME_CURRENT_DAY = $current_day;
return $current_day;
}
return '';
}
/**
* Get date in RFC3339
* For example used in XML/Atom
*
* @param integer $timestamp
* @return string date in RFC3339
* @author Boris Korobkov
* @see http://tools.ietf.org/html/rfc3339
*
* http://it.php.net/manual/en/function.date.php#75757
*
*/
function theme_smarty_modifier_date_rfc3339($timestamp='') {
if (!$timestamp) {
$timestamp = time();
}
$date = date('Y-m-d\TH:i:s', $timestamp);
$matches = array();
if (preg_match('/^([\-+])(\d{2})(\d{2})$/', date('O', $timestamp), $matches)) {
$date .= $matches[1].$matches[2].':'.$matches[3];
} else {
$date .= 'Z';
}
return $date;
}
// {{{ permalink, commentlink, staticlink: filters
add_filter('feed_link', 'theme_def_feed_link', 0, 2);
function theme_def_feed_link($str, $type) {
return BLOG_BASEURL . "?feed={$type}";
}
function theme_feed_link ($feed='rss2') {
return apply_filters('feed_link', '', $feed);
}
add_filter('post_comments_feed_link', 'theme_def_feed_comments_link', 0, 3);
function theme_def_feed_comments_link($str, $feed, $id) {
return BLOG_BASEURL . "?entry=$id&amp;comments&amp;feed={$feed}";
}
function theme_comments_feed_link ($feed='rss2', $id) {
return apply_filters('post_comments_feed_link', '', $feed, $id);
}
add_filter('post_link', 'theme_def_permalink', 0, 2);
function theme_def_permalink($str, $id) {
return BLOG_BASEURL . "?entry=$id";
}
function get_permalink ($id) {
return apply_filters('post_link', '', $id);
}
add_filter('comments_link', 'theme_def_commentlink', 0, 2);
function theme_def_commentlink($str, $id) {
return BLOG_BASEURL . "?entry=$id&amp;comments";
}
function get_comments_link ($id) {
return apply_filters('comments_link', '', $id);
}
add_filter('page_link', 'theme_def_staticlink', 0, 2);
function theme_def_staticlink($str, $id) {
return BLOG_BASEURL . "?page=$id";
}
function theme_staticlink ($id) {
return apply_filters('page_link', '', $id);
}
add_filter('category_link', 'theme_def_catlink', 0, 2);
function theme_def_catlink($str, $catid) {
return BLOG_BASEURL . "?cat=$catid";
}
function get_category_link($catid) {
return apply_filters('category_link', '', $catid);
}
function get_year_link($year) {
return wp_specialchars(
apply_filters(
'year_link',
BLOG_BASEURL . '?y='. str_pad($year, 2, '0', STR_PAD_LEFT),
$year)
);
}
function get_month_link($year, $month) {
return wp_specialchars(
apply_filters(
'month_link',
BLOG_BASEURL . '?y='. str_pad($year, 2, '0', STR_PAD_LEFT) .
'&m=' . str_pad($month, 2, '0', STR_PAD_LEFT),
$year,
$month)
);
}
function get_day_link($year, $month, $day) {
return wp_specialchars(
apply_filters(
'month_link',
BLOG_BASEURL . '?y='. str_pad($year, 2, '0', STR_PAD_LEFT)
. '&m=' . str_pad($month, 2, '0', STR_PAD_LEFT)
. '&d=' . str_pad($day, 2, '0', STR_PAD_LEFT),
$year,
$month)
);
}
// }}}
function theme_entry_commentcount($count) {
global $lang;
switch ($count) {
case 0: return $comments = $lang['main']['nocomments'];
case 1: return $comments = $lang['main']['comment'];
default: return $comments = $count . ' ' . $lang['main']['comments'];
}
}
add_filter('comments_number', 'theme_entry_commentcount');
function theme_entry_categories($cats, $link = true, $separator=', ') {
if (!$cats) {
return;
} else {
$filed=array();
if ($tmp1 = entry_categories_get('defs')) {
foreach ($tmp1 as $k=>$c) {
if(array_intersect(array($k),$cats)) {
$filed[] = $link? "<a href=\"" . get_category_link($k) ."\">$c</a>" : $c;
}
}
}
if ($filed) {
return implode($separator, $filed);
}
}
}
/*
this is called only in legacy mode
*/
// {{{ ENTRY
function &theme_entry_filters(&$contentarr, $id=null) {
$contentarr['subject']=apply_filters('the_title', $contentarr['subject']);
$contentarr['content'] = apply_filters('the_content', $contentarr['content']);
if (isset($contentarr['comments'])) {
$contentarr['commentcount'] = $contentarr['comments'];
$contentarr['comments'] = apply_filters('comments_number', $contentarr['commentcount']);
}
$contentarr['permalink']=get_permalink($id);
$contentarr['commentlink']=get_comments_link($id);
return $contentarr;
}
//{{{ COMMENTS
function &theme_comments_filters(&$contentarr, $key) {
$contentarr['name']=apply_filters('comment_author_name', $contentarr['name']);
if (isset($contentarr['email'])) {
$contentarr['email']=apply_filters('comment_author_email', $contentarr['email']);
$contentarr['mailto'] = 'mailto:' . $contentarr['email'];
}
if (!isset($contentarr['url'])) $contentarr['url'] = '#';
$contentarr['timestamp']=$contentarr['date'];
$contentarr['content']=apply_filters('comment_text', $contentarr['content']);
return $contentarr;
}
?>

184
fp-includes/core/core.users.php Executable file
View File

@ -0,0 +1,184 @@
<?php
class user_lister extends fs_filelister {
var $_varname = 'cache';
var $_cachefile = null;
var $_directory = USERS_DIR;
function bdb_entrylister() {
$this->_cachefile = CACHE_DIR . 'userlist.php';
parent::cache_filelister();
}
function _checkFile($directory, $file) {
if (fnmatch('*.php', $file)) {
array_push($this->_list, basename($file,EXT));
return 0;
}
}
}
function user_list(){
$obj =& new user_lister;
if ($users = $obj->getList()) {
return $entry_arr;
} else return false;
}
function user_pwd($userid, $pwd){
return md5($userid.$pwd);
}
function user_login($userid, $pwd, $params=null){
global $loggedin;
$loggedin = false;
$user = user_get($userid);
// $retval = 0;
/*
print_r($user);
print_r(user_pwd($userid,$pwd));
*/
if (user_pwd($userid,$pwd) == $user['password']){
$loggedin = true;
// session_regenerate_id();
$expire = time() + 31536000;
setcookie(USER_COOKIE, $userid, $expire, COOKIEPATH, COOKIE_DOMAIN);
setcookie(PASS_COOKIE, $user['password'], $expire, COOKIEPATH, COOKIE_DOMAIN);
/*
$retval = 1;
sess_close();
sess_setup(60*60*24*7);
$retval = 1;
sess_add('userid', $userid);
// sess_add('userhash', $user['PWD']);
sess_add('loggedin', true);
sess_add('ip', $_SERVER['REMOTE_ADDR']);
sess_add('host', $_SERVER['SERVER_ADDR']);
sess_add('path', ABS_PATH);
$user = user_get($userid);
$user['LOGINTIME']=time();
system_save(USERS_DIR . $user['NAME'] . ".php", compact('user'));
*/
}
return $loggedin;
}
function user_logout(){
global $loggedin;
if ( user_loggedin() ) {
setcookie(USER_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
setcookie(PASS_COOKIE, ' ', time() - 31536000, COOKIEPATH, COOKIE_DOMAIN);
/*
$user = user_get(sess_get('userid'));
unset($user['LOGINTIME']);
system_save(USERS_DIR . $user['NAME'] . ".php", compact('user'));
sess_close();
*/
}
$loggedin = false;
}
function user_loggedin(){
global $loggedin, $fp_user;
if ($loggedin)
return $fp_user;
if ( empty($_COOKIE[USER_COOKIE]) || empty($_COOKIE[PASS_COOKIE]) ) {
$fp_user = null;
return $loggedin = false;
}
// print_r($_COOKIE);
$fp_user = user_get($_COOKIE[USER_COOKIE]);
if ($fp_user) {
$loggedin = ($_COOKIE[PASS_COOKIE] == $fp_user['password']);
}
return $fp_user;
/*
//return true;
if (!$loggedin && sess_get('loggedin')) {
$user = user_get(sess_get('userid'));
// removed: sess_get('ip') == $_SERVER['REMOTE_ADDR'] &&
// quite stupid, as people usually will disconnect sooner or later :D
if (sess_get('host') == $_SERVER['SERVER_ADDR'] &&
sess_get('path') == ABS_PATH ) {
@sess_setup(60*60*24*7);
// may bug sometimes:
// session_regenerate_id();
$loggedin = true;
}
}
*/
return $loggedin;
}
function user_get($userid=null){
if ($userid == null && ($user = user_loggedin())) {
return $user;
}
if (file_exists($f = USERS_DIR . $userid.".php")) {
include($f);
return $user;
}
}
function user_add($user){
$user['password']=user_pwd($user['userid'], $user['password']);
return system_save(USERS_DIR . $user['userid'] . ".php", compact('user'));
}
?>

View File

@ -0,0 +1,362 @@
<?php
// utils.php
// library of misc utilities
// function subkey sort
// function prototype :
// array utils_sksort(array $arr, string $key, int $flag=SORT_ASC)
// sorts an array of associative arrays by given key $key
// $flag can be SORT_ASC or SORT_DESC for ascending
// or descending order (defaults to ascending);
// other flags are the same of array_multisort() php function ;)
function utils_sksort($arr, $key, $flag=SORT_ASC) {
if ($arr) {
foreach($arr as $val)
$sorter[] = $val[$key];
array_multisort($sorter, $flag, $arr);
return $arr;
} else return false;
}
// function prototype:
// bool utils_pattern_match(string $string, string $pattern)
// returns true if $pattern matches $string, else returns false (what else?)
// $pattern is a string containing standard shell-style jokers: * and ?
// regex are powerful but somtimes, too complicated :)
// usage: * matches a variable number of chars
// e.g. : doc*.txt matches document.txt, docs.txt, dock.txt, etc.
// and also doc.txt (note: I didn't want it to do that, but I didn't change it)
// ? matches one char, whichever is
// e.g. : document?.txt matches document1.txt, document2.txt, document3.txt, etc.
// likewise "*", it should match document.txt, too (but I hadn't tried it :) )
// code from http://www.php.net/function.glob.php.htm#54519
// by x_terminat_or_3 at yahoo dot country:fr
// thank you, man ;)
// as usual, slightly modified to fit my tastes :)
if (!function_exists('fnmatch')) {
function fnmatch($pattern, $string) {
if ($pattern == null)
return false;
//basically prepare a regular expression
$out=null;
$chunks=explode(';',$pattern);
foreach($chunks as $pattern)
{
$escape=array('$','^','.','{','}','(',')','[',']','|');
while(strpos($pattern,'**')!==false)
$pattern=str_replace('**','*',$pattern);
foreach($escape as $probe)
$pattern=str_replace($probe,"\\$probe",$pattern);
$pattern=str_replace('?*','*', str_replace('*?','*',
str_replace('*',".*",
str_replace('?','.{1,1}',$pattern))));
$out[]=$pattern;
}
/* // NoWhereMan note: why splitting this in two? :)
if(count($out)==1) return(eregi("^$out[0]$",$string)); else*/
foreach($out as $tester) {
if (eregi("^$tester$",$string))
return true;
}
return false;
}
}
// function prototype:
// array utils_kexplode(string $string, string $delim='|')
// explodes a string into an array by the given delimiter;
// delimiter defaults to pipe ('|').
// the string must be formatted as in:
// key1|value1|key2|value2 , etc.
// the array will look like
// $arr['key1'] = 'value1'; $arr['key2'] = 'value2'; etc.
function utils_kexplode($string, $delim='|', $keyupper=true) {
$arr = array();
$string = trim($string);
$arr[strtok($string, $delim)] = strtok($delim);
while (( $k = strtok($delim) ) !== false) {
if ($keyupper && !preg_match('/[A-Z-_]/',$k)){
/*
trigger_error("Failed parsing <pre>$string</pre>
keys were supposed to be UPPERCASE but <strong>\"$k\"</strong> was found; file may be corrupted
or in an expected format. <br />
Some SimplePHPBlog files may raise this error: set DUMB_MODE_ENABLED
to true in your defaults.php to force parsing of the offending keys.",
E_USER_WARNING);
*/
continue;
}
$arr[$k] = strtok($delim);
}
return $arr;
}
/*
function utils_newkexplode($string, $delim='|') {
$arr = array();
$lastoffset = $offset = 0;
$len = strlen($string);
while ($lastoffset<$len) {
$offset = strpos($string, $delim, $lastoffset);
$key = substr($string, $lastoffset, $offset-$lastoffset);
//echo 'parsing key: ', $key, $offset, chr(10);
$lastoffset = $offset + 1;
if (!ctype_upper($key))
trigger_error("Failed parsing \"$string\"
keys were supposed to be UPPERCASE", E_USER_ERROR);
$offset = strpos($string, $delim, $lastoffset);
if ($offset===false)
$offset = $len;
$val = substr($string, $lastoffset, $offset-$lastoffset);
//echo 'parsing value ', $val, $offset, chr(10);
$lastoffset = $offset + 1;
$arr[$key] = $val;
}
return $arr;
}*/
// function prototype:
// array utils_kimplode(string $string, string $delim='|')
// explodes a string into an array by the given delimiter;
// delimiter defaults to pipe ('|').
// the string must be formatted as in:
// key1|value1|key2|value2 , etc.
// the array will look like
// $arr['key1'] = 'value1'; $arr['key2'] = 'value2'; etc.
function utils_kimplode($arr, $delim='|') {
$string = "";
foreach ($arr as $k => $val) {
if ($val)
$string .= $k . $delim . $val . $delim;
}
return $string;
}
/**
* @todo send mail to admin
*/
function &utils_explode_recursive($array, &$string, $rdelim, $ldelim='', $outerldelim='', $outerrdelim='') {
$string .= $outerldelim;
while (list(,$val) = each($array)) {
$string .= $rdelim;
if (is_array($val)) {
$string .= utils_explode_recursive($val, $string, $rdelim, $ldelim, $outerldelim, $outerrdelim);
} else {
$string .= $val;
}
$string .= $ldelim;
}
$string .= $outerrdelim;
}
function utils_validateinput($str) {
if (preg_match('/[^a-z0-9\-_]/i',$str)){
trigger_error("String \"$str\" is not a valid input", E_USER_ERROR);
//return false;
} else
return true;
}
function utils_cut_string($str,$maxc) {
$car = strlen($str);
if($car > $maxc) {
return substr($str, 0, $maxc)."...";
} else {
return $str;
}
}
function utils_status_header($status) {
switch ($status) {
case 301:
header("HTTP/1.1 301 Moved Permanently");
break;
case 403:
header("HTTP/1.1 403 Forbidden");
break;
case 404:
header("HTTP/1.1 404 Not Found");
break;
}
}
// code from php.net ;)
// defaults to index.php ;)
function utils_redirect($location="", $absolute_path=false, $red_type=null) {
if (!$absolute_path)
$location = BLOG_BASEURL . $location;
header("Location: $location");
exit();
}
/*
* utils_geturlstring()
*
* @return string complete url string as displayed in the browser
*
*/
function utils_geturlstring() {
$str = BLOG_BASEURL . $_SERVER['PHP_SELF'];
if ($_SERVER['QUERY_STRING'])
$str .='?'.$_SERVER['QUERY_STRING'];
return $str;
}
// custom array_merge:
// pads the second array to match the length of the first
// this can be improved, anyway for now I'd just
// do a quick & dirty solution :)
function utils_array_merge($arr1, $arr2) {
$len=count($arr1[0]);
foreach($arr2 as $k=>$v)
$arr2[$k]=array_pad((Array) $v, $len, null);
return array_merge($arr1, $arr2);
}
/*
* Simple function to replicate PHP 5 behaviour
*/
function utils_microtime()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
function utils_countdashes($string, &$rest) {
trim($string);
$i = 0;
while ($string{$i} == '-') {
$i++;
}
if ($i)
$rest = substr($string, $i);
else $rest = $string;
return $i;
}
function utils_mail($from, $subject, $message, $headers = '') {
global $fp_config;
if( $headers == '' ) {
$headers = "MIME-Version: 1.0\n" .
"From: " . $from . "\n" .
"Content-Type: text/plain; charset=\"" . $fp_config['general']['charset'] . "\"\n";
}
return mail($fp_config['general']['email'], $subject, $message, $headers);
}
// get client IP
function utils_ipget() {
if ( !empty ( $_SERVER[ 'HTTP_CLIENT_IP' ] ) ) {
$ip = $_SERVER[ 'HTTP_CLIENT_IP' ];
}
elseif ( !empty ( $_SERVER[ 'HTTP_X_FORWARDED_FOR' ] ) ) {
$ip = $_SERVER[ 'HTTP_X_FORWARDED_FOR' ];
}
elseif ( !empty ( $_SERVER[ 'REMOTE_ADDR' ] ) ) {
$ip = $_SERVER[ 'REMOTE_ADDR' ];
}
elseif ( getenv( "HTTP_CLIENT_IP" ) ) {
$ip = getenv( "HTTP_CLIENT_IP" );
}
elseif ( getenv( "HTTP_X_FORWARDED_FOR" ) ) {
$ip = getenv( "HTTP_X_FORWARDED_FOR" );
}
elseif ( getenv( "REMOTE_ADDR") ) {
$ip = getenv( "REMOTE_ADDR" );
}
else {
$ip = "UNKNOWN";
}
return( $ip );
}
function utils_nocache_headers() {
@ header('Expires: Wed, 11 Jan 1984 05:00:00 GMT');
@ header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
@ header('Cache-Control: no-cache, must-revalidate, max-age=0');
@ header('Pragma: no-cache');
}
function utils_checksmarty() {
if (!file_exists(SMARTY_DIR . 'Smarty.class.php')) {
$err = <<<ERR
Fatal error: Smarty is not installed; please download it from <a href="http://smarty.php.net">http://smarty.php.net</a>; you will
probably need <a href="http://www.phpinsider.com/php/code/SmartyValidate/">SmartyValidate</a> as well; unpack them to <b>fp-includes/core/smarty</b>: please do not overwrite files in fp-includes/core/smarty/plugins/
ERR;
trigger_error($err, E_USER_ERROR);
}
}
function fplog($str) {
if(!defined('DEBUG_MODE'))
echo "\n[DEBUG] $str \n";
}
?>

174
fp-includes/core/core.widgets.php Executable file
View File

@ -0,0 +1,174 @@
<?php
/**
* Block-Managing Functions
*/
class widget_indexer extends fs_filelister {
var $_varname = 'fp_widgets';
var $_enabledlist = null;
function widget_indexer() {
if (!file_exists(CONFIG_DIR. 'widgets.conf.php'))
trigger_error('widgets.conf.php not found. Blog may not work as expected, create a widgetlist.conf.php
or reinstall completely FlatPress. If you have just installed FlatPress, the package you
downloaded may be corrupted.', E_USER_WARNING);
$this->_enabledlist = CONFIG_DIR . 'widgets.conf.php';
$this->getEnableds();
}
function getEnableds() {
if (!file_exists($this->_enabledlist))
return;
include($this->_enabledlist);
$this->_list = ${$this->_varname};
}
function hasMore($hor) {
return is_array($this->_list[$hor]) && (current($this->_list[$hor]) !== false);
}
function get($hor) {
global $fp_registered_widgets;
$content = array();
do {
list(,$id) = each($this->_list[$hor]);
@list($newid, $params) = explode(":", $id);
if ($params) $params = explode(',', $params); else $params = array();
// $var = 'plugin_' . $newid . '_widget';
$var = $fp_registered_widgets[ $newid ]['func'];
if (function_exists($var)) {
$content = call_user_func_array($var, $params);
if (!isset($content['id'])) {
$content['id'] = "widget-$newid";
}
} /*
else $content = array(
'subject' => "Sidebar::Error",
'content' => "<ul class=\"widget-error\"><li>No $var function found for plugin $newid.
Plugin may not have been loaded.
Verify whether it is enabled.</li></ul>",
);
*/
} while(!$content);
return array_change_key_case($content, CASE_LOWER);
}
}
function register_widgetset($widgetset) {
global $fp_registered_widgetsets;
if (!$fp_registered_widgetsets) {
$fp_registered_widgetsets = array();
}
if (!in_array($widgetset, $fp_registered_widgetsets))
$fp_registered_widgetsets[] = $widgetset;
}
function get_registered_widgetsets($widgetset) {
global $fp_registered_widgetsets;
if (!$fp_registered_widgetsets) {
$fp_registered_widgetsets = array();
}
return $fp_registered_widgetsets;
}
function register_widget(
$widgetid, // widget id
$widgetname, // name to show
$widget_func, // function/method to call
$num_params = 0, // number of eventually needed parameters
// -1 means optional,
// 0 means no parameters
// each N>0 means *at least* N parameters
$limit_params_to=array()// indexed array of arrays, containing
// allowed parameters (not impl.)
) {
global $fp_registered_widgets;
if (!$fp_registered_widgets)
$fp_registered_widgets = array();
/* we won't mind about collisions, for now */
$fp_registered_widgets[$widgetid] = array(
'name' => $widgetname,
'func' => $widget_func,
'nparams'=> $num_params,
//'needed'=> $params_needed,
'params'=> $limit_params_to
);
}
function get_registered_widgets($widget=null) {
global $fp_registered_widgets;
if (!$fp_registered_widgets)
$fp_registered_widgets = array();
ksort($fp_registered_widgets);
if ($widget)
return isset($fp_registered_widgets[$widget])?
$fp_registered_widgets[$widget]
:
false;
return $fp_registered_widgets;
}
function smarty_block_widgets($params, $content, &$smarty, &$repeat) {
global $fp_widgets;
if($repeat = $fp_widgets->hasMore(($params['pos']))) {
$entry = $fp_widgets->get(($params['pos']));
$smarty->assign($entry);
}
return $content;
}
$smarty->register_block('widgets','smarty_block_widgets');
?>

View File

@ -0,0 +1,96 @@
<?php
// Some default filters
add_filter('bloginfo','wp_specialchars');
add_filter('category_description', 'wptexturize');
add_filter('list_cats', 'wptexturize');
add_filter('comment_author', 'wptexturize');
add_filter('comment_text', 'wptexturize');
add_filter('single_post_title', 'wptexturize');
add_filter('the_title', 'wptexturize');
add_filter('the_content', 'wptexturize');
add_filter('the_excerpt', 'wptexturize');
add_filter('bloginfo', 'wptexturize');
// Comments, trackbacks, pingbacks
add_filter('pre_comment_author_name', 'htmlentities');
add_filter('pre_comment_author_name', 'trim');
add_filter('pre_comment_author_name', 'wp_specialchars', 30);
add_filter('pre_comment_author_email', 'trim');
add_filter('pre_comment_fauthor_email', 'sanitize_email');
add_filter('pre_comment_author_url', 'htmlentities');
add_filter('pre_comment_author_url', 'trim');
//add_filter('pre_comment_author_url', 'clean_url');
add_filter('pre_comment_content', 'stripslashes', 1);
//add_filter('pre_comment_content', 'wp_filter_kses');
add_filter('pre_comment_content', 'wp_rel_nofollow', 15);
add_filter('pre_comment_content', 'balanceTags', 30);
//add_filter('pre_comment_content', 'addslashes', 50);
//add_filter('pre_comment_author_name', 'wp_filter_kses');
//add_filter('pre_comment_author_email', 'wp_filter_kses');
//add_filter('pre_comment_author_url', 'wp_filter_kses');
// Default filters for these functions
add_filter('comment_author', 'wptexturize');
add_filter('comment_author', 'convert_chars');
add_filter('comment_author', 'wp_specialchars');
add_filter('comment_email', 'antispambot');
add_filter('comment_url', 'clean_url');
add_filter('comment_text', 'convert_chars');
add_filter('comment_text', 'make_clickable');
add_filter('comment_text', 'wpautop', 30);
//add_filter('comment_text', 'convert_smilies', 20);
add_filter('comment_excerpt', 'convert_chars');
// Places to balance tags on input
add_filter('content_save_pre', 'balanceTags', 50);
add_filter('excerpt_save_pre', 'balanceTags', 50);
add_filter('comment_save_pre', 'balanceTags', 50);
// Clean & add entities (delegated to plugins)
/*
add_filter('content_save_pre', 'wp_specialchars');
add_filter('excerpt_save_pre', 'wp_specialchars');
add_filter('comment_save_pre', 'wp_specialchars');
*/
// Misc. title, content, and excerpt filters
add_filter('the_title', 'convert_chars');
add_filter('the_title', 'trim');
//add_filter('the_content', 'convert_smilies');
add_filter('the_content', 'convert_chars');
add_filter('the_content', 'wpautop');
//add_filter('the_excerpt', 'convert_smilies');
add_filter('the_excerpt', 'convert_chars');
add_filter('the_excerpt', 'wpautop');
add_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('sanitize_title', 'sanitize_title_with_dashes');
// RSS filters
add_filter('the_title_rss', 'htmlentities');
add_filter('the_title_rss', 'ent2ncr', 8);
add_filter('the_content_rss', 'ent2ncr', 8);
add_filter('the_excerpt_rss', 'convert_chars');
add_filter('the_excerpt_rss', 'ent2ncr', 8);
add_filter('comment_author_rss', 'ent2ncr', 8);
add_filter('comment_text_rss', 'htmlspecialchars');
add_filter('comment_text_rss', 'ent2ncr', 8);
add_filter('bloginfo_rss', 'ent2ncr', 8);
add_filter('the_author', 'ent2ncr', 8);
// Actions
//add_action('publish_post', 'generic_ping');
?>

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