fixed some more each() calls;

core.utils.php: added new function utils_array_kshift();
code formatting changed slightly
This commit is contained in:
azett 2018-10-23 12:24:43 +02:00
parent 3ca9093f7a
commit 61ec0d9f4d
5 changed files with 2540 additions and 2570 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,223 +1,204 @@
<?php <?php
define('DRAFT_DIR', CONTENT_DIR . 'drafts/');
class draft_indexer extends fs_filelister {
define('DRAFT_DIR', CONTENT_DIR . 'drafts/'); var $_varname = 'cache';
class draft_indexer extends fs_filelister { var $_cachefile = null;
var $_varname = 'cache'; var $_directory = DRAFT_DIR;
var $_cachefile = null;
var $_directory = DRAFT_DIR;
function __construct() {
$this->_cachefile = CACHE_DIR . 'draft_index.php';
return parent::__construct();
}
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 __construct() {
$this->_cachefile = CACHE_DIR . 'draft_index.php';
return parent::__construct();
} }
function &draft_init() { function _checkFile($directory, $file) {
global $draftdb; $f = "$directory/$file";
if (!isset($draftdb)) if (is_dir($f) && ctype_digit($file)) {
$draftdb = new draft_indexer; return 1;
return $draftdb; }
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_getlist() { function &draft_init() {
global $draftdb;
if (!isset($draftdb))
$draftdb = new draft_indexer();
return $draftdb;
}
static $list = array(); function draft_getlist() {
static $list = array();
if (!$list) {
$obj =& draft_init();
$list = $obj->getList();
krsort($list);
}
return $list;
if (!$list) {
$obj = & draft_init();
$list = $obj->getList();
krsort($list);
} }
function draft_parse($id) { return $list;
}
if ($fname=draft_exists($id)) { function draft_parse($id) {
if ($fname = draft_exists($id)) {
$entry = io_load_file($fname); $entry = io_load_file($fname);
$entry = utils_kexplode($entry); $entry = utils_kexplode($entry);
if (!isset($entry['categories'])) if (!isset($entry ['categories']))
$entry['categories'] = array(); $entry ['categories'] = array();
else else
$entry['categories'] = explode(',', $entry['categories']); $entry ['categories'] = explode(',', $entry ['categories']);
return $entry; return $entry;
} }
return array(); return array();
}
function draft_save(&$entry, $id = null, $update_index = false, $update_date = false) {
if (!$id) {
$id = bdb_idfromtime('entry', $entry ['date']);
} }
$ed = entry_dir($id);
$dd = draft_dir($id);
function draft_save(&$entry, $id=null, $update_index = false, $update_date=false) { if (file_exists($ed . EXT)) {
if (!$id) { // move collateral files
$id = bdb_idfromtime('entry', $entry['date']); @rename($ed, $dd);
if ($update_index) {
// delete normal entry
fs_delete($ed . EXT);
// remove from normal flow
$o = & entry_init();
$o->delete($id, null);
} }
}
$ed = entry_dir($id); $new_entry = entry_prepare($entry);
$dd = draft_dir($id); if ($new_entry ['categories'])
$new_entry ['categories'] = implode(',', $entry ['categories']);
else
unset($new_entry ['categories']);
if (file_exists($ed.EXT)) { $string = utils_kimplode($new_entry);
// move collateral files if (!io_write_file($dd . EXT, $string)) {
@rename($ed, $dd); return false;
} else
return $id;
if ($update_index) { return false;
// delete normal entry }
fs_delete($ed.EXT);
// remove from normal flow function draft_dir($id) {
$o =& entry_init(); if (!preg_match('|^entry[0-9]{6}-[0-9]{6}$|', $id))
$o->delete($id, null); return false;
} // $date = date_from_id($id);
// $f = CONTENT_DIR . "{$date['y']}/{$date['m']}/$id";
} return DRAFT_DIR . $id;
// return $f;
$new_entry = entry_prepare($entry); }
if ($new_entry['categories'])
$new_entry['categories']=implode(',', $entry['categories']);
else unset($new_entry['categories']);
$string = utils_kimplode($new_entry);
if (!io_write_file($dd.EXT, $string)) {
return false;
} else return $id;
function draft_exists($id) {
$dir = draft_dir($id);
if (!$dir)
return false; return false;
} $f = $dir . EXT;
if (file_exists($f))
return $f;
function draft_dir($id) { return false;
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_delete($id) {
$dir = draft_dir($id);
} $f = $dir . EXT;
if (!file_exists($f))
function draft_exists($id) {
$dir = draft_dir($id);
if (!$dir)
return false;
$f = $dir .EXT;
if (file_exists($f))
return $f;
return false; return false;
}
function draft_delete($id) { // $draftdb =& draft_init();
$dir = draft_dir($id); // $draftdb->delete($id);
fs_delete_recursive($dir);
$f=$dir.EXT; return fs_delete($f);
if (!file_exists($f)) }
return false;
//$draftdb =& draft_init(); /*
//$draftdb->delete($id); * function draft_from_entry($entryid) {
fs_delete_recursive($dir); * $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);
return fs_delete($f); @rename($dir, $dir2);
} draft_delete($draftid);
}
/* function smarty_block_draftlist($params, $content, &$smarty, &$repeat) {
function draft_from_entry($entryid) { global $fpdb;
$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');
$id = $subject = null;
if ($arr)
list($id, $subject)=each($arr);
if ($id){
$smarty->assign('subject', $subject);
$smarty->assign('id', $id);
}
$repeat = (bool) $id;
if ($list = draft_getlist()) {
$smarty->assign('draft_list', $list);
return $content; 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');
$smarty->register_block('draft_block', 'smarty_block_draftlist'); $id = $subject = null;
$smarty->register_block('draft', 'smarty_block_draft'); if ($arr) {
$firstElement = utils_array_kshift($arr);
$id = array_keys($firstElement) [0];
$subject = $firstElement [$id];
}
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');
?> ?>

File diff suppressed because it is too large Load Diff

View File

@ -1,69 +1,79 @@
<?php <?php
// utils.php // utils.php
// library of misc utilities // 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 subkey sort // function prototype:
// function prototype : // bool utils_pattern_match(string $string, string $pattern)
// 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: // returns true if $pattern matches $string, else returns false (what else?)
// bool utils_pattern_match(string $string, string $pattern) // $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 :) )
// returns true if $pattern matches $string, else returns false (what else?) // code from http://www.php.net/function.glob.php.htm#54519
// $pattern is a string containing standard shell-style jokers: * and ? // by x_terminat_or_3 at yahoo dot country:fr
// regex are powerful but somtimes, too complicated :) // thank you, man ;)
// usage: * matches a variable number of chars // as usual, slightly modified to fit my tastes :)
// 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')) { if (!function_exists('fnmatch')) {
function fnmatch($pattern, $string) {
function fnmatch($pattern, $string) {
if ($pattern == null) if ($pattern == null)
return false; return false;
//basically prepare a regular expression // basically prepare a regular expression
$out=null; $out = null;
$chunks=explode(';',$pattern); $chunks = explode(';', $pattern);
foreach($chunks as $pattern) foreach ($chunks as $pattern) {
{ $escape = array(
$escape=array('$','^','.','{','}','(',')','[',']','|'); '$',
while(strpos($pattern,'**')!==false) '^',
$pattern=str_replace('**','*',$pattern); '.',
'{',
'}',
'(',
')',
'[',
']',
'|'
);
while (strpos($pattern, '**') !== false)
$pattern = str_replace('**', '*', $pattern);
foreach($escape as $probe) foreach ($escape as $probe)
$pattern=str_replace($probe,"\\$probe",$pattern); $pattern = str_replace($probe, "\\$probe", $pattern);
$pattern=str_replace('?*','*', str_replace('*?','*', $pattern = str_replace('?*', '*', str_replace('*?', '*', str_replace('*', ".*", str_replace('?', '.{1,1}', $pattern))));
str_replace('*',".*", $out [] = $pattern;
str_replace('?','.{1,1}',$pattern))));
$out[]=$pattern;
} }
/* // NoWhereMan note: why splitting this in two? :) /*
if(count($out)==1) return(eregi("^$out[0]$",$string)); else*/ * // NoWhereMan note: why splitting this in two? :)
foreach($out as $tester) { * if(count($out)==1) return(eregi("^$out[0]$",$string)); else
if (preg_match("/^$tester$/i",$string)) */
foreach ($out as $tester) {
if (preg_match("/^$tester$/i", $string))
return true; return true;
} }
@ -71,388 +81,362 @@ if (!function_exists('fnmatch')) {
} }
} }
// function prototype:
// array utils_kexplode(string $string, string $delim='|')
// function prototype: // explodes a string into an array by the given delimiter;
// array utils_kexplode(string $string, string $delim='|') // 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);
// explodes a string into an array by the given delimiter; $k = strtolower(strtok($string, $delim));
// delimiter defaults to pipe ('|'). $arr [$k] = strtok($delim);
// the string must be formatted as in: while (($k = strtok($delim)) !== false) {
// key1|value1|key2|value2 , etc. if ($keyupper && !preg_match('/[A-Z-_]/', $k)) {
// the array will look like /*
// $arr['key1'] = 'value1'; $arr['key2'] = 'value2'; etc. * trigger_error("Failed parsing <pre>$string</pre>
* keys were supposed to be UPPERCASE but <strong>\"$k\"</strong> was found; file may be corrupted
function utils_kexplode($string, $delim='|', $keyupper=true) { * or in an expected format. <br />
$arr = array(); * Some SimplePHPBlog files may raise this error: set DUMB_MODE_ENABLED
$string = trim($string); * to true in your defaults.php to force parsing of the offending keys.",
* E_USER_WARNING);
$k = strtolower(strtok($string, $delim)); */
$arr[$k] = strtok($delim); continue;
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[strtolower($k)] = strtok($delim);
} }
return $arr; $arr [strtolower($k)] = strtok($delim);
} }
return $arr;
}
/* /*
function utils_newkexplode($string, $delim='|') { * 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;
*
* }
*/
$arr = array(); // function prototype:
// array utils_kimplode(string $string, string $delim='|')
$lastoffset = $offset = 0; // explodes a string into an array by the given delimiter;
$len = strlen($string); // delimiter defaults to pipe ('|').
// the string must be formatted as in:
while ($lastoffset<$len) { // key1|value1|key2|value2 , etc.
$offset = strpos($string, $delim, $lastoffset); // the array will look like
$key = substr($string, $lastoffset, $offset-$lastoffset); // $arr['key1'] = 'value1'; $arr['key2'] = 'value2'; etc.
//echo 'parsing key: ', $key, $offset, chr(10); function utils_kimplode($arr, $delim = '|') {
$string = "";
$lastoffset = $offset + 1; foreach ($arr as $k => $val) {
if ($val)
if (!ctype_upper($key)) $string .= strtoupper($k) . $delim . ($val) . $delim;
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 .= strtoupper($k) . $delim . ($val) . $delim;
}
return $string;
} }
return $string;
}
/** /**
* @todo send mail to admin *
*/ * @todo send mail to admin
*/
function &utils_explode_recursive($array, &$string, $rdelim, $ldelim = '', $outerldelim = '', $outerrdelim = '') {
$string .= $outerldelim;
while ($val = array_shift($array)) {
function &utils_explode_recursive($array, &$string, $rdelim, $ldelim='', $outerldelim='', $outerrdelim='') { $string .= $rdelim;
if (is_array($val)) {
$string .= $outerldelim; $string .= utils_explode_recursive($val, $string, $rdelim, $ldelim, $outerldelim, $outerrdelim);
while ($val = array_shift($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 { } else {
return $str; $string .= $val;
}
}
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;
} }
$string .= $ldelim;
} }
// code from php.net ;) $string .= $outerrdelim;
// defaults to index.php ;) }
function utils_redirect($location="", $absolute_path=false, $red_type=null) {
if (!$absolute_path) function utils_validateinput($str) {
$location = BLOG_BASEURL . $location; 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;
}
if ( function_exists('wp_redirect') ) { function utils_cut_string($str, $maxc) {
wp_redirect($location); $car = strlen($str);
} else { if ($car > $maxc) {
header("Location: $location"); return substr($str, 0, $maxc) . "...";
} } else {
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; return $str;
} }
}
// custom array_merge: function utils_status_header($status) {
// pads the second array to match the length of the first switch ($status) {
// this can be improved, anyway for now I'd just case 301:
// do a quick & dirty solution :) header("HTTP/1.1 301 Moved Permanently");
function utils_array_merge($arr1, $arr2) { break;
case 403:
header("HTTP/1.1 403 Forbidden");
break;
case 404:
header("HTTP/1.1 404 Not Found");
break;
}
}
$len=count($arr1[0]); // 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;
foreach($arr2 as $k=>$v) if (function_exists('wp_redirect')) {
$arr2[$k]=array_pad((Array) $v, $len, null); wp_redirect($location);
} else {
return array_merge($arr1, $arr2); header("Location: $location");
} }
exit();
}
/* /*
* Simple function to replicate PHP 5 behaviour * utils_geturlstring()
*/ *
function utils_microtime() * @return string complete url string as displayed in the browser
{ *
list($usec, $sec) = explode(" ", microtime()); */
return ((float)$usec + (float)$sec); 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";
} }
function utils_countdashes($string, &$rest) { return mail($fp_config ['general'] ['email'], $subject, $message, $headers);
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);
}
/* /*
* props: http://crisp.tweakblogs.net/blog/2031 * props: http://crisp.tweakblogs.net/blog/2031
*/ */
function utils_validateIPv4($IP) { function utils_validateIPv4($IP) {
return $IP == long2ip(ip2long($IP)); return $IP == long2ip(ip2long($IP));
}
function utils_validateIPv6($IP) {
// fast exit for localhost
if (strlen($IP) < 3)
return $IP == '::';
// Check if part is in IPv4 format
if (strpos($IP, '.')) {
$lastcolon = strrpos($IP, ':');
if (!($lastcolon && validateIPv4(substr($IP, $lastcolon + 1))))
return false;
// replace IPv4 part with dummy
$IP = substr($IP, 0, $lastcolon) . ':0:0';
} }
function utils_validateIPv6($IP) { // check uncompressed
// fast exit for localhost if (strpos($IP, '::') === false) {
if (strlen($IP) < 3) return preg_match('/^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}$/i', $IP);
return $IP == '::';
// Check if part is in IPv4 format
if (strpos($IP, '.'))
{
$lastcolon = strrpos($IP, ':');
if (!($lastcolon && validateIPv4(substr($IP, $lastcolon + 1))))
return false;
// replace IPv4 part with dummy
$IP = substr($IP, 0, $lastcolon) . ':0:0';
}
// check uncompressed
if (strpos($IP, '::') === false)
{
return preg_match('/^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}$/i', $IP);
}
// check colon-count for compressed format
if (substr_count($IP, ':') < 8)
{
return preg_match('/^(?::|(?:[a-f0-9]{1,4}:)+):(?:(?:[a-f0-9]{1,4}:)*[a-f0-9]{1,4})?$/i', $IP);
}
return false;
} }
// get client IP // check colon-count for compressed format
function utils_ipget() { if (substr_count($IP, ':') < 8) {
return preg_match('/^(?::|(?:[a-f0-9]{1,4}:)+):(?:(?:[a-f0-9]{1,4}:)*[a-f0-9]{1,4})?$/i', $IP);
$ip = '';
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" );
}
if (utils_validateIPv4($ip) || utils_validateIPv6($ip)) {
return $ip;
} else {
return '';
}
} }
function utils_nocache_headers() { return false;
@ 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'); // get client IP
@ header('Pragma: no-cache'); function utils_ipget() {
$ip = '';
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");
} }
if (utils_validateIPv4($ip) || utils_validateIPv6($ip)) {
return $ip;
} else {
return '';
}
}
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');
}
// from http://nadeausoftware.com/articles/2007/06/php_tip_how_get_web_page_using_curl // from http://nadeausoftware.com/articles/2007/06/php_tip_how_get_web_page_using_curl
// code under OSI BSD // code under OSI BSD
/** /**
* Get a web file (HTML, XHTML, XML, image, etc.) from a URL. Return an * Get a web file (HTML, XHTML, XML, image, etc.) from a URL.
* Return an
* array containing the HTTP server response header fields and content. * array containing the HTTP server response header fields and content.
*/ */
function utils_geturl($url) { function utils_geturl($url) {
/* /*
if (ini_get('allow_url_fopen')) { * if (ini_get('allow_url_fopen')) {
return array('content' => io_load_file($url)); * return array('content' => io_load_file($url));
} * }
*/ */
if (!function_exists('curl_init')) { if (!function_exists('curl_init')) {
trigger_error('curl extension is not installed'); trigger_error('curl extension is not installed');
return array(); return array();
} }
$options = array( $options = array(
CURLOPT_RETURNTRANSFER => true, // return web page CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => false, // don't follow redirects CURLOPT_FOLLOWLOCATION => false, // don't follow redirects
CURLOPT_ENCODING => "", // handle all encodings CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
); );
$ch = curl_init( $url ); $ch = curl_init($url);
curl_setopt_array( $ch, $options ); curl_setopt_array($ch, $options);
$content = curl_exec( $ch ); $content = curl_exec($ch);
$err = curl_errno( $ch ); $err = curl_errno($ch);
$errmsg = curl_error( $ch ); $errmsg = curl_error($ch);
$header = curl_getinfo( $ch ); $header = curl_getinfo($ch);
curl_close( $ch ); curl_close($ch);
$header['errno'] = $err; $header ['errno'] = $err;
$header['errmsg'] = $errmsg; $header ['errmsg'] = $errmsg;
$header['content'] = $content; $header ['content'] = $content;
return $header; return $header;
} }
function utils_checksmarty() {
if (!file_exists(SMARTY_DIR . 'Smarty.class.php')) {
function utils_checksmarty() {
if (!file_exists(SMARTY_DIR . 'Smarty.class.php')) {
$err = <<<ERR $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 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/ 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; ERR;
trigger_error($err, E_USER_ERROR); trigger_error($err, E_USER_ERROR);
}
} }
}
function fplog($str) {
if (!defined('DEBUG_MODE'))
echo "\n[DEBUG] $str \n";
}
function fplog($str) { /**
if(!defined('DEBUG_MODE')) * Shift an element with its key off the beginning of array.
echo "\n[DEBUG] $str \n"; * Just like array_shift(), but for an associative array.
} *
* @param array $arr
* The input array
* @return unknown the shifted value, or NULL if array is empty or is not an array
*/
function utils_array_kshift(&$arr) {
list ($k) = array_keys($arr);
$r = array(
$k => $arr [$k]
);
unset($arr [$k]);
return $r;
}
?> ?>

View File

@ -1,95 +1,100 @@
<?php <?php
/* /*
Plugin Name: Calendar * Plugin Name: Calendar
Version: 1.1 * Version: 1.1
Plugin URI: http://flatpress.sf.net * Plugin URI: http://flatpress.sf.net
Type: Block * Type: Block
Description: Adds a Calendar block level element * Description: Adds a Calendar block level element
Author: NoWhereMan * Author: NoWhereMan
Author URI: http://flatpress.sf.net * Author URI: http://flatpress.sf.net
*/ */
// PHP Calendar (version 2.3), written by Keith Devens
// http://keithdevens.com/software/php_calendar
// see example at http://keithdevens.com/weblog
// License: http://keithdevens.com/software/license
function generate_calendar($year, $month, $days = array(), $day_name_length = 3, $month_href = NULL, $first_day = 0, $pn = array()) {
$first_of_month = gmmktime(0, 0, 0, $month, 1, $year);
// remember that mktime will automatically correct if invalid dates are entered
// for instance, mktime(0,0,0,12,32,1997) will be the date for Jan 1, 1998
// this provides a built in "rounding" feature to generate_calendar()
# PHP Calendar (version 2.3), written by Keith Devens $day_names = array(); // generate all the day names according to the current locale
# http://keithdevens.com/software/php_calendar for($n = 0, $t = (3 + $first_day) * 86400; $n < 7; $n++, $t += 86400) // January 4, 1970 was a Sunday
# see example at http://keithdevens.com/weblog $day_names [$n] = ucfirst(date_strformat('%A', $t)); // %A means full textual day name
# License: http://keithdevens.com/software/license
function generate_calendar($year, $month, $days = array(), $day_name_length = 3, $month_href = NULL, $first_day = 0, $pn = array()){ list ($month, $year, $month_name, $weekday) = explode(',', date_strformat('%m,%Y,%B,%w', $first_of_month));
$first_of_month = gmmktime(0,0,0,$month,1,$year); $weekday = ($weekday + 7 - $first_day) % 7; // adjust for $first_day
#remember that mktime will automatically correct if invalid dates are entered $title = htmlentities(ucfirst($month_name)) . '&nbsp;' . $year; // note that some locales don't capitalize month and day names
# for instance, mktime(0,0,0,12,32,1997) will be the date for Jan 1, 1998
# this provides a built in "rounding" feature to generate_calendar()
$day_names = array(); #generate all the day names according to the current locale // Begin calendar. Uses a real <caption>. See http://diveintomark.org/archives/2002/07/03
for($n=0,$t=(3+$first_day)*86400; $n<7; $n++,$t+=86400) #January 4, 1970 was a Sunday
$day_names[$n] = ucfirst(date_strformat('%A',$t)); #%A means full textual day name
list($month, $year, $month_name, $weekday) = explode(',',date_strformat('%m,%Y,%B,%w',$first_of_month));
$weekday = ($weekday + 7 - $first_day) % 7; #adjust for $first_day
$title = htmlentities(ucfirst($month_name)).'&nbsp;'.$year; #note that some locales don't capitalize month and day names
#Begin calendar. Uses a real <caption>. See http://diveintomark.org/archives/2002/07/03
// PHP7 compatibility: Since $pn is never passed, we do not need to create "previous" and "next" elements. // PHP7 compatibility: Since $pn is never passed, we do not need to create "previous" and "next" elements.
// Commented out to prevent deprecated each() function from being executed.
$p = ''; $p = '';
$n = ''; $n = '';
/* // Commented out to prevent deprecated each() function from being executed.
@list($p, $pl) = each($pn); @list($n, $nl) = each($pn); #previous and next links, if applicable // @list($p, $pl) = each($pn); @list($n, $nl) = each($pn); #previous and next links, if applicable
if($p) $p = '<span class="calendar-prev">'.($pl ? '<a href="'.($pl).'">'.$p.'</a>' : $p).'</span>&nbsp;'; // if($p) $p = '<span class="calendar-prev">'.($pl ? '<a href="'.($pl).'">'.$p.'</a>' : $p).'</span>&nbsp;';
if($n) $n = '&nbsp;<span class="calendar-next">'.($nl ? '<a href="'.($nl).'">'.$n.'</a>' : $n).'</span>'; // if($n) $n = '&nbsp;<span class="calendar-next">'.($nl ? '<a href="'.($nl).'">'.$n.'</a>' : $n).'</span>';
*/
$calendar = '<table class="calendar">'."\n".
'<caption class="calendar-month">'.$p.($month_href ? '<a href="'.($month_href).'">'.$title.'</a>' : $title).$n."</caption>\n<tr>";
if($day_name_length){ #if the day names should be shown ($day_name_length > 0) $calendar = '<table class="calendar">' . "\n" . '<caption class="calendar-month">' . $p . ($month_href ? '<a href="' . ($month_href) . '">' . $title . '</a>' : $title) . $n . "</caption>\n<tr>";
#if day_name_length is >3, the full name of the day will be printed
foreach($day_names as $d) if ($day_name_length) { // if the day names should be shown ($day_name_length > 0)
$calendar .= '<th abbr="'.htmlentities($d).'">'.htmlentities($day_name_length < 4 ? substr($d,0,$day_name_length) : $d).'</th>'; // if day_name_length is >3, the full name of the day will be printed
foreach ($day_names as $d)
$calendar .= '<th abbr="' . htmlentities($d) . '">' . htmlentities($day_name_length < 4 ? substr($d, 0, $day_name_length) : $d) . '</th>';
$calendar .= "</tr>\n<tr>"; $calendar .= "</tr>\n<tr>";
} }
if($weekday > 0) $calendar .= '<td colspan="'.$weekday.'">&nbsp;</td>'; #initial 'empty' days if ($weekday > 0)
for($day=1,$days_in_month=gmdate('t',$first_of_month); $day<=$days_in_month; $day++,$weekday++){ $calendar .= '<td colspan="' . $weekday . '">&nbsp;</td>'; // initial 'empty' days
if($weekday == 7){ for($day = 1, $days_in_month = gmdate('t', $first_of_month); $day <= $days_in_month; $day++, $weekday++) {
$weekday = 0; #start a new week if ($weekday == 7) {
$weekday = 0; // start a new week
$calendar .= "</tr>\n<tr>"; $calendar .= "</tr>\n<tr>";
} }
if(isset($days[$day]) and is_array($days[$day])){ if (isset($days [$day]) and is_array($days [$day])) {
@list($link, $classes, $content) = $days[$day]; @list ($link, $classes, $content) = $days [$day];
if(is_null($content)) $content = $day; if (is_null($content))
$calendar .= '<td'.($classes ? ' class="'.htmlspecialchars($classes).'">' : '>'). $content = $day;
($link ? '<a class="calendar-day" href="'.($link).'">'.$content.'</a>' : $content).'</td>'; $calendar .= '<td' . ($classes ? ' class="' . htmlspecialchars($classes) . '">' : '>') . ($link ? '<a class="calendar-day" href="' . ($link) . '">' . $content . '</a>' : $content) . '</td>';
} } else
else $calendar .= "<td>$day</td>"; $calendar .= "<td>$day</td>";
} }
if($weekday != 7) $calendar .= '<td colspan="'.(7-$weekday).'">&nbsp;</td>'; #remaining "empty" days if ($weekday != 7)
$calendar .= '<td colspan="' . (7 - $weekday) . '">&nbsp;</td>'; // remaining "empty" days
return $calendar."</tr>\n</table>\n"; return $calendar . "</tr>\n</table>\n";
} }
function plugin_calendar_widget() { function plugin_calendar_widget() {
global $fp_params; global $fp_params;
$y = isset($fp_params['y'])? $fp_params['y'] : date('y'); $y = isset($fp_params ['y']) ? $fp_params ['y'] : date('y');
$m = isset($fp_params['m'])? $fp_params['m'] : date('m'); $m = isset($fp_params ['m']) ? $fp_params ['m'] : date('m');
global $fpdb; global $fpdb;
$q = new FPDB_Query(array('fullparse'=>false,'y'=>$y,'m'=>$m, 'count' => -1), null); $q = new FPDB_Query(array(
'fullparse' => false,
'y' => $y,
'm' => $m,
'count' => -1
), null);
$days = array(); $days = array();
while ($q->hasmore($queryId)) { while ($q->hasmore($queryId)) {
list($id, $entry) = $q->getEntry($queryId); list ($id, $entry) = $q->getEntry($queryId);
$date = date_from_id($id); $date = date_from_id($id);
$d = (int)$date['d']; $d = (int) $date ['d'];
$days[$d] = array(get_day_link($y, $m, str_pad($d, 2, '0', STR_PAD_LEFT)), 'linked-day');
$days [$d] = array(
get_day_link($y, $m, str_pad($d, 2, '0', STR_PAD_LEFT)),
'linked-day'
);
$count++; $count++;
} }
@ -99,8 +104,8 @@ function plugin_calendar_widget() {
$lang = lang_load('plugin:calendar'); $lang = lang_load('plugin:calendar');
$widget = array(); $widget = array();
$widget['subject'] = $lang['plugin']['calendar']['subject']; $widget ['subject'] = $lang ['plugin'] ['calendar'] ['subject'];
$widget['content'] = '<ul id="widget_calendar"><li>'. generate_calendar($y,$m, $days).'</li></ul>'; $widget ['content'] = '<ul id="widget_calendar"><li>' . generate_calendar($y, $m, $days) . '</li></ul>';
return $widget; return $widget;
} }