Location: PHPKode > projects > Bloggie Lite > includes/functions.php
<?

// Copyright (C) Bloggie Lite Written by : Sean
// http://www.mywebland.com , http://mybloggie.mywebland.com

// You are requested to retain this copyright notice in order to use
// this software.

//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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

if ( !defined('IN_BLOGGIE') )
{
    die("You are not allowed to access this page directly !");
}

function pref_data() {
   global $pref_data, $db;

   $sql = "SELECT * FROM ". PREF_TBL;
   if (!($result = $db->sql_query($sql))) {
      $sql_error = $db->sql_error();         //214
      error($lang['Error'], 'SQL Query Error : '.$sql_error['message'].' !');
   }
      $pref_data = array();
   while ( $row = $db->sql_fetchrow($result) ) {
     $pref_data[$row['option_name']] = $row['setting'];
   }
   $db->sql_freeresult($result);
   return $pref_data;
}


function read_url() {
  global $db, $lang, $sef_method, $pref_data;

     if  (empty($_GET))  {
         $site_url =  $pref_data['bloggie_path'];
         $pathinfo = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : "";
         $pathinfo_array = explode('?', $pathinfo);
         $pathinfo = $pathinfo_array[0];

         $request_uri = $_SERVER['REQUEST_URI'];
         $request_uri_array = explode('?', $request_uri);
         $request_uri = $request_uri_array[0];
         $home_path = parse_url($site_url);
         $home_path = $home_path['path']."/index.php";
         $home_path = trim($home_path, '/');

         $request_uri = str_replace($pathinfo, '', $request_uri);
         $request_uri = trim($request_uri, '/');
         $request_uri = preg_replace("|^$home_path|", '', $request_uri);
         $request_uri = trim($request_uri, '/');

         $pathinfo = trim($pathinfo, '/');
         $pathinfo = preg_replace("|^$home_path|", '', $pathinfo);
         $pathinfo = trim($pathinfo, '/');
     if ( ! empty($pathinfo)) {
        $path = $pathinfo;
     } else {
        $path = $request_uri;
     }
     $path_parts = explode('/', trim($path));
//print_r($path_parts);
     return $path_parts;
     } else {
        $sef_method = "xsef";
        $path_parts = "";
     return $path_parts;
     }
}

// array combine for non PHP 5
if (! function_exists('array_combine')) {
  function array_combine($keys, $values) {
   foreach($keys as $key) $out[$key] = array_shift($values);
   return $out;
  }
}

function get_topic() {
   global $db, $link_vars;
//   $variable_tags = array("mm", "dd", "yyyy", "title", "post_id", "cat_id", "cat_desc", "mth", "yr");
    if( is_array($_GET) && !empty($_GET))  {
        while( list($k, $v) = each($_GET) ) {
            if( is_array($_GET[$k]) ) {
                while( list($k2, $v2) = each($_GET[$k]) ) {
                     $$k[$k2]       = $_GET[$k][$k2];
                }
                @reset($_GET[$k]);
            } else {
                $$k = $_GET[$k];
// echo "$k =".$$k;
            }
        }
        @reset($_GET);
      $sef_method = "xsef";
    } else {

      while (list($key, $val) = each($link_vars)) {
           $$key = $val;
// echo  $$key;
        }
    }

   if ( isset($dd) && isset($mm) && isset($yyyy)) {
      $yyyy = ( numerical_check($yyyy) ) ? intval($yyyy) : "";
      $mm = ( numerical_check($mm) ) ? intval($mm) : "";
      $dd = ( numerical_check($dd) ) ? intval($dd) : "";
      $date_criteria = "DATE_FORMAT(FROM_UNIXTIME(".POST_TBL.".timestamp) , '%e') = ".$dd."  AND
                        DATE_FORMAT(FROM_UNIXTIME(".POST_TBL.".timestamp) , '%Y') = ".$yyyy." AND
                        DATE_FORMAT(FROM_UNIXTIME(".POST_TBL.".timestamp) , '%c') = ".$mm;
   } else $date_criteria ="";
   if ( isset($title) ) {
      $title = sanitize_url_subject($title);
      if ( isset($dd) && isset($mm) && isset($yyyy)) $and = " AND "; else  $and = "";
      $title_criteria = $and.POST_TBL.".perm_subj='".$title."'" ;
   } else $title_criteria ="";

   if ( isset($post_id) ) {
      $post_id = ( numerical_check($post_id) ) ? intval($post_id) : "";
      if ( (isset($dd) && isset($mm) && isset($yyyy)) || isset($title)) $and = " AND "; else $and = "";
      $post_id_criteria = $and.POST_TBL.".post_id='".$post_id."'" ;
   } else { $post_id_criteria = ""; }

   $criteria =  $date_criteria." ".$title_criteria." ".$post_id_criteria;
//echo $criteria;

  $sql = "SELECT ".CAT_TBL.".cat_desc, ".CAT_TBL.".cat_perma, ".POST_TBL.".cat_id, ".CAT_TBL.".cat_id, ".POST_TBL.".post_id,
  ".POST_TBL.".comments_count, ".POST_TBL.".perm_subj, ".POST_TBL.".subject,".POST_TBL.".message, ".USER_TBL.".user,
  ".POST_TBL.".timestamp, ".USER_TBL.".id, ".POST_TBL.".user_id FROM ".POST_TBL.", ".USER_TBL.", ".CAT_TBL."
  WHERE ".POST_TBL.".user_id=".USER_TBL.".id  AND  ".CAT_TBL.".cat_id=".POST_TBL.".cat_id AND ".$criteria."
  Order by ".POST_TBL.".post_id DESC ";

  $result = $db->sql_query($sql);
  $row = $db->sql_fetchrow($result);
   unset($result);
 return  $row;

}

function get_permalink_info($path_parts) {
    global $link_format;
    $mode_tags = array("read", "category", "archives", "page", "search", "author");
//    $variable_tags = array("mm", "dd", "yyyy", "title", "post_id", "cat_id", "cat_desc", "mth", "yr");
    if  ( !empty($path_parts)) {
    $mode = $path_parts[0];
    //$link_format_parts =
//    $link_format = str_replace ("'", "\'", $link_format);
//    $interpreted_link = strtolower(preg_replace('#\{([a-z0-9\-_]*?)\}#is', "$\\1", $link_format));
//     print_r($path_parts) ;
     $link_vars = explode( '/',strtolower(preg_replace('#\{([a-z0-9\-_]*?)\}#is', "\\1", $link_format)));
//print_r($link_vars);
     if ($link_vars[0] == "index.php") {
        $link_vars  = array_slice($link_vars,1);
     }
     if (count($link_vars) == count($path_parts) && $path_parts[0] != "") {
        $link_vars =  array_combine( $link_vars , $path_parts);
/**        while (list($key, $val) = each($link_vars)) {
           //$$key = $val;
            // $vars["$key"] = $val;
        }
        foreach ( $variable_tags as $tag ) {
          if (isset($$tag)) { $mode = $tag ;
          break;
        }
        } **/
      }
    }  else {

       $link_vars = "";
    }
return $link_vars  ;
}

function get_post_setting($id) {
  global $post_setting, $db;

  $sql = "SELECT subject, allow_comments, allow_ping, allow_tb  FROM ".POST_TBL." where post_id ='".$id."'" ;
  if (!($result = $db->sql_query($sql)))
   {
    $sql_error = $db->sql_error();         //214
    error($lang['Error'], 'SQL Query Error : '.$sql_error['message'].' !');
   }
  $post_setting = array();
  $row = $db->sql_fetchrow($result);
  $post_setting['allow_comments'] = $row['allow_comments'];
  $post_setting['allow_ping'] = $row['allow_ping'];
  $post_setting['allow_tb'] = $row['allow_tb'];
  $post_setting['subject'] = $row['subject'];
  $db->sql_freeresult($result);
  return $post_setting;
}

// GMT Date function
function gmtdate($format, $gmepoch, $timezone)
{
    return ( @gmdate($format, $gmepoch + (3600 * $timezone)));
}

function current_timestamp($timezone) {
    $timestamp = mktime(gmtdate('H', time(),$timezone ),
                        gmtdate('i', time(), $timezone ),
                        gmtdate('s', time(), $timezone ),
                        gmtdate('n', time(), $timezone ),
                        gmtdate('d', time(), $timezone ),
                        gmtdate('Y', time(), $timezone ));

    return ($timestamp);
}

function time_YYYYMMDD($timestamp) {

    global $time_format;

    $YYYYMMDD = array();
    $YYYYMMDD['YYYY'] = date('Y', $timestamp);
    $YYYYMMDD['MM']   = date('m', $timestamp);
    $YYYYMMDD['DD']   = date('d', $timestamp);
    return ($YYYYMMDD);
}



function gen_subject_url($id) {
    global $db,  $time_format;

       //$file=str_replace(".php","",$file);

        if(!empty($keyword)) {
            $keyword= str_replace(" ","-",trim(ereg_replace("[^[:space:]a-zA-Z0-9]", "", $keyword)));
            $keyword =strtolower($keyword);
        } else {
            $keyword="";
        }

       if ($method == "date") {
           time_YYYYMMDD($sef_date);
           $sef_format = $time_YYYYMMDD['YYYY']."/".$time_YYYYMMDD['MM']."/".$time_YYYYMMDD['DD'];
           return "{$file}/{$mode}/{$sef_format}/{$keyword}/";
       }
           elseif ($method == "id"){
           $sef_format = $sef_id ;
           return "{$file}/{$mode}/{$sef_format}/{$keyword}/";
       } elseif (($method == "category")) {
           return "{$file}/{$method}/{$keyword}/";
       }
         elseif (($method == "archives")) {
          time_YYYYMMDD($sef_date);
          $sef_format = $time_format['YYYY']."/".$time_format['MM'];
          $keyword = $sef_format ;
          return "{$file}/{$method}/{$keyword}/";
       }

       else { return 0; }

}
/**
function SEF_URL($file="",$mode="",$sef_method="",$keyword="",$sef_id="",$sef_date="" ) {
    global $db, $time_format;
    if($sef_method != "xsef") {
       if ($sef_method == "date") {
           time_format($sef_date);
           $sef_format = $time_format['YYYY']."/".$time_format['MM']."/".$time_format['DD'];
           return "{$file}/{$mode}/{$sef_format}/{$keyword}/";
       }
           elseif ($sef_method == "id"){
           $sef_format = $sef_id ;
           return "{$file}/{$mode}/{$sef_format}/{$keyword}/";
       } elseif (($sef_method == "category")) {
           return "{$file}/{$sef_method}/{$keyword}/";
       }
         elseif (($sef_method == "archives")) {
          time_format($sef_date);
          $sef_format = $time_format['YYYY']."/".$time_format['MM'];
          $keyword = $sef_format ;
          return "{$file}/{$sef_method}/{$keyword}/";
       }
    } elseif($sef_method == "xsef") {
       if ($mode == "read") {
       return "{$file}?mode={$mode}&amp;post_id={$sef_id}"; }
       if ($mode == "category") {
       return "{$file}?mode={$mode}&amp;cat_id={$sef_id}"; }
       if ($mode == "archives") {
       return "{$file}?mode={$mode}&amp;{$sef_id}"; }
    }
     else { return ""; }
}
**/
//ereg("[^-’A-Za-z0-9 \t]", "don’t forget about secu-rity");

function numerical_check($input) {
  $input = intval($input) ;
  return !preg_match ("/[^0-9]/", $input);
}
function alphabet_check($input) {
  return !preg_match ("/[^A-z]/", $input);
}

function sanitize_username($username)
{
    $username = strip_tags($username);
    $username = substr(htmlspecialchars(str_replace("\'", "'", trim($username))), 0, 25);
    $username = r_trim($username, "\\");
    $username = str_replace("'", "\'", $username);
    $username = str_replace("%'", " ", $username);
    $username = preg_replace('/&.+?;/', '', $username);
    return $username;
}

function sanitize_url_subject($title) {
    $title = strip_tags($title);
    $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
    $title = str_replace('%', '', $title);
    $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
/**
    $title = remove_accents($title);
    if (seems_utf8($title)) {
        if (function_exists('mb_strtolower')) {
            $title = mb_strtolower($title, 'UTF-8');
        }
        $title = utf8_uri_encode($title);
    }
 **/
    $title = strtolower($title);
    $title = preg_replace('/&.+?;/', '', $title); // kill entities
    $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
    $title = preg_replace('/\s+/', '-', $title);
    $title = preg_replace('|-+|', '-', $title);
    $title = trim($title, '-');

    return $title;
}

function l_trim($str, $charlist = false)
{
    if ($charlist === false)
    {
        return ltrim($str);
    }
    
    $php_version = explode('.', PHP_VERSION);

    if ((int) $php_version[0] < 4 || ((int) $php_version[0] == 4 && (int) $php_version[1] < 1))
    {
        while ($str{0} == $charlist)
        {
            $str = substr($str, 1);
        }
    }
    else
    {
        $str = ltrim($str, $charlist);
    }

    return $str;
}

function r_trim($str, $charlist = false)
{
    if ($charlist === false)
    {
        return rtrim($str);
    }
     $php_version = explode('.', PHP_VERSION);

    // php version < 4.1.0
    if ((int) $php_version[0] < 4 || ((int) $php_version[0] == 4 && (int) $php_version[1] < 1))
    {
        while ($str{strlen($str)-1} == $charlist)
        {
            $str = substr($str, 0, strlen($str)-1);
        }
    }
    else
    {
        $str = rtrim($str, $charlist);
    }
    return $str;
}


// Plugin Module
function add_func_list($desc, $function_to_add, $no_of_args = 1, $order = 10) {
   global $func_list;

   if ( isset($func_list[$desc][$order]) ) {
      foreach($func_list[$desc][$order] as $function) {
        if ( $function == array($function, $no_of_args) ) {
           if ( $function['function'] == $function_to_add ) {
              return true;
           }
        }
      }
   }
   $func_list[$desc][$order][] = array('function'=>$function_to_add, 'no_of_args'=>$no_of_args);
   if ( isset($func_list[$desc]) )
        ksort( $func_list[$desc] );
    return true;
}

function remove_func_list($desc, $function_to_remove, $no_of_args = 1, $order = 10) {
   global $func_list;
    if ( isset($func_list[$desc][$order]) ) {
       foreach($func_list[$desc][$order] as $function) {
            if ( $function['function'] != $function_to_remove ) {
                $new_function_list[] = $function;
            }
        }
        $func_list[$desc][$order] = $new_function_list;
    }
    return true;
}

function execute($desc, $arg = '') {
   global $func_list;

   if ( !isset($func_list[$desc]) ) {
      return;
   }
//  print_r ($func_list);
//ksort($func_list);
    $args = array_slice(func_get_args(), 1);
    foreach ($func_list[$desc] as $order => $functions) {
 //   echo $order;  ksort($functions);
       foreach($functions as $function) {
 //          print_r($function) ; echo "<br />";

          $function_desc = $function['function'];
          $no_of_args = $function['no_of_args'];
          if ( $no_of_args >= 1 ) {
             $args = array_slice($args, 0, $no_of_args);
          } elseif ( $no_of_args == 0 ) {
             $args = NULL;
          }
          $call = call_user_func_array($function_desc, $args);
       }
   }
}
/**
function execute($desc, $arg = '') {
   global $func_list;

   if ( !isset($func_list[$desc]) ) {
      return;
   }

    $extra_args = array_slice(func_get_args(), 2);
//    $args = array_slice(func_get_args(), 1);

     if ( is_array($arg) )
         $args = array_merge($arg, $extra_args);
    else
        $args = array_merge(array($arg), $extra_args);


    foreach ($func_list[$desc] as $order => $functions) {
        if ( !is_null($functions) ) {
            foreach($functions as $function) {
                $function_name = $function['function'];
                $no_of_args = $function['no_of_args'];

                if ( $no_of_args == 1 ) {
                    if ( is_array($arg) )
                        $the_args = $arg;
                    else
                        $the_args = array($arg);
                } elseif ( $no_of_args > 1 ) {
                    $the_args = array_slice($args, 0, $no_of_args);
                } elseif ( $no_of_args == 0 ) {
                    $the_args = NULL;
                } else {
                    $the_args = $args;
                }
//                 print_r($the_args);
                $string = call_user_func_array($function_name, $the_args);
            }
        }
    }
}
**/
function sendmail( $from, $to, $subject, $body )  {
   $headers  = "MIME-Version: 1.0\r\n";
   $headers .= "Content-type: text/plain\r\n";
   $headers .= "From: {$from}\r\n";
   $sent = @mail( $to, $subject, $body, $headers );
   if( $sent ) return true;
}

function simpleheader(){
global $pref_data, $lang;
?>
<head>
<title>Bloggie Lite <? echo $pref_data['version'] ?> - Adminstrator Log In</title>
<meta http-equiv="Content-Type" content="text/html; charset=<? echo $pref_data['encoding'] ?>">
<link rel="stylesheet" title="<? echo $pref_data['default_style'] ?>" href="templates/<? echo $pref_data['default_style'] ?>/<? echo $pref_data['default_style'].".css" ?>" type="text/css" />
</head>
<style>
body { background: #ffffff;}
  font-family: Verdana;
  height: 22px;
  border-style: solid;
  border-width: 1px;
  border-color: #aaaaaa;
  background: #f0f0f0;
  border-width: 1px;
  margin: 2px;
  align : center;
}
</style>
<body bgcolor="#FFFFFF" topmargin="5" leftmargin="5" marginheight="5" marginwidth="5" >
<div>
<?
return;
}


function error( $alert, $message ){
global $bloggie_root_path, $bloggie_path, $lang, $template;
      ?>
      <center>
      <div id="error">
      <h2><? echo $alert  ?></h2>
         <div id="errmsg">
           <p><em><b><? echo $message  ?></b></em></p>
         </div>
         <div id="errlink">
           <p><a href="<? echo $bloggie_root_path ?>index.php">Blog's Home</a> | <a href="http://mybloggie.com/doc/"><? echo $lang['Help'] ?></a>  | <a class="std" href="javascript:history.back()"><? echo $lang['Go_Back'] ?></a></p>
          </div>
      </div>
      </center>
   <?
  // $template = new Template('./templates/') ;
   //$template->set_filenames(array(
    //          'footer' => $bloggie_root_path.'footer.tpl' ));
   $template->pparse('simplefooter');
   exit;
}

function message( $alert, $message ){
global $bloggie_root_path, $lang, $site_url;
      ?>
      <center>
      <div id="error">
      <h2><? echo $alert  ?></h2>
         <div id="errmsg">
           <p><em><b><? echo $message  ?></b></em></p>
         </div>
         <div id="errlink">
           <p><a href="<? echo $bloggie_root_path ?>index.php">Blog's Home</a> | <a href="http://mybloggie.com/doc/"><? echo $lang['Help'] ?></a>  | <a class="std" href="javascript:history.back()"><? echo $lang['Go_Back'] ?></a></p>
          </div>
      </div>
      </center>
   <?
  // $template = new Template('./templates/') ;
   //$template->set_filenames(array(
    //          'footer' => $bloggie_root_path.'footer.tpl' ));
   //$template->pparse('footer');
}

function authenticate() {
  global $db;
  if(isset($_COOKIE[USER_COOKIE]) && isset($_COOKIE[PASS_COOKIE])) {
    $use_cookie  = true;
    $user_cookie = $_COOKIE[USER_COOKIE];
    $pass_cookie = $_COOKIE[PASS_COOKIE];
//    echo $user_cookie ;
//    echo $pass_cookie ;
    $sql =  "SELECT user FROM ".USER_TBL." WHERE user='$user_cookie' AND password='$pass_cookie'";
    $result = $db->sql_query($sql);
    if ( $db->sql_numrows($result)== 1  )   {
//     $logged['status'] = 1 ;
//     $logged['user'] = $user_cookie;
       $cookie_data['username']   = $user_cookie;
       $cookie_data['pass']   = $pass_cookie;
     return $cookie_data;
    }
  }
  else {
    return false;
  } // Not logged in
}

function unique_permasubj($perm_subj, $post_id="" ) {
  global $db, $lang;
    //echo $post_id ;
    $sql =  "SELECT post_id, perm_subj FROM ".POST_TBL." WHERE perm_subj like '".$perm_subj."%' AND post_id <> '".$post_id."' ORDER BY perm_subj ASC";
    $result = $db->sql_query($sql);
    if ( $db->sql_numrows($result) > 0  ) {
       if ($post_id =="") {
          $sql ="SHOW TABLE STATUS LIKE '".POST_TBL."'";
          if (!($result1 = $db->sql_query($sql)))
          {
            $sql_error = $db->sql_error();         //214
            error($lang['Error'], 'SQL Query Error : '.$sql_error['message'].' !');
          }
       $row = $db->sql_fetchrow($result1);
       $perm_subj = $perm_subj."-".$row['Auto_increment'];
       $db->sql_freeresult($result1);
       } else { $perm_subj = $perm_subj."-".$post_id;  }
    }
     $db->sql_freeresult($result);
    return $perm_subj;
}

function comments_count($post_id)
{    global $db;

   $sql  = "SELECT comment_id FROM ".COMMENT_TBL."
            WHERE ".COMMENT_TBL.".post_id = ".$post_id." and comment_type!='trackback' and approved='1'";
            if ( !($result = $db->sql_query($sql)) )
            {
              $sql_error = $db->sql_error();
              error ('Error', $sql_error['message']);;
            }
            $comments_count = $db->sql_numrows($result) ;

   return $comments_count;
}



if ( !function_exists('clear_cookie') ) {
   function clear_cookie() {
       setcookie(USER_COOKIE, $_COOKIE[USER_COOKIE], time()-31536000, PATH_COOKIE , DOMAIN_COOKIE);
       setcookie(PASS_COOKIE, $_COOKIE[PASS_COOKIE], time()-31536000, PATH_COOKIE, DOMAIN_COOKIE);
   }
}

function nocache() {
    @ header('Expires: Mon, 22 Jul 2002 11:12:01 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 redirect($url)
{
    global $db;

    if (!empty($db)) { $db->sql_close(); }

    if (strstr(urldecode($url), "\n") || strstr(urldecode($url), "\r"))
    {
        error($lang['Error'], 'Tried to redirect to potentially insecure url.');
    }

    if (strstr($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS'))
        header("Refresh: 0;url=$url");
    else
        header("Location: $url");
}

function metaredirect($url, $sec)
{
    global $db, $template;

    if (!empty($db)) { $db->sql_close(); }
    //$url = preg_replace('#^\/?(.*?)\/?$#', '/\1', trim($url));
//    $template->assign_vars(array(
//            'META' => "<meta http-equiv=\"refresh\" content=\"".$sec.";url='.$url. '\"/>")
//          );
   echo "<meta http-equiv=\"refresh\" content=\"".$sec.";url=".$url."\" />" ;
}

function self_url( $display=0 ) {

if  (isset($_SERVER['PHP_SELF']) && isset($_SERVER['HTTP_HOST'])) {
   $me = $_SERVER['PHP_SELF'];
   $Apathweb = explode("/", $me);
$myFileName = array_pop($Apathweb);
   $pathweb = implode("/", $Apathweb);
   $myUrl = "http://".$_SERVER['HTTP_HOST'].$pathweb;
   }
elseif (isset($_SERVER['PHP_SELF']) && isset($_SERVER['SERVER_NAME'])) {
   $me = $_SERVER['PHP_SELF'];
   $Apathweb = explode("/", $me);
   $pathweb = implode("/", $Apathweb);
   $myUrl = 'http://'.$_SERVER['SERVER_NAME'].$pathweb;
   }
   //echo $pathweb;
   //echo $Apathweb[0];
 if ($display) {
        echo $myUrl;
    } else {
        return $myUrl;
    }
}


function versioncheck($version) {
$error_no  = 0;
$error_msg = $latest_version = '';
$i = 0;
$blog_info['version'] = $version ;
$get_status = false;
$updatemsg = "";
if ($fsock = @fsockopen('www.mywebland.com', 80, $error_no, $error_msg, 10)) {
   @fputs($fsock, "GET /version/bloggielite/latestversion.txt HTTP/1.1\r\n");
   @fputs($fsock, "HOST: www.mywebland.com\r\n");
   @fputs($fsock, "Connection: close\r\n\r\n");

   while (!@feof($fsock))
      {
         if ($get_status) {
            $latest_version .= @fread($fsock, 1024);
         }
         else {
            if (@fgets($fsock, 1024) == "\r\n") {
               $get_status = true;
            }
         }
      }
   @fclose($fsock);


   //echo $latest_version ;
   $installed_version = explode('.', $blog_info['version']);
   $latest_version = explode("\n", $latest_version);
   $i = count($latest_version) ;
   if ($installed_version[0] < $latest_version[0] || $installed_version[1] < $latest_version[1]
      || $installed_version[2] < $latest_version[2])  {
         $updatemsg  = "<font color=\"#FF0000\">Alert ! Bloggie Lite Installed is not the latest version. <br />";
         $updatemsg .= "Installed version : ".$version. ", &nbsp; Latest available update : ".$latest_version[0].".".$latest_version[1].".".$latest_version[2]."<br /></font>";
       if ($i > 3) {
        $updatemsg .= $latest_version[3];
      }
   }
   else {
      $updatemsg = "Installed is the latest version<br />";
      if ($i > 4) {
      $updatemsg .="<span style=\"font-size:9px;\">".$latest_version[4]."</span>";
      }
   }
}
else {
   if ($error_msg) {
      $updatemsg = $error_msg;
   }
   else {
      $updatemsg = 'Socket functions disabled';
   }
}

return $updatemsg;

}


function pagination($urlmode, $page_link, $num_of_post, $post_per_page, $post_no)
{
    global $lang;
    //if ($urlmode != "SEF") = $post_n
    $no_of_pages = ceil($num_of_post/$post_per_page);
    if ( $no_of_pages == 1 ) { return ''; }
    $on_page = floor($post_no / $post_per_page) + 1;
    $pagination = "";
    if ( $no_of_pages > 10 )  {
        $init_page_max = ( $no_of_pages > 3 ) ? 3 : $no_of_pages;
        for($i = 1; $i < $init_page_max + 1; $i++)  {
            if ($urlmode != "SEF") {
               $pagination .= ( $i == $on_page ) ? '<li class="currentpage">'.$i.'</li>' : '<li class="pages"><a href="' . $page_link . "&amp;pno=" . ( ( $i - 1 ) * $post_per_page )  . '">'.$i.'</a></li>';
            }
            else {
               $pagination .= ( $i == $on_page ) ? '<li class="currentpage">'.$i.'</li>' : '<li class="pages"><a href="' .$page_link."/page/". ( ( $i - 1 ) * $post_per_page ) . '/">'.$i.'</a></li>';
            }
            if ( $i <  $init_page_max )  {
                $pagination .= "";
            }
        }
        if ( $no_of_pages > 3 )  {
            if ( $on_page > 1  && $on_page < $no_of_pages )
            {
                $pagination .= ( $on_page > 5 ) ? ' ... ' : '';
                $init_page_min = ( $on_page > 4 ) ? $on_page : 5;
                $init_page_max = ( $on_page < $no_of_pages - 4 ) ? $on_page : $no_of_pages - 4;

                for($i = $init_page_min - 1; $i < $init_page_max + 2; $i++)
                {
                    if ($urlmode != "SEF") {
                    $pagination .= ($i == $on_page) ? '<li class="currentpage">'.$i.'</li>' : '<li class="pages"><a href="' . $page_link . "&amp;pno=" . ( ( $i - 1 ) * $post_per_page )  . '">'.$i.'</a></li>';
                    }
                    else {
                    $pagination .= ($i == $on_page) ? '<li class="currentpage">'.$i.'</li>' : '<li class="pages"><a href="' . $page_link . "/page/". ( ( $i - 1 ) * $post_per_page ) . '/">'.$i.'</a></li>';
                    }
                    if ( $i <  $init_page_max + 1 )
                    {
                        $pagination .= "";
                    }
                }
                $pagination .= ( $on_page < $no_of_pages - 4 ) ? ' ... ' : '';
            }
            else
            {
                $pagination .= ' ... ';
            }
            for($i = $no_of_pages - 2; $i < $no_of_pages + 1; $i++)
            {
            if ($urlmode != "SEF") {
                $pagination .= ( $i == $on_page ) ? '<li class="currentpage">'.$i.'</li>'  : '<li class="pages"><a href="' . $page_link . "&amp;pno=" . ( ( $i - 1 ) * $post_per_page )  . '">'.$i.'</a></li>';
            }
            else
            {
                $pagination .= ( $i == $on_page ) ? '<li class="currentpage">'.$i.'</li>'  : '<li class="pages"><a href="' . $page_link . "/page/" . ( ( $i - 1 ) * $post_per_page )  . '/">'.$i.'</a></li>';
            }
                if( $i <  $no_of_pages )
                {
                    $pagination .= "";
                }
            }
        }
    }
    else
    {
        for($i = 1; $i < $no_of_pages + 1; $i++)
        {
            if ($urlmode != "SEF") {
            $pagination .= ( $i == $on_page ) ? '<li class="currentpage">'.$i.'</li>' : '<li class="pages"><a href="'.$page_link ."&amp;pno=" . ( ( $i - 1 ) * $post_per_page )  . '">'.$i.'</a></li>';
            }
            else
            {
            $pagination .= ( $i == $on_page ) ? '<li class="currentpage">'.$i.'</li>' : '<li class="pages"><a href="'.$page_link ."/page/" . ( ( $i - 1 ) * $post_per_page ) . '/">'.$i.'</a></li>';
            }
            if ( $i <  $no_of_pages )
            {
                $pagination .= "";
            }
        }
    }
        if ( $on_page > 1 )
        {
            if ($urlmode != "SEF") {
            $pagination = '<li class="pages"><a href="' . $page_link . "&amp;pno=" . ( ( $on_page - 2 ) * $post_per_page ) . '">'.$lang['Previous'].'</a>'. $pagination.'</li>';
            }
            else {
            $pagination = '<li class="pages"><a href="' . $page_link . "/page/" . ( ( $on_page - 2 ) * $post_per_page ) . '/">'.$lang['Previous'].'</a>'. $pagination.'</li>';
            }
        }

        if ( $on_page < $no_of_pages )
        {
            if ($urlmode != "SEF") {
            $pagination .= '<li class="pages"><a href="' . $page_link . "&amp;pno=" . ( $on_page * $post_per_page )  . '">'. $lang['Next'].'</a></li>';
            }
            else {
            $pagination .= '<li class="pages"><a href="' . $page_link . "/page/" . ( $on_page * $post_per_page )  . '/">'. $lang['Next'].'</a></li>';
            }
        }
    $pagination = "<b><ul id=\"pagination\"><li class=\"page\">".$lang['Page']."</li>".$pagination."</ul></b>";
    return $pagination;
}




/**
function generate_scode() {

    $show_code ="";
    $imagecode ="";
    $chars = "ABCDEFGHJKMNPRSTUVWXYZ23456789";
    $len   = strlen($chars)-1;

    for($i=0;$i<5;$i++)
     {
       $randomcode = substr($chars,rand(0,$len),1);
       $show_code .= $randomcode;
       // And we encrypt it
       $randomcode = $enc->html_encrypt($randomcode);
       $imagecode .= "<img src=\"scode.php?code=".$randomcode."\" alt=\"\" title=\"\" />";
     }

     $show_code = $enc->html_encrypt($show_code);

     $security_code = "<table background=\"./templates/".$style."/images/dot.png\"><tr><td>".$imagecode."</td></tr></table>";

     $template->assign_block_vars('scodeswitch', array(
          'SHOW_IMAGE_CODE'  => $security_code,
          'SHOW_CODE'        => $show_code,
          'SECURITY_CODE'    => $lang['Security_Code'],
          'SECURITY_PROMPT'  => $lang['Security_Prompt'],
           ));
}

**/

/**
format character  Description  Example returned values
Day  ---  ---
d  Day of the month, 2 digits with leading zeros  01 to 31
D  A textual representation of a day, three letters  Mon through Sun
j  Day of the month without leading zeros  1 to 31
l (lowercase 'L')  A full textual representation of the day of the week  Sunday through Saturday
N  ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)  1 (for Monday) through 7 (for Sunday)
S  English ordinal suffix for the day of the month, 2 characters  st, nd, rd or th. Works well with j
w  Numeric representation of the day of the week  0 (for Sunday) through 6 (for Saturday)
z  The day of the year (starting from 0)  0 through 365
Week  ---  ---
W  ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)  Example: 42 (the 42nd week in the year)
Month  ---  ---
F  A full textual representation of a month, such as January or March  January through December
m  Numeric representation of a month, with leading zeros  01 through 12
M  A short textual representation of a month, three letters  Jan through Dec
n  Numeric representation of a month, without leading zeros  1 through 12
t  Number of days in the given month  28 through 31
Year  ---  ---
L  Whether it's a leap year  1 if it is a leap year, 0 otherwise.
o  ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)  Examples: 1999 or 2003
Y  A full numeric representation of a year, 4 digits  Examples: 1999 or 2003
y  A two digit representation of a year  Examples: 99 or 03
Time  ---  ---
a  Lowercase Ante meridiem and Post meridiem  am or pm
A  Uppercase Ante meridiem and Post meridiem  AM or PM
B  Swatch Internet time  000 through 999
g  12-hour format of an hour without leading zeros  1 through 12
G  24-hour format of an hour without leading zeros  0 through 23
h  12-hour format of an hour with leading zeros  01 through 12
H  24-hour format of an hour with leading zeros  00 through 23
i  Minutes with leading zeros  00 to 59
s  Seconds, with leading zeros  00 through 59
Timezone  ---  ---
e  Timezone identifier (added in PHP 5.1.0)  Examples: UTC, GMT, Atlantic/Azores
I (capital i)  Whether or not the date is in daylights savings time  1 if Daylight Savings Time, 0 otherwise.
O  Difference to Greenwich time (GMT) in hours  Example: +0200
P  Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3)  Example: +02:00
T  Timezone setting of this machine  Examples: EST, MDT ...
Z  Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.  -43200 through 43200
Full Date/Time  ---  ---
c  ISO 8601 date (added in PHP 5)  2004-02-12T15:19:21+00:00
r  RFC 2822 formatted date  Example: Thu, 21 Dec 2000 16:01:07 +0200

**/

?>
Return current item: Bloggie Lite