Update of /cvsroot/php-blog/serendipity/include
In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv23806/include
Added Files:
Tag: branch-smarty
compat.inc.php functions.inc.php functions_comments.inc.php
functions_config.inc.php functions_entries.inc.php
functions_images.inc.php functions_installer.inc.php
functions_smarty.inc.php functions_trackbacks.inc.php
genpage.inc.php lang.inc.php plugin_api.inc.php
plugin_internal.inc.php
Log Message:
* renamed files as announced on the list. upgrader will take care of moving
old files to a 'backup' directory for upgrading (non-CVS) users.
* MFH'ed some parts
* Fixed quicksave button display
* Fixed footer
* Fixed entry preview properly
* Fixed printing categories where no categories appeard in entry view
--- NEW FILE: functions_installer.inc.php ---
<?php # $Id: functions_installer.inc.php,v 1.1.2.1 2004/11/06 11:22:49 garvinhicking Exp $
function serendipity_updateLocalConfig($dbName, $dbPrefix, $dbHost, $dbUser, $dbPass, $dbType, $file = 'serendipity_config_local.inc.php', $path = null, $privateVariables = null) {
global $serendipity;
umask(0000);
if (is_null($path)) {
$path = $serendipity['serendipityPath'];
}
$configfp = fopen($path . $file, 'w');
if (!is_resource($configfp)) {
$errs[] = sprintf(FILE_WRITE_ERROR, $file);
$errs[] = sprintf(DIRECTORY_RUN_CMD, 'chown -R www:www', $path) . ' (' . WWW_USER . ')';
$errs[] = sprintf(DIRECTORY_RUN_CMD, 'chmod 770' , $path);
$errs[] = BROWSER_RELOAD;
return $errs;
}
if (isset($_POST['sqlitedbName']) && !empty($_POST['sqlitedbName'])) {
$dbName = $_POST['sqlitedbName'];
}
fwrite($configfp, "<?php\n");
fwrite($configfp, "\t/*\n");
fwrite($configfp, "\t Serendipity configuration file\n");
fwrite($configfp, "\t Written on ". date('r') ."\n");
fwrite($configfp, "\t*/\n\n");
fwrite($configfp, "\t\$serendipity['versionInstalled'] = '{$serendipity['version']}';\n");
fwrite($configfp, "\t\$serendipity['dbName'] = '{$dbName}';\n");
fwrite($configfp, "\t\$serendipity['dbPrefix'] = '{$dbPrefix}';\n");
fwrite($configfp, "\t\$serendipity['dbHost'] = '{$dbHost}';\n");
fwrite($configfp, "\t\$serendipity['dbUser'] = '{$dbUser}';\n");
fwrite($configfp, "\t\$serendipity['dbPass'] = '{$dbPass}';\n");
fwrite($configfp, "\t\$serendipity['dbType'] = '{$dbType}';\n");
if (is_array($privateVariables) && count($privateVariables) > 0) {
foreach($privateVariables AS $p_idx => $p_val) {
fwrite($configfp, "\t\$serendipity['{$p_idx}'] = '{$p_val}';\n");
}
}
fwrite($configfp, "?>\n");
fclose($configfp);
@chmod($path . $file, 0700);
return true;
}
function serendipity_query_default($optname, $default, $usertemplate = false, $type = 'string') {
global $serendipity;
/* I won't tell you the password, it's MD5 anyway, you can't do anything with it */
if ( $type == 'protected' && IS_installed === true ) {
return '';
}
switch ($optname) {
case 'dbType' :
if ( extension_loaded('mysqli') ) {
$type = 'mysqli';
}
if ( extension_loaded('postgres') ) {
$type = 'postgres';
}
if ( extension_loaded('mysql') ) {
$type = 'mysql';
}
return $type;
case 'serendipityPath':
$test_path1 = $_SERVER['DOCUMENT_ROOT'] . rtrim(dirname($_SERVER['PHP_SELF']), '/') . '/';
$test_path2 = serendipity_getRealDir(__FILE__);
if (file_exists($test_path1 . 'serendipity_entries.php')) {
return $test_path1;
} else {
return $test_path2;
}
case 'serendipityHTTPPath':
return rtrim(dirname($_SERVER['PHP_SELF']), '/') .'/';
case 'baseURL':
$ssl = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on';
$port = $_SERVER['SERVER_PORT'];
return sprintf('http%s://%s%s%s',
$ssl ? 's' : '',
preg_replace('@^([^:]+):?.*$@', '\1', $_SERVER['HTTP_HOST']),
(($ssl && $port != 443) || (!$ssl && $port != 80)) ? (':' . $port) : '',
rtrim(dirname($_SERVER['PHP_SELF']), '/') .'/'
);
case 'convert':
if (isset($_EVN['PATH'])) {
$path = explode(':', $_ENV['PATH']);
} else {
$path = '';
}
/* add some other possible locations to the path while we are at it,
* as these are not always included in the apache path */
$path[] = '/usr/X11R6/bin';
$path[] = '/usr/bin';
foreach ($path as $dir) {
if (function_exists('is_executable') && @is_executable($dir . '/convert') || @is_file($dir . '/convert')) {
return $dir . '/convert';
}
}
return $default;
default:
if ($usertemplate) {
return serendipity_get_user_var($optname, $serendipity['authorid'], $default);
}
return $default;
}
}
function serendipity_replaceEmbeddedConfigVars ($s) {
return str_replace(
array(
'[USERLEVEL_ADMIN]',
'[USERLEVEL_CHIEF]',
'[USERLEVEL_EDITOR]',
'[LANGUAGE_LIST]'
),
array(
USERLEVEL_ADMIN,
USERLEVEL_CHIEF,
USERLEVEL_EDITOR,
LANGUAGE_LIST
), $s);
}
function serendipity_parseTemplate($n, $raw = false, $prepend_var = null, $get_defaults = true) {
global $serendipity;
if (is_array($prepend_var)) {
$config = $configRaw = &$prepend_var;
$usertemplate = true;
} else {
$config = $configRaw = array();
$usertemplate = false;
}
$t = file($n, 1);
$maxt = count($t);
for ($x=0; $x<$maxt; $x++) {
$l = $t[$x];
$l = trim($l);
if ($l != '') {
switch ($l[0]) {
// New Configure section
case '/':
if ($l[1] == '/') {
$current = @constant(trim(substr($l, 2)));
$config['categories'][$current] = array();
}
break;
case '#':
$config['descriptions'][$current] = @constant(trim(substr($l, 1)));
break;
// A configure option
case '$':
// Grep out the name, type and default
preg_match('#\{([^|]+\|[^|]+\|([^}]+)?)\}[^/]+/{2}(.+)#msi', $l, $match);
// Make vars containing the elements in the | list
list($constant, $name, $type, $distdefault, $permission, $flags) = explode('|', $match[1]);
// Only show directives which are destined for this user. On installation, show everyting.
if (IS_installed === false || $serendipity['serendipityUserlevel'] >= $permission) {
$cdef = ($get_defaults ? serendipity_query_default($name, $distdefault, $usertemplate, $type) : '');
$config['categories'][$current][] = $configRaw[] = array(
'longname' => @constant($constant),
'name' => $name,
'type' => $type,
'default' => $cdef,
'distdefault' => serendipity_replaceEmbeddedConfigvars($distdefault),
'desc' => serendipity_replaceEmbeddedConfigVars(@constant(trim($match[3]))),
'valid_for' => $permission,
'flags' => explode(',', $flags)
);
}
break;
}
}
}
if ($raw) {
return $configRaw;
} else {
// Cleanup phase. Remove categories for which no variables can be defined
if (isset($config['categories']) && is_array($config['categories'])) {
foreach($config['categories'] AS $item => $itemarray) {
if (count($itemarray) < 1) {
unset($config['categories'][$item]);
}
}
}
return $config;
}
}
function serendipity_guessInput($type, $name, $value='', $default='') {
global $serendipity;
if ($name == 'rewrite' && $default == $value && isset($serendipity['rewrite_default']) && $serendipity['rewrite_default'] != '') {
$value = $serendipity['rewrite_default'];
}
switch ($type) {
case 'bool' :
$value = serendipity_get_bool($value);
echo '<input id="radio_cfg_' . $name . '_yes" type="radio" name="' . $name . '" value="true" ';
echo (($value == true) ? 'checked="checked"' : ''). ' /><label for="radio_cfg_' . $name . '_yes"> ' . YES . '</label> ';
echo '<input id="radio_cfg_' . $name . '_no" type="radio" name="' . $name . '" value="false" ';
echo (($value == true) ? '' : 'checked="checked"'). ' /><label for="radio_cfg_' . $name . '_no"> ' . NO . '</label>';
break;
case 'protected' :
echo '<input type="password" size="30" name="' . $name . '" value="' . htmlspecialchars($value) . '" />';
break;
case 'list' :
preg_match_all("/([^\=]+)\=\>([^\,]+)\,?/i", $default, $res);
echo '<select name="'. $name .'">';
for ($x=0; $x<sizeof($res[1]); $x++) {
printf('<option value="%s"%s>%s</option>'. "\n",
$res[1][$x],
(($res[1][$x] == $value) ? ' selected="selected"' : ''),
$res[2][$x]);
}
echo '</select>';
break;
default :
echo '<input type="text" size="30" name="' . $name . '" value="' . htmlspecialchars($value) . '" />';
break;
}
}
function serendipity_printConfigTemplate($t, $from = false, $minimum = false, $folding = true, $_abort = true) {
global $serendipity;
if (!isset($serendipity['XHTML11'])) {
$serendipity['XHTML11'] = FALSE;
}
if (IS_installed !== true) {
$folding = false;
}
// If not yet installed, do some magic:
$abort = false;
if (IS_installed !== true && $_abort !== true) {
$serendipity_root = dirname($_SERVER['PHP_SELF']) . '/';
$serendipity_core = serendipity_httpCoreDir();
$old_htaccess = @file_get_contents($serendipity_core . '.htaccess');
$fp = @fopen($serendipity_core . '.htaccess', 'w');
$serendipity_host = preg_replace('@^([^:]+):?.*$@', '\1', $_SERVER['HTTP_HOST']);
if (!$fp) {
printf(HTACCESS_ERROR,
'<b>chmod go+rwx ' . getcwd() . '/</b>'
);
$abort = true;
} else {
fwrite($fp, 'ErrorDocument 404 ' . $serendipity_root . 'index.php');
fclose($fp);
// Do a request on a nonexistant file to see, if our htaccess allows ErrorDocument
$sock = @fsockopen($serendipity_host, $_SERVER['SERVER_PORT'], $errorno, $errorstring, 10);
$response = '';
if ($sock) {
fputs($sock, "GET {$_SERVER['PHP_SELF']}nonexistant HTTP/1.0\r\n");
fputs($sock, "Host: $serendipity_host\r\n");
fputs($sock, "User-Agent: Serendipity/{$serendipity['version']}\r\n");
fputs($sock, "Connection: close\r\n\r\n");
while (!feof($sock) && strlen($response) < 4096) {
$response .= fgets($sock, 400);
}
fclose($sock);
}
if (preg_match('@^HTTP/\d\.\d 200@', $response) && preg_match('@X\-Blog: Serendipity@', $response)) {
$serendipity['rewrite_default'] = 'errordocs';
} else {
$serendipity['rewrite_default'] = 'none';
}
if (!empty($old_htaccess)) {
$fp = @fopen($serendipity_core . '.htaccess', 'w');
fwrite($fp, $old_htaccess);
fclose($fp);
} else {
@unlink($serendipity_core . '.htaccess');
}
}
}
if ($abort === false) {
?>
<script type="text/javascript" language="JavaScript">
function showConfig(id) {
if (document.getElementById) {
el = document.getElementById(id);
if (el.style.display == 'none') {
document.getElementById('option' + id).src = '<?php echo serendipity_getTemplateFile('img/minus.png') ?>';
el.style.display = '';
} else {
document.getElementById('option' + id).src = '<?php echo serendipity_getTemplateFile('img/plus.png') ?>';
el.style.display = 'none';
}
}
}
var state='<?php echo ($folding === true ? '' : 'none'); ?>';
function showConfigAll(count) {
if (document.getElementById) {
for (i = 1; i <= count; i++) {
document.getElementById('el' + i).style.display = state;
document.getElementById('optionel' + i).src = (state == '' ? '<?php echo serendipity_getTemplateFile('img/minus.png') ?>' : '<?php echo serendipity_getTemplateFile('img/plus.png') ?>');
}
if (state == '') {
document.getElementById('optionall').src = '<?php echo serendipity_getTemplateFile('img/minus.png') ?>';
state = 'none';
} else {
document.getElementById('optionall').src = '<?php echo serendipity_getTemplateFile('img/plus.png') ?>';
state = '';
}
}
}
</script>
<?php
if (!$minimum) {
?>
<form action="?" method="POST">
<div>
<input type="hidden" name="serendipity[adminModule]" value="installer" />
<input type="hidden" name="installAction" value="check" />
<br />
<?php }
if ( sizeof($t['categories']) > 1 ) { ?>
<div align="right">
<a style="border:0; text-decoration: none" href="#" onclick="showConfigAll(<?php echo count($t['categories']); ?>)" title="<?php echo TOGGLE_ALL; ?>"><img src="<?php echo serendipity_getTemplateFile('img/'. ($folding === true ? 'plus' : 'minus') .'.png') ?>" id="optionall" alt="+/-" border="0" /> <?php echo TOGGLE_ALL; ?></a></a><br />
</div>
<?php
}
$el_count = 0;
foreach ($t['categories'] as $key => $value) {
$el_count++;
?>
<table width="100%" cellspacing="2">
<?php
if ( sizeof($t['categories']) > 1 ) {
?>
<tr>
<th align="left" colspan="2" style="padding-left: 15px;">
<a style="border:0; text-decoration: none" href="#" onclick="showConfig('el<?php echo $el_count; ?>'); return false" title="<?php echo TOGGLE_OPTION; ?>"><img src="<?php echo serendipity_getTemplateFile('img/'. ($folding === true ? 'plus' : 'minus') .'.png') ?>" id="optionel<?php echo $el_count; ?>" alt="+/-" border="0" /> <?php echo $key; ?></a></th>
</tr>
<?php } ?>
<tr>
<td>
<table width="100%" cellspacing="0" cellpadding="3" style="<?php echo ($folding === true ? 'display: none;' : ''); ?>" id="el<?php echo $el_count; ?>">
<tr>
<td style="padding-left: 20px;" colspan="2">
<?php echo $t['descriptions'][$key] ?>
</td>
</tr>
<?php
for ($x=0; $x<count($value); $x++) {
/* Check for installOnly flag */
if ( in_array('installOnly', $value[$x]['flags']) && IS_installed === true ) {
continue;
}
/* If we have a valuelist, then use the value from there */
if (@is_array($from)) {
$value[$x]['value'] = $from[$value[$x]['name']];
}
/* If the value is never assigned in the valuelist, then use our default value */
if (!isset($from[$value[$x]['name']])) {
$value[$x]['value'] = $value[$x]['default'];
}
?>
<tr>
<td style="border-bottom: 1px #000000 solid" align="left" valign="top" width="75%">
<strong><?php echo $value[$x]['longname']; ?></strong>
<br />
<span style="color: #5E7A94; font-size: 8pt;"><?php echo '(' . $value[$x]['type'] . ') ' . $value[$x]['desc']; ?></span>
</td>
<td style="border-bottom: 1px #000000 solid; font-size: 8pt" align="left" valign="middle" width="25%">
<?php echo ($serendipity['XHTML11'] ? '<span style="white-space: nowrap">' : '<nobr>'); ?><?php echo serendipity_guessInput($value[$x]['type'], $value[$x]['name'], $value[$x]['value'], $value[$x]['distdefault']); ?><?php echo ($serendipity['XHTML11'] ? '</span>' : '</nobr>'); ?>
</td>
</tr>
<?php
}
?>
</table><br /><br />
</td>
</tr>
</table>
<?php
}
if (!$minimum) {
?>
<input type="submit" value="<?php echo CHECK_N_SAVE; ?>" />
</div>
</form>
<?php
}
}
}
function serendipity_parse_sql_tables($filename) {
$in_table = 0;
$queries = array();
$fp = fopen($filename, 'r', 1);
if ($fp) {
while (!@feof($fp)) {
$line = trim(fgets($fp, 4096));
if ($in_table) {
$def .= $line;
if (preg_match('/^\)\s*(type\=\S+)?\s*\;$/i', $line)) {
$in_table = 0;
array_push($queries, $def);
}
} else {
if (preg_match('#^create table \{PREFIX\}\S+\s*\(#i', $line)) {
$in_table = 1;
$def = $line;
}
if (preg_match('#^create\s*(\{fulltext\}|unique)\s*index#i', $line)) {
array_push($queries, $line);
}
}
}
fclose($fp);
}
return $queries;
}
function serendipity_checkInstallation() {
global $serendipity, $umask;
$errs = array();
// Check dirs
if (!is_dir($_POST['serendipityPath'])) {
$errs[] = sprintf(DIRECTORY_NON_EXISTANT, $_POST['serendipityPath']);
}
elseif (!is_writable($_POST['serendipityPath']) ) {
$errs[] = sprintf(DIRECTORY_WRITE_ERROR, $_POST['serendipityPath']);
}
elseif (!is_dir($_POST['serendipityPath'] . $_POST['uploadPath'] ) && @mkdir($_POST['serendipityPath'] . $_POST['uploadPath'], $umask) !== true) {
$errs[] = sprintf(DIRECTORY_CREATE_ERROR, $_POST['serendipityPath'] . $_POST['uploadPath']);
}
elseif (!is_writable($_POST['serendipityPath'] . $_POST['uploadPath'])) {
$errs[] = sprintf(DIRECTORY_WRITE_ERROR, $_POST['serendipityPath'] . $_POST['uploadPath']);
$errs[] = sprintf(DIRECTORY_RUN_CMD , 'chmod go+rws', $_POST['serendipityPath'] . $_POST['uploadPath']);
}
// Attempt to create the template compile directory, it might already be there, but we just want to be sure
if (!is_dir($_POST['serendipityPath'] . PATH_SMARTY_COMPILE) && @mkdir($_POST['serendipityPath'] . PATH_SMARTY_COMPILE, $umask) !== true) {
$errs[] = sprintf(DIRECTORY_CREATE_ERROR, $_POST['serendipityPath'] . PATH_ARCHIVES);
$errs[] = sprintf(DIRECTORY_RUN_CMD , 'mkdir' , $_POST['serendipityPath'] . PATH_SMARTY_COMPILE);
$errs[] = sprintf(DIRECTORY_RUN_CMD , 'chmod go+rwx', $_POST['serendipityPath'] . PATH_SMARTY_COMPILE);
} elseif (is_dir($_POST['serendipityPath'] . PATH_SMARTY_COMPILE) && !is_writeable($_POST['serendipityPath'] . PATH_SMARTY_COMPILE) && @chmod($_POST['serendipityPath'] . PATH_SMARTY_COMPILE, $umask) !== true) {
$errs[] = sprintf(DIRECTORY_RUN_CMD , 'chmod go+rwx', $_POST['serendipityPath'] . PATH_SMARTY_COMPILE);
}
// Attempt to create the archives directory
if (!is_dir($_POST['serendipityPath'] . PATH_ARCHIVES) && @mkdir($_POST['serendipityPath'] . PATH_ARCHIVES, $umask) !== true) {
$errs[] = sprintf(DIRECTORY_CREATE_ERROR, $_POST['serendipityPath'] . PATH_ARCHIVES);
$errs[] = sprintf(DIRECTORY_RUN_CMD , 'mkdir' , $_POST['serendipityPath'] . PATH_ARCHIVES);
$errs[] = sprintf(DIRECTORY_RUN_CMD , 'chmod go+rwx', $_POST['serendipityPath'] . PATH_ARCHIVES);
}
// plugins directory now part of basic CVS
// Check imagick
if ($_POST['magick'] == 'true' && !@is_executable($_POST['convert'])) {
$errs[] = sprintf(CANT_EXECUTE_BINARY, 'convert imagemagick');
}
if ($_POST['dbType'] == 'sqlite') {
// We don't want that our SQLite db file can be guessed from other applications on a server
// and have access to our's. So we randomize the SQLite dbname.
$_POST['sqlitedbName'] = $_POST['dbName'] . '_' . md5(time());
}
$serendipity['dbType'] = $_POST['dbType'];
// Probe database
// (do it after the dir stuff, as we need to be able to create the sqlite database)
@include_once($_POST['serendipityPath'] . 'include/db/db.inc.php');
// For shared installations, probe the file on include path
@include_once(S9Y_INCLUDE_PATH . 'include/db/serendipity_db.inc.php');
if (S9Y_DB_INCLUDED) {
serendipity_db_probe($_POST, $errs);
}
return (count($errs) > 0 ? $errs : '');
}
function serendipity_installDatabase() {
global $serendipity;
/* Try and check if the database/tables are already installed,
if they are... exit the function */
echo CHECK_DATABASE_EXISTS;
$t = serendipity_db_query("SELECT * FROM {$_POST['dbPrefix']}authors", false, 'both', false);
echo ' ' . DONE . '<br />';
if (is_array($t)) {
return false;
}
echo CREATE_DATABASE;
// Create tables
$queries = serendipity_parse_sql_tables($serendipity['serendipityPath'] . 'sql/db.sql');
$queries = str_replace('{PREFIX}', $_POST['dbPrefix'], $queries);
foreach ($queries as $query) {
serendipity_db_schema_import($query);
}
if ($_POST['want_mail'] == true) {
$mail_comments = 1;
} else {
$mail_comments = 0;
}
echo ' ' . DONE . '<br />';
/*
------------- Install main author ------------
*/
$enc_pass = md5($_POST['pass']);
$query = "INSERT INTO {$_POST['dbPrefix']}authors (
username,
password,
email,
mail_comments,
mail_trackbacks,
userlevel
)
VALUES (
'{$_POST['user']}',
'$enc_pass',
'{$_POST['email']}',
$mail_comments,
$mail_comments,
" . USERLEVEL_ADMIN . "
)";
serendipity_db_query($query);
$serendipity['dbPrefix'] = $_POST['dbPrefix'];
/* Set the default template */
serendipity_set_config_var('template', $serendipity['defaultTemplate']);
return true;
}
function serendipity_installFiles($serendipity_core = '') {
global $serendipity;
// This variable is transmitted from serendipity_admin_installer. If an empty variable is used,
// this means that serendipity_installFiles() was called from the auto-updater facility.
if (empty($serendipity_core)) {
$serendipity_core = $serendipity['serendipityPath'];
}
$htaccess = @file_get_contents($serendipity_core . '.htaccess');
// Let this function be callable outside installation and let it use existing settings.
$import = array('rewrite', 'serendipityHTTPPath', 'indexFile');
foreach($import AS $key) {
if (empty($_POST[$key]) && isset($serendipity[$key])) {
$$key = $serendipity[$key];
} else {
$$key = $_POST[$key];
}
}
if (php_sapi_name() == 'cgi' || php_sapi_name() == 'cgi-fcgi') {
$htaccess_cgi = '_cgi';
} else {
$htaccess_cgi = '';
}
/* Detect comptability with php_value directives */
if ($htaccess_cgi == '') {
$response = '';
$serendipity_root = dirname($_SERVER['PHP_SELF']) . '/';
$serendipity_host = preg_replace('@^([^:]+):?.*$@', '\1', $_SERVER['HTTP_HOST']);
$old_htaccess = @file_get_contents($serendipity_core . '.htaccess');
$fp = @fopen($serendipity_core . '.htaccess', 'w');
if ($fp) {
fwrite($fp, 'php_value register_globals off'. "\n" .'php_value session.use_trans_sid 0');
fclose($fp);
$sock = @fsockopen($serendipity_host, $_SERVER['SERVER_PORT'], $errorno, $errorstring, 10);
if ($sock) {
fputs($sock, "GET {$serendipity['serendipityHTTPPath']} HTTP/1.0\r\n");
fputs($sock, "Host: $serendipity_host\r\n");
fputs($sock, "User-Agent: Serendipity/{$serendipity['version']}\r\n");
fputs($sock, "Connection: close\r\n\r\n");
while (!feof($sock) && strlen($response) < 4096) {
$response .= fgets($sock, 400);
}
fclose($sock);
}
/* If we get HTTP 500 Internal Server Error, we have to use the .cgi template */
if (preg_match('@^HTTP/\d\.\d 500@', $response)) {
$htaccess_cgi = '_cgi';
}
if (!empty($old_htaccess)) {
$fp = @fopen($serendipity_core . '.htaccess', 'w');
fwrite($fp, $old_htaccess);
fclose($fp);
} else {
@unlink($serendipity_core . '.htaccess');
}
}
}
if ($rewrite == 'rewrite') {
$template = 'htaccess' . $htaccess_cgi . '_rewrite.tpl';
} elseif ($rewrite == 'errordocs') {
$template = 'htaccess' . $htaccess_cgi . '_errordocs.tpl';
} else {
$template = 'htaccess' . $htaccess_cgi . '_normal.tpl';
}
if (!($a = file(S9Y_INCLUDE_PATH . 'include/tpl/' . $template, 1))) {
$err[] = ERROR_TEMPLATE_FILE;
}
$content = str_replace(
array(
'{PREFIX}',
'{indexFile}',
'{PAT_UNSUBSCRIBE}', '{PATH_UNSUBSCRIBE}',
'{PAT_ARCHIVES}', '{PATH_ARCHIVES}',
'{PAT_ARCHIVES_SHORT}',
'{PAT_FEEDS}', '{PATH_FEEDS}',
'{PAT_FEED}',
'{PAT_ADMIN}', '{PATH_ADMIN}',
'{PAT_ENTRIES}', '{PATH_ENTRIES}',
'{PAT_ARCHIVE}', '{PATH_ARCHIVE}',
'{PAT_CATEGORIES}', '{PATH_CATEGORIES}',
'{PAT_PLUGIN}', '{PATH_PLUGIN}',
'{PAT_DELETE}', '{PATH_DELETE}',
'{PAT_APPROVE}', '{PATH_APPROVE}'
),
array(
$serendipityHTTPPath,
$indexFile,
trim(PAT_UNSUBSCRIBE, '@/i'), PATH_UNSUBSCRIBE,
trim(PAT_ARCHIVES, '@/i'), PATH_ARCHIVES,
trim(PAT_ARCHIVES_SHORT, '@/i'),
trim(PAT_FEEDS, '@/i'), PATH_FEEDS,
trim(PAT_FEED, '@/i'),
trim(PAT_ADMIN, '@/i'), PATH_ADMIN,
trim(PAT_ENTRIES, '@/i'), PATH_ENTRIES,
trim(PAT_ARCHIVE, '@/i'), PATH_ARCHIVE,
trim(PAT_CATEGORIES, '@/i'), PATH_CATEGORIES,
trim(PAT_PLUGIN, '@/i'), PATH_PLUGIN,
trim(PAT_DELETE, '@/i'), PATH_DELETE,
trim(PAT_APPROVE, '@/i'), PATH_APPROVE
),
implode('', $a)
);
$fp = @fopen($serendipity_core . '.htaccess', 'w');
if (!$fp) {
$errs[] = sprintf(FILE_WRITE_ERROR, $serendipity_core . '.htaccess') . ' ' . FILE_CREATE_YOURSELF;
$errs[] = sprintf(COPY_CODE_BELOW , $serendipity_core . '.htaccess', 'serendipity', htmlspecialchars($content));
return $errs;
} else {
// Check if an old htaccess file existed and try to preserve its contents. Otherwise completely wipe the file.
if ($htaccess != '' && preg_match('@^(.*)#\s+BEGIN\s+s9y.*#\s+END\s+s9y(.*)$@isU', $htaccess, $match)) {
// Code outside from s9y-code was found.
fwrite($fp, $match[1] . $content . $match[2]);
} else {
fwrite($fp, $content);
}
fclose($fp);
return true;
}
}
function serendipity_updateConfiguration() {
global $serendipity, $umask;
// Save all basic config variables to the database
$p = serendipity_parseTemplate(S9Y_CONFIG_TEMPLATE, true);
if (isset($_POST['sqlitedbName']) && !empty($_POST['sqlitedbName'])) {
$_POST['dbName'] = $_POST['sqlitedbName'];
}
foreach($p as $key => $entry) {
serendipity_set_config_var(
$entry['name'],
$_POST[$entry['name']],
(($entry['range'] == 'global' || $serendipity['serendipityUserlevel'] >= USERLEVEL_ADMIN || IS_installed === false) ? 0 : $serendipity['authorid'])
);
}
// Save all user-relevant data in the usertable. Only when s9y is installed.
if (IS_installed === true) {
$u = serendipity_parseTemplate(S9Y_CONFIG_USERTEMPLATE, true);
foreach($u AS $key => $entry) {
serendipity_set_user_var(
$entry['name'],
$_POST[$entry['name']],
($entry['range'] == 'global' ? 0 : $serendipity['authorid'])
);
}
}
if (IS_installed === false || $serendipity['serendipityUserlevel'] >= USERLEVEL_ADMIN) {
return serendipity_updateLocalConfig($_POST['dbName'],
$_POST['dbPrefix'],
$_POST['dbHost'],
$_POST['dbUser'],
$_POST['dbPass'],
$_POST['dbType'],
'serendipity_config_local.inc.php',
$_POST['serendipityPath']);
} else {
return true;
}
}
function serendipity_httpCoreDir() {
if (!empty($_SERVER['SCRIPT_FILENAME'])) {
return dirname($_SERVER['SCRIPT_FILENAME']) . '/';
}
return $_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['PHP_SELF']) . '/';
}
function serendipity_removeFiles($files = null) {
global $serendipity, $errors;
if (!is_array($files)) {
return;
}
$backupdir = S9Y_INCLUDE_PATH . 'backup';
if (!is_dir($backupdir)) {
@mkdir($backupdir, 0777);
if (!is_dir($backupdir)) {
$errors[] = sprintf(DIRECTORY_CREATE_ERROR, $backupdir);
return false;
}
}
if (!is_writable($backupdir)) {
$errors[] = sprintf(DIRECTORY_WRITE_ERROR, $backupdir);
return false;
}
foreach($files AS $file) {
$source = S9Y_INCLUDE_PATH . $file;
$sanefile = str_replace('/', '_', $file);
$target = $backupdir . '/' . $sanefile;
if (!file_exists($source)) {
continue;
}
if (file_exists($target)) {
$target = $backupdir . '/' . time() . '.' . $sanefile; // Backupped file already exists. Append with timestamp as name.
}
if (!is_writable($source)) {
$errors[] = sprintf(FILE_WRITE_ERROR, $source) . '<br />';
} else {
rename($source, $target);
}
}
}
?>
--- NEW FILE: functions_smarty.inc.php ---
<?php # $Id: functions_smarty.inc.php,v 1.1.2.1 2004/11/06 11:22:49 garvinhicking Exp $
function serendipity_smarty_fetch($block, $file, $echo = false) {
global $serendipity;
$output = $serendipity['smarty']->fetch('file:'. serendipity_getTemplateFile($file, 'serendipityPath'), null, null, ($echo === true && $serendipity['smarty_raw_mode']));
$serendipity['smarty']->assign($block, $output);
return $output;
}
function serendipity_emptyPrefix($string, $prefix = ': ') {
return (!empty($string) ? $prefix . htmlspecialchars($string) : '');
}
function serendipity_smarty_hookPlugin($params, &$smarty) {
global $serendipity;
static $hookable = array('frontend_header',
'entries_footer',
'frontend_comment');
if ( !isset($params['hook']) ) {
$smarty->trigger_error(__FUNCTION__ .": missing 'hook' parameter");
return;
}
if ( !in_array($params['hook'], $hookable) ) {
$smarty->trigger_error(__FUNCTION__ .": illegal hook '". $params['hook'] ."'");
return;
}
if ( !isset($params['data']) ) {
$params['data'] = &$serendipity;
}
if ( !isset($params['adddata']) ) {
$params['add'] = null;
}
serendipity_plugin_api::hook_event($params['hook'], $params['data'], $params['add']);
}
function serendipity_smarty_printSidebar($params, &$smarty) {
if ( !isset($params['side']) ) {
$smarty->trigger_error(__FUNCTION__ .": missing 'side' parameter");
return;
}
return serendipity_plugin_api::generate_plugins($params['side']);
}
function serendipity_smarty_getFile($params, &$smarty) {
if ( !isset($params['file']) ) {
$smarty->trigger_error(__FUNCTION__ .": missing 'file' parameter");
return;
}
return serendipity_getTemplateFile($params['file']);
}
function serendipity_smarty_formatTime($timestamp, $format) {
if (defined($format)) {
return serendipity_formatTime(constant($format), $timestamp);
} else {
return serendipity_formatTime($format, $timestamp);
}
}
function serendipity_smarty_printComments($params, &$smarty) {
global $serendipity;
if (!isset($params['entry'])) {
$smarty->trigger_error(__FUNCTION__ .": missing 'entry' parameter");
return;
}
if (!isset($params['mode'])) {
$params['mode'] = VIEWMODE_THREADED;
}
$comments = serendipity_fetchComments($params['entry']);
if (!empty($serendipity['POST']['preview'])) {
$comments[] =
array(
'email' => $serendipity['POST']['email'],
'username' => $serendipity['POST']['name'],
'body' => $serendipity['POST']['comment'],
'url' => $serendipity['POST']['url'],
'parent_id' => $serendipity['POST']['replyTo'],
'timestamp' => time()
);
}
return serendipity_printComments($comments, $params['mode']);
}
function serendipity_smarty_printTrackbacks($params, &$smarty) {
if ( !isset($params['entry']) ) {
$smarty->trigger_error(__FUNCTION__ .": missing 'entry' parameter");
return;
}
return serendipity_printTrackbacks(serendipity_fetchTrackbacks($params['entry']));
}
function serendipity_smarty_assignDefaults() {
global $serendipity;
$serendipity['smarty']->assign(
array(
'head_charset' => LANG_CHARSET,
'head_version' => $serendipity['version'],
'CONST' => get_defined_constants(),
'is_xhtml' => $serendipity['XHTML11'],
'use_popups' => $serendipity['enablePopup'],
'is_embedded' => (!$serendipity['embed'] || $serendipity['embed'] === 'false' || $serendipity['embed'] === false) ? false : true,
'is_raw_mode' => $serendipity['smarty_raw_mode'],
'entry_id' => (isset($serendipity['GET']['id']) && is_numeric($serendipity['GET']['id'])) ? $serendipity['GET']['id'] : false,
'is_single_entry' => (isset($serendipity['GET']['id']) && is_numeric($serendipity['GET']['id'])),
'blogTitle' => htmlspecialchars($serendipity['blogTitle']),
'blogSubTitle' => htmlspecialchars($serendipity['blogSubTitle']),
'blogDescription' => htmlspecialchars($serendipity['blogDescription']),
'serendipityHTTPPath' => $serendipity['serendipityHTTPPath'],
'serendipityBaseURL' => $serendipity['baseURL'],
'serendipityRewritePrefix' => $serendipity['rewrite'] == 'none' ? $serendipity['indexFile'] . '?/' : '',
'serendipityIndexFile' => $serendipity['indexFile']
)
);
return true;
}
--- NEW FILE: lang.inc.php ---
<?php # $Id: lang.inc.php,v 1.1.2.1 2004/11/06 11:22:49 garvinhicking Exp $
if (!defined('LANGUAGE_LIST')) define('LANGUAGE_LIST', 'en=>English,de=>German,da=>Danish,es=>Spanish,fr=>French,cs=>Czech (Win-1250),cz=>Czech (ISO-8859-2),nl=>Dutch,pt=>Portuguese Brazilian,bg=>Bulgarian,no=>Norwegian,it=>Italian');
if (!defined('serendipity_LANG_LOADED') || serendipity_LANG_LOADED !== true) {
// Try and include preferred language from the configurated setting
if (@include(S9Y_INCLUDE_PATH . 'lang/serendipity_lang_'. $serendipity['lang'] .'.inc.php') ) {
// Only here can we truely say the language is loaded
define('serendipity_LANG_LOADED', true);
} elseif (IS_installed === false || (defined('IS_up2date') && IS_up2date === false)) { /* -- Auto-Guess -- */
// If no config file is loaded, language includes are not available.
// Now include one. Try to auto-guess the language by looking up the HTTP_ACCEPT_LANGUAGE.
$serendipty['autolang'] = 'en';
$supported_languages = array('en', 'da', 'de', 'es', 'cs', 'cz', 'fr', 'nl', 'pt', 'bg', 'no', 'it');
$possible_languages = explode(',', (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : ''));
if (is_array($possible_languages)) {
foreach($possible_languages as $index => $lang) {
$preferred_language = strtolower(preg_replace('@^([^\-_;]*)_?.*$@', '\1', $lang));
if (in_array($preferred_language, $supported_languages)) {
@include_once(S9Y_INCLUDE_PATH . 'lang/serendipity_lang_' . $preferred_language . '.inc.php');
$serendipity['autolang'] = $preferred_language;
break;
} // endif
} // endforeach
} // endif
} //endif
// Do fallback to english
if ((defined('serendipity_LANG_LOADED') && serendipity_LANG_LOADED === true) || IS_installed === false || (defined('IS_up2date') && IS_up2date === false)) {
@include_once(S9Y_INCLUDE_PATH . 'lang/serendipity_lang_en.inc.php');
}
}
/* vim: set sts=4 ts=4 expandtab : */
?>
--- NEW FILE: functions_config.inc.php ---
<?php # $Id: functions_config.inc.php,v 1.1.2.1 2004/11/06 11:22:49 garvinhicking Exp $
function serendipity_set_config_var($name, $val, $authorid = 0) {
global $serendipity;
serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}config where name='" . serendipity_db_escape_string($name) . "' AND authorid = " . (int)$authorid);
$r = serendipity_db_insert('config', array('name' => $name, 'value' => $val, 'authorid' => $authorid));
$serendipity[$name] = $val;
if (is_string($r)) {
echo $r;
}
}
function serendipity_get_config_var($name, $defval = false, $empty = false) {
global $serendipity;
if (isset($serendipity[$name])) {
if ($empty && gettype($serendipity[$name]) == 'string' && $serendipity[$name] === '') {
return $defval;
} else {
return $serendipity[$name];
}
} else {
return $defval;
}
}
function serendipity_get_user_var($name, $authorid, $default) {
global $serendipity;
$r = serendipity_db_query("SELECT $name FROM {$serendipity['dbPrefix']}authors WHERE authorid = " . (int)$authorid, true);
if (is_array($r)) {
return $r[0];
} else {
return $default;
}
}
function serendipity_set_user_var($name, $val, $authorid, $copy_to_s9y = true) {
global $serendipity;
// When inserting a DB value, this array maps the new values to the corresponding s9y variables
static $user_map_array = array(
'username' => 'serendipityUser',
'email' => 'serendipityEmail',
'userlevel' => 'serendipityUserlevel'
);
// Special case for inserting a password
switch($name) {
case 'password':
if (empty($val)) {
return;
}
$val = md5($val);
$copy_to_s9y = false;
break;
case 'right_publish':
case 'mail_comments':
case 'mail_trackbacks':
$val = (serendipity_db_bool($val) ? 1 : '0');
break;
}
serendipity_db_query("UPDATE {$serendipity['dbPrefix']}authors SET $name = '" . serendipity_db_escape_string($val) . "' WHERE authorid = " . (int)$authorid);
if ($copy_to_s9y) {
if (isset($user_map_array[$name])) {
$key = $user_map_array[$name];
} else {
$key = 'serendipity' . ucfirst($name);
}
$_SESSION[$key] = $serendipity[$key] = $val;
}
}
function serendipity_getTemplateFile($file, $key = 'serendipityHTTPPath') {
global $serendipity;
$directories = array(
(isset($serendipity['template']) ? $serendipity['template'] . '/' : ''),
$serendipity['defaultTemplate'] .'/',
'default/'
);
foreach ($directories as $directory) {
$templateFile = $serendipity['templatePath'] . $directory . $file;
if (file_exists($serendipity['serendipityPath'] . $templateFile)) {
return $serendipity[$key] . $templateFile;
}
}
return false;
}
function serendipity_load_configuration($author = null) {
global $serendipity;
if (!empty($author)) {
// Replace default configuration directives with user-relevant data
$rows = serendipity_db_query("SELECT name,value
FROM {$serendipity['dbPrefix']}config
WHERE authorid = '". (int)$author ."'");
} else {
// Only get default variables, user-independent (frontend)
$rows = serendipity_db_query("SELECT name,value
FROM {$serendipity['dbPrefix']}config
WHERE authorid = 0");
}
if (is_array($rows)) {
foreach ($rows as $row) {
// Convert 'true' and 'false' into booleans
$serendipity[$row['name']] = serendipity_get_bool($row['value']);
}
}
}
/* vim: set sts=4 ts=4 expandtab : */
?>
--- NEW FILE: genpage.inc.php ---
<?php # $Id: genpage.inc.php,v 1.1.2.1 2004/11/06 11:22:49 garvinhicking Exp $
include_once('serendipity_config.inc.php');
include_once(S9Y_INCLUDE_PATH . 'include/plugin_api.inc.php');
include_once(S9Y_INCLUDE_PATH . 'include/plugin_internal.inc.php');
$serendipity['smarty_file'] = 'index.tpl';
if (file_exists($serendipity['smarty']->template_dir . '/layout.php')) {
$serendipity['smarty_raw_mode'] = true;
} else {
$serendipity['smarty_raw_mode'] = false;
}
serendipity_smarty_assignDefaults();
$serendipity['smarty']->assign(
array(
'leftSidebarElements' => serendipity_plugin_api::count_plugins('left'),
'rightSidebarElements' => serendipity_plugin_api::count_plugins('right')
)
);
if ($serendipity['smarty_raw_mode']) {
include_once(serendipity_getTemplateFile('layout.php', 'serendipityPath'));
} else {
include_once(serendipity_getTemplateFile('smarty_layout.php', 'serendipityPath'));
serendipity_smarty_fetch('CONTENT', 'content.tpl');
}
/* vim: set sts=4 ts=4 expandtab : */
?>
--- NEW FILE: functions.inc.php ---
<?php # $Id: functions.inc.php,v 1.1.2.1 2004/11/06 11:22:49 garvinhicking Exp $
# Copyright (c) 2003-2004, Jannis Hermanns
# All rights reserved. See LICENSE file for licensing details
$serendipity['imageList'] = array();
include_once(S9Y_INCLUDE_PATH . "include/db/db.inc.php");
include_once(S9Y_INCLUDE_PATH . "include/compat.inc.php");
include_once(S9Y_INCLUDE_PATH . "include/functions_config.inc.php");
include_once(S9Y_INCLUDE_PATH . "bundled-libs/XML/RPC.php");
include_once(S9Y_INCLUDE_PATH . "include/plugin_api.inc.php");
include_once(S9Y_INCLUDE_PATH . "include/functions_images.inc.php");
include_once(S9Y_INCLUDE_PATH . "include/functions_installer.inc.php");
include_once(S9Y_INCLUDE_PATH . "include/functions_entries.inc.php");
include_once(S9Y_INCLUDE_PATH . "include/functions_comments.inc.php");
include_once(S9Y_INCLUDE_PATH . "include/functions_trackbacks.inc.php");
include_once(S9Y_INCLUDE_PATH . "include/functions_smarty.inc.php");
function serendipity_truncateString($s, $len) {
if ( strlen($s) > ($len+3) ) {
$s = substr($s, 0, $len) . '...';
}
return $s;
}
function serendipity_formatTime($format, $time) {
static $cache;
if (!isset($cache)) {
$cache = array();
}
if (!isset($cache[$format])) {
$cache[$format] = $format;
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$cache[$format] = str_replace('%e', '%d', $cache[$format]);
}
}
return ucfirst(strftime($cache[$format], (int)$time));
}
function serendipity_logout() {
$_SESSION['serendipityAuthedUser'] = false;
@session_destroy();
serendipity_deleteCookie('author_information');
}
function serendipity_login() {
global $serendipity;
if (serendipity_authenticate_author()) {
#The session has this data already
#we previously just checked the value of $_SESSION['serendipityAuthedUser'] but
#we need the authorid still, so call serendipity_authenticate_author with blank
#params
return true;
}
if (serendipity_authenticate_author($serendipity['POST']['user'], $serendipity['POST']['pass'])) {
if (empty($serendipity['POST']['auto'])) {
serendipity_deleteCookie('author_information');
return false;
} else {
$package = serialize(array('username' => $serendipity['POST']['user'],
'password' => $serendipity['POST']['pass']));
serendipity_setCookie('author_information', base64_encode($package));
return true;
}
} elseif ( isset($serendipity['COOKIE']['author_information']) ) {
$cookie = unserialize(base64_decode($serendipity['COOKIE']['author_information']));
if (serendipity_authenticate_author($cookie['username'], $cookie['password'])) {
return true;
} else {
serendipity_deleteCookie('author_information');
return false;
}
}
}
function serendipity_userLoggedIn() {
if ($_SESSION['serendipityAuthedUser'] === true && IS_installed) {
return true;
} else {
return false;
}
}
function serendipity_fetchTemplates() {
global $serendipity;
$dir = opendir($serendipity['serendipityPath'] . $serendipity['templatePath']);
while (($file = readdir($dir)) !== false) {
if (is_dir($serendipity['serendipityPath'] . $serendipity['templatePath'] . $file) && !ereg('^(\.|CVS)', $file) && !file_exists($serendipity['serendipityPath'] . $serendipity['templatePath'] . $file . '/inactive.txt') && file_exists($serendipity['serendipityPath'] . $serendipity['templatePath'] . $file . '/info.txt')) {
$rv[] = $file;
}
}
natcasesort($rv);
return $rv;
}
function serendipity_fetchTemplateInfo($theme) {
global $serendipity;
/* Blame jannis */
$lines = file($serendipity['serendipityPath'] . $serendipity['templatePath'] . $theme . '/info.txt');
for($x=0; $x<count($lines); $x++) {
$j = preg_split('/([^\:]+)\:/', $lines[$x], -1, PREG_SPLIT_DELIM_CAPTURE);
if ($j[2]) {
$currSec = $j[1];
$data[strtolower($currSec)][] = trim($j[2]);
} else {
$data[strtolower($currSec)][] = trim($j[0]);
}
}
foreach ($data as $k => $v) {
$data[$k] = implode("\n", $v);
}
return $data;
}
function serendipity_setCookie($name,$value) {
global $serendipity;
setcookie("serendipity[$name]", $value, time()+60*60*24*30, $serendipity['serendipityHTTPPath']);
$_COOKIE[$name] = $value;
$serendipity['COOKIE'][$name] = $value;
}
function serendipity_deleteCookie($name) {
global $serendipity;
setcookie("serendipity[$name]", '', time()-4000);
unset($_COOKIE[$name]);
unset($serendipity['COOKIE'][$name]);
}
function serendipity_fetchUsers($user = '') {
global $serendipity;
$where = '';
if (!empty($user)) {
$where = "WHERE authorid = '" . (int)$user ."'";
}
$querystring = "SELECT * FROM {$serendipity['dbPrefix']}authors $where ORDER BY username ASC";
return serendipity_db_query($querystring);
}
/**
* Creates a filename that consists of [a-zA-z0-9-] (with some custom adjustments (space -> _, ä -> ae and such)
**/
function serendipity_makeFilename($str) {
static $from = array(
' ',
'Ä',
'ä',
'Ö',
'ö',
'Ü',
'ü',
'ß',
'é',
'è',
'ê',
'í',
'ì',
'î',
'á',
'à',
'â',
'å',
'ó',
'ò',
'ô',
'õ',
'ú',
'ù',
'û',
'ç',
'Ç',
'ñ',
'ý');
static $to = array(
'-',
'AE',
'ae',
'OE',
'oe',
'UE',
'ue',
'ss',
'e',
'e',
'e',
'i',
'i',
'i',
'a',
'a',
'a',
'a',
'o',
'o',
'o',
'o',
'u',
'u',
'u',
'c',
'C',
'n',
'y');
// For pretty urls we want to have a '+' as word separator. But GUIDs need to stay used to using '_' to not break bc.
// (For performance reasons this changes the static array instead of using a second str_replace call only for the ' ' case,
// and to avoid a costy call to array_merge()
if ($compat !== true) {
$to[0] = '-';
} else {
$to[0] = '_';
}
// Replace international chars not detected by every locale
$str = str_replace($from, $to, $str);
// Nuke chars not allowed in our URI
$str = preg_replace('#[^' . PAT_FILENAME . ']#i', '', $str);
// Remove consecutive separators
$str = preg_replace('#'. $to[0] .'{2,}#s', $to[0], $str);
// Remove excess separators
$str = trim($str, $to[0]);
return $str;
}
function serendipity_fetchReferences($id) {
global $serendipity;
$query = "SELECT name,link FROM {$serendipity['dbPrefix']}references WHERE entry_id = '" . (int)$id . "'";
return serendipity_db_query($query);
}
function serendipity_utf8_encode($string) {
if (strtolower(LANG_CHARSET) != 'utf-8') {
if (function_exists('iconv')) {
return iconv(LANG_CHARSET, 'UTF-8', $string);
} else {
return utf8_encode($string);
}
} else {
return $string;
}
}
function serendipity_rss_getguid($entry, $comments = false) {
$guid = serendipity_archiveURL((isset($entry['entryid']) && $entry['entryid'] != '' ? $entry['entryid'] : $entry['id']), 'guid');
if ($comments == true) {
$guid .= '#c' . $entry['commentid'];
}
return $guid;
}
// jbalcorn: starter function to clean up xhtml for atom feed. Add things to this as we find common
// mistakes, unless someone finds a better way to do this.
// DONE:
// since someone encoded all the urls, we can now assume any amp followed by
// whitespace or a HTML tag (i.e. &<br /> )should be
// encoded and most not with a space are intentional
// TODO:
// check ALL ampersands, find out if it's a valid code, and encode if not
function xhtml_cleanup($html) {
static $p = array(
'/\&([\s\<])/', // ampersand followed by whitespace or tag
'/\&$/', // ampersand at end of body
'/<(br|hr|img)([^\/>]*)>/i', // unclosed br tag - attributes included
);
static $r = array(
'&\1',
'&',
'<\1\2 />'
);
return preg_replace($p, $r, $html);
}
/* Uses logic to figure out how the URI should look, based on current rewrite rule */
function serendipity_rewriteURL($path, $key='baseURL') {
global $serendipity;
return $serendipity[$key] . ($serendipity['rewrite'] == 'none' ? $serendipity['indexFile'] . '?/' : '') . $path;
}
function serendipity_archiveURL($id, $title, $key = 'baseURL', $checkrewrite = true) {
$path = PATH_ARCHIVES . '/' . (int)$id . '-' . serendipity_makeFilename($title) . '.html';
if ( $checkrewrite ) {
$path = serendipity_rewriteURL($path, $key);
}
return $path;
}
function serendipity_archiveDateUrl($range, $summary=false, $key='baseURL') {
return serendipity_rewriteURL(PATH_ARCHIVES . '/' . $range . ($summary ? '/summary' : '') . '.html', $key);
}
/**
* Returns the maximum file upload size, in bytes (0 if none).
**/
function serendipity_maxfileuploadsize() {
if ( $val = trim(ini_get('upload_max_filesize')) == '' )
return 0;
switch(substr($val, -1)) {
case 'k':
case 'K':
return (int) $val * 1024;
break;
case 'm':
case 'M':
return (int) $val * 1048576;
break;
default:
return $val;
}
}
function serendipity_fetchAuthor($author) {
global $serendipity;
return serendipity_db_query("SELECT * FROM {$serendipity['dbPrefix']}authors WHERE " . (is_numeric($author) ? "authorid={$author};" : "username='{$author}';"));
}
/**
* Split up a filename
**/
function serendipity_parseFileName($file) {
$x = explode('.', $file);
$suf = array_pop($x);
$f = @implode('.', $x);
return array($f, $suf);
}
function serendipity_authenticate_author($username = '', $password = '', $is_md5 = false) {
global $serendipity;
if (isset($_SESSION['serendipityUser']) && isset($_SESSION['serendipityPassword']) && isset($_SESSION['serendipityAuthedUser']) && $_SESSION['serendipityAuthedUser'] == true) {
$username = $_SESSION['serendipityUser'];
$password = $_SESSION['serendipityPassword'];
// For safety reasons when multiple blogs are installed on the same host, we need to check the current author each time to not let him log into a different blog with the same sessiondata
$is_md5 = true;
}
if ($username != '') {
if ($is_md5 === false && !empty($password)) {
$password = md5($password);
}
$query = "SELECT DISTINCT
email, authorid, userlevel, right_publish
FROM
$serendipity[dbPrefix]authors
WHERE
username = '" . serendipity_db_escape_string($username) . "'
AND password = '" . serendipity_db_escape_string($password) . "'";
$row = serendipity_db_query($query, true, 'assoc');
if (is_array($row)) {
$_SESSION['serendipityUser'] = $serendipity['serendipityUser'] = $username;
$_SESSION['serendipityPassword'] = $serendipity['serendipityPassword'] = $password;
$_SESSION['serendipityEmail'] = $serendipity['serendipityEmail'] = $row['email'];
$_SESSION['serendipityAuthorid'] = $serendipity['authorid'] = $row['authorid'];
$_SESSION['serendipityUserlevel'] = $serendipity['serendipityUserlevel'] = $row['userlevel'];
$_SESSION['serendipityAuthedUser'] = $serendipity['serendipityAuthedUser'] = true;
$_SESSION['serendipityRightPublish']= $serendipity['serendipityRightPublish'] = $row['right_publish'];
serendipity_load_configuration($serendipity['authorid']);
return true;
} else {
$_SESSION['serendipityAuthedUser'] = false;
@session_destroy();
}
}
return false;
}
function serendipity_track_referrer($entry = 0) {
global $serendipity;
if (isset($_SERVER['HTTP_REFERER'])) {
if (stristr($_SERVER['HTTP_REFERER'], $serendipity['baseURL']) !== false) {
return;
}
if (!isset($serendipity['_blockReferer']) || !is_array($serendipity['_blockReferer'])) {
// Only generate an array once per call
$serendipity['_blockReferer'] = array();
$serendipity['_blockReferer'] = @explode(';', $serendipity['blockReferer']);
}
$url_parts = parse_url($_SERVER['HTTP_REFERER']);
$host_parts = explode('.', $url_parts['host']);
if (!$url_parts['host'] ||
strstr($url_parts['host'], $_SERVER['SERVER_NAME'])) {
return;
}
foreach($serendipity['_blockReferer'] AS $idx => $hostname) {
if (@strstr($url_parts['host'], $hostname)) {
return;
}
}
if (rand(0, 100) < 1) {
serendipity_track_referrer_gc();
}
if(preg_match('/^mysqli?/', $serendipity['dbType'])) {
$interval = 900;
} else {
$interval = "interval '900'";
}
$suppressq = "SELECT count(1)
FROM $serendipity[dbPrefix]suppress
WHERE ip = '" . serendipity_db_escape_string($_SERVER['REMOTE_ADDR']) . "'
AND scheme = '" . serendipity_db_escape_string($url_parts['scheme']) . "'
AND port = '" . serendipity_db_escape_string($url_parts['port']) . "'
AND host = '" . serendipity_db_escape_string($url_parts['host']) . "'
AND path = '" . serendipity_db_escape_string($url_parts['path']) . "'
AND query = '" . serendipity_db_escape_string($url_parts['query']) . "'
AND last > now() - $interval";
$suppressp = "DELETE FROM $serendipity[dbPrefix]suppress
WHERE ip = '" . serendipity_db_escape_string($_SERVER['REMOTE_ADDR']) . "'
AND scheme = '" . serendipity_db_escape_string($url_parts['scheme']) . "'
AND host = '" . serendipity_db_escape_string($url_parts['host']) . "'
AND port = '" . serendipity_db_escape_string($url_parts[...
[truncated message content] |