<?php
/**********************************************************************
* OSAKA UNLIMITED WORDPRESS THEME 
* (Ideal For Business And Personal Use: Portfolio or Blog)      
* 
* File name:   
*      cms_functions.php
* Brief:       
*      Theme CMS functions file
* Author:      
*      DigitalCavalry
* Author URI:
*      http://themeforest.net/user/DigitalCavalry
* Contact:
*      digitalcavalry@gmail.com 
***********************************************************************/
            /*
function sidebar_selectbox( $name = '', $current_value = false ) {
    global $wp_registered_sidebars;

    if( empty( $wp_registered_sidebars ) )
        return;

    $name = ( empty( $name ) ) ? false : ' name="' . esc_attr( $name ) . '"';
    $current = ( $current_value ) ? esc_attr( $current_value ) : false;     
    $selected = '';
    ?>
    <select<?php echo $name; ?>>
    <?php foreach( $wp_registered_sidebars as $sidebar ) : ?>
        <?php 
        if( $current ) 
            $selected = selected( $sidebar['id'] == $current, true, false ); ?> 
        <option value="<?php echo $sidebar['id']; ?>"<?php echo $selected; ?>><?php echo $sidebar['name']; ?></option>
    <?php endforeach; ?>
    </select>
    <?php
}             */

function dcf_combineArgs(& $def, & $args, $add=false)
{
    $combined = $def;
    foreach($def as $key => $value)
    {
        if(array_key_exists($key, $args)) 
        {
            $combined[$key] = $args[$key];
        }
    }
    
    if($add)
    {
        foreach($args as $key => $value)
        {
            if(!array_key_exists($key, $combined))
            {
                $combined[$key] = $value;    
            }
        }
    }
    
    return $combined;
}  

/*****************************************************************
    NAME: dcf_getSecurityImage  
    
    DESCRIPTION:
        This function creates in real-time image for authorization process.
        Create call to special script that return image date outputed to 
        user browser.
        
    SPECIAL NOTE:
        Commented experimental code allow to create fully crypted image call.
        So there will be no information about code visible in website sorce code.
        There is only one condition for this solution. User browser must support
        creting images from hard coded data.    
    
    PARAMETERS:
        $w - image width
        $h - image height
        $src - image url, default set to null
        $z - zoom and crop, can be set to 0 or 1, default set to 1
        $q - image quality, can be set value form 1 to 100, default set to 75
        
    RETURN VALUE:
         Array with elements. First is an image. And the second crypted code that should be
         passed to authorization script.
         
*****************************************************************/ 

function dcf_getSecurityImage()
{
  $value = array('image' => '', 'code' => ''); 
    
  $value['code'] = (string)rand(0, 9).(string)rand(0, 9).(string)rand(0, 9).(string)rand(0, 9);  
  $value['image'] = '<img src="'.CMS_THEME_URL.'/php/authorization.php?code='.(string)$value['code'].'" />';
  $value['code'] = md5(md5($value['code']));
  
/*    
  $url = CMS_THEME_URL.'/php/authorization.php?code=10';   
  $ch = curl_init();
  $timeout = 5;
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
  $data = curl_exec($ch);
  curl_close($ch);
    
  $data = base64_encode($data); 
  $value = '<img src="data:image/png;base64,'.$data.'" />'; 
*/  
        
  return $value;
}

function dcf_attrSelected($value)
{
    $out = '';
    $out .= $value ? ' selected="selected" ' : ''; 
    return $out;
}

function dcf_attrChecked($value)
{
    $out = '';
    $out .= $value ? ' checked="checked" ' : ''; 
    return $out;
}        

function dcf_attrDisabled($value)
{
    $out = '';
    $out .= $value ? ' disabled="disabled" ' : ''; 
    return $out;
}  

function dcf_getRelativePath( $url ) 
{  
    $rel_path = $url;
    
    // find wp-content start pos
    $s = strpos($url, 'wp-content');
    // get path from wp-content folder to end
    $from_wp_content = substr($url, $s);
    // remove wp-content folder
    $from_wp_content = str_replace('wp-content', '', $from_wp_content);
    
    $rel_path = WP_CONTENT_DIR.$from_wp_content;
    return $rel_path;    
} 

function dcf_formatBytes($bytes=0)
{
    if ($bytes < 1024) {
        return $bytes .' B';
    } elseif ($bytes < 1048576) {
        return round($bytes / 1024, 2) .' kB';
    } elseif ($bytes < 1073741824) {
        return round($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes < 1099511627776) {
        return round($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes < 1125899906842624) {
        return round($bytes / 1099511627776, 2) .' TB';
    }
}

/*****************************************************************
    NAME: dcf_getTimThumbURL  
    
    DESCRIPTION:
        This function returns path to timthumb script which should be
        located in main theme folder and named thumb.php
    
    PARAMETERS:
        $w - image width
        $h - image height
        $src - image url, default set to null
        $z - zoom and crop, can be set to 0 or 1, default set to 1
        $q - image quality, can be set value form 1 to 100, default set to 75
        
    RETURN VALUE:
        url to timthumb script with image path and parameters,
        if src parameter is not set, function will return only
        path to timthumb script
         
*****************************************************************/ 
function dcf_getTimThumbURL($src=null, $w=null, $h=null, $z=1, $q=100)
{  
    $value = '';
    
    if($src === null)  
    {
        $value = CMS_THEME_URL.'/thumb.php';    
    } else
    {
        $value = CMS_THEME_URL.'/thumb.php';
        $value .= '?src='.$src; 
        $value .= '&w='.$w;
        $value .= '&h='.$h;
        $value .= '&z='.$z; 
        $value .= '&q='.$q;  
    }
     
    return $value;
}

function dcf_getImageSize($url)
{
    $path = dcf_getRelativePath($url);    
    
    if(!is_file($path)) 
    {        
        return false;
    }    
        
    $path_info = pathinfo($path);     
    $image_size = getimagesize($path);
    $image = array();
    $image['path'] = $path;
    $image['w'] = $image_size[0];
    $image['h'] = $image_size[1];       
    $image['ext'] = $path_info['extension']; 
    
    return $image;
}

function dcf_getImageURL($url=null, $w=null, $h=null, $crop=CMS_IMAGE_CROP_FIT, $filter=CMS_IMAGE_FILTER_NONE, $keep_size=false) 
{
    $value = '';
    $FRESHIZER = true;
    $TIMTHUMB = false;
 
    if($url == '' or $url === null or !is_string($url)) { return $value; }
 
    if($keep_size)
    {
        $image = dcf_getImageSize($url);
        
        if($image !== false)
        {
            $w = $image['w'];
            $h = $image['h'];
        }           
    }
    
    if($filter != CMS_IMAGE_FILTER_NONE and $filter != CMS_IMAGE_FILTER_GRAYSCALE) { $filter = CMS_IMAGE_FILTER_NONE; }

    if($TIMTHUMB)
    {
        switch($crop)
        {
            case CMS_IMAGE_NOCROP: $crop = 3; break;
            case CMS_IMAGE_CROP_FIT: $crop = 1; break;
            case CMS_IMAGE_NOCROP_FIT: $crop = 2; break;
            default: $crop = 1; break;
        }
        
        switch($filter)
        {
            case CMS_IMAGE_FILTER_GRAYSCALE: $filter = '&f=2'; break;
            default: $filter = ''; break;
        }
        
        if($url === null)  
        {
            $value = CMS_THEME_URL.'/thumb.php';    
        } else
        {
            $value = CMS_THEME_URL.'/thumb.php';
            $value .= '?src='.$url; 
            $value .= '&w='.$w;
            $value .= '&h='.$h;
            $value .= '&zc='.$crop; 
            $value .= '&q=95';  
            $value .= $filter;
        }            
    } else
    if($FRESHIZER)
    {   
        switch($crop)
        {
            case CMS_IMAGE_NOCROP: $crop = DCC_FreShizer::IMAGE_NOCROP; break;
            case CMS_IMAGE_CROP_FIT: $crop = DCC_FreShizer::IMAGE_CROP_FIT; break;
            case CMS_IMAGE_NOCROP_FIT: $crop = DCC_FreShizer::IMAGE_NOCROP_FIT; break; 
            default: $crop = DCC_FreShizer::IMAGE_CROP_FIT; break;
        }    
        
        switch($filter)
        {
            case CMS_IMAGE_FILTER_NONE: $filter = DCC_FreShizer::IMAGE_FILTER_NONE; break;
            case CMS_IMAGE_FILTER_GRAYSCALE: $filter = DCC_FreShizer::IMAGE_FILTER_GRAYSCALE; break; 
            default: $filter = DCC_FreShizer::IMAGE_FILTER_NONE; break;
        }          
          
        $value = DCC_FreShizer::resize($url, $w, $h, $crop, $filter);
    }
 
    return $value;    
}

/*****************************************************************
    NAME: dcf_strNWords  
    
    DESCRIPTION:
         This function returns first N words from given string  
    
    PARAMETERS:
        $str - string
        $count - number of first words from string to return
        
    RETURN VALUE:
         first N words from given string
         
*****************************************************************/ 
function dcf_strNWords($str, $count=20, $postfix='...')
{
    $value = $str;
    
    if($count > 0)
    {
        $array = explode(' ', $str);

        if(count($array) <= $count)
        {
            $value = $str;
        }
        else
        {
            array_splice($array, $count);
            $value = implode(' ', $array).$postfix;
            if($value == $postfix) { $value = ''; }
        }
    } else
    {
        $value = '';
    }
    
    return $value;
}

function dcf_getLastLineIndex($count=0, $perline=0)
{
    $r = 0;
    
    if($count and $perline)
    {
        if($count <= $perline) 
        { $r = 0; }
        else
        {
            $full_lines = (int)($count/$perline);
            $rest = $count % $perline;
            
            $r = $full_lines*$perline;
            if($rest == 0)
            {
                $r -= $perline;
            }   
        }    
    }
    
    return $r;    
}

function dcf_getGalleriesNGG($order_by = 'gid', $order_dir = 'ASC', $counter = false, $limit = 0, $start = 0, $exclude = true, $selected_ids='', $excluded_ids='', & $max_page=null) 
{      
        
    global $wpdb; 
    global $nggdb;    
    $galleries = false;  
      
    if(isset($wpdb) and isset($nggdb))  
    {            
        // Check for the exclude setting
        $exclude_clause = ($exclude) ? ' AND exclude<>1 ' : '';
        $order_dir = ( $order_dir == 'DESC') ? 'DESC' : 'ASC';
        $limit_by  = ( $limit > 0 ) ? 'LIMIT ' . intval($start) . ',' . intval($limit) : '';
        $excluded_galleries = ($excluded_ids != '') ? " $wpdb->nggallery.gid NOT IN ($excluded_ids) " : '';        
        $selected_galleries = ($selected_ids != '') ? " $wpdb->nggallery.gid IN ($selected_ids) " : '';
        $before = '';
        
        if($excluded_galleries != '' or $selected_galleries != '')
        {
            $before = ' WHERE ';
        }   
        
        if($excluded_galleries != '' and $selected_galleries != '')
        {
            $selected_galleries = ' AND '.$selected_galleries;    
        }       
        
        $galleries = $wpdb->get_results( "SELECT SQL_CALC_FOUND_ROWS * FROM $wpdb->nggallery $before $excluded_galleries $selected_galleries ORDER BY {$order_by} {$order_dir} {$limit_by}", OBJECT_K );
        
        // Count the number of galleries
        if($max_page !== null and $limit > 0)
        {
            $total = intval( $wpdb->get_var( "SELECT FOUND_ROWS()" ) );            
            $max_page = (int)ceil($total / $limit);
        }       
        
        if ( !$galleries )
        {         
            return array();
        }
        
        $galleriesID = array(); 
        // get the galleries information    
        foreach ($galleries as $key => $value) {
            $galleriesID[] = $key;
            // init the counter values
            $galleries[$key]->counter = 0;
            $galleries[$key]->title = stripslashes($galleries[$key]->title);
            $galleries[$key]->galdesc  = stripslashes($galleries[$key]->galdesc);   
        }

        // if we didn't need to count the images then stop here
        if ( !$counter )
        {
            return $galleries;
        }
        
        // get the counter values   
        $picturesCounter = $wpdb->get_results('SELECT galleryid, COUNT(*) as counter FROM '.$wpdb->nggpictures.' WHERE galleryid IN (\''.implode('\',\'', $galleriesID).'\') ' . $exclude_clause . ' GROUP BY galleryid', OBJECT_K);

        if ( !$picturesCounter )
        {
            return $galleries;
        }
        
        // add the counter to the gallery object    
        foreach ($picturesCounter as $key => $value) {
            $galleries[$value->galleryid]->counter = $value->counter;
        }
    }
    
    return $galleries;    
}

function dcf_getGalleryNGG($id, $order_by = 'sortorder', $order_dir = 'ASC', $exclude = true, $limit = 0, $start = 0, & $max_page=null) 
{
    global $wpdb;
    global $nggdb;    

    // init the gallery as empty array
    $gallery = array();    
    
    if(isset($wpdb) and isset($nggdb))
    {                   
        // Check for the exclude setting
        $exclude_clause = ($exclude) ? ' AND tt.exclude<>1 ' : '';
        
        // Say no to any other value
        $order_dir = ( $order_dir == 'DESC') ? 'DESC' : 'ASC';
        $order_by  = ( empty($order_by) ) ? 'sortorder' : $order_by;
        
        // Should we limit this query ?
        $limit_by  = ( $limit > 0 ) ? 'LIMIT ' . intval($start) . ',' . intval($limit) : '';
        
        // Query database
        $result = $wpdb->get_results(
            $wpdb->prepare( "SELECT SQL_CALC_FOUND_ROWS tt.*, t.* 
            FROM $wpdb->nggallery AS t INNER JOIN $wpdb->nggpictures AS tt ON t.gid = tt.galleryid 
            WHERE t.gid = %d {$exclude_clause} 
            ORDER BY tt.{$order_by} {$order_dir} {$limit_by}", $id ), OBJECT_K );
        
        if($max_page !== null and $limit > 0)
        {
            $total = intval( $wpdb->get_var( "SELECT FOUND_ROWS()" ) );            
            $max_page = (int)ceil($total / $limit);
        }              
        
        // Build the object
        if($result) 
        {                
            // Now added all image data
            foreach ($result as $key => $value)
            {
                $pic = new nggImage( $value );                
                $new_pic = new DCC_NGGImage(
                    $pic->pid,
                    $pic->imageURL,
                    $pic->thumbURL,
                    $pic->meta_data['width'],
                    $pic->meta_data['height'],
                    $pic->thumbcode,
                    $pic->description,
                    $pic->alttext,
                    $pic->imagedate 
                );           
                 
                array_push($gallery, $new_pic);                 
            }
        } else
        {
            $gallery = false;    
        }
    } else
    {
        $gallery = false;    
    } 
    
    return $gallery;        
}

function dcf_getNGGLastImages($page=0, $limit=15, $exclude=true, $gid=0, $orderby='id')
{
    global $nggdb;
    $gallery = false;
    if(isset($nggdb))
    {
        $result = $nggdb->find_last_images($page, $limit, $exclude, $gid, $orderby); 
        if($result !== null)
        {
            $gallery = array();

            foreach($result as $pic)
            {
                $new_pic = new DCC_NGGImage(
                    $pic->pid,
                    $pic->imageURL,
                    $pic->thumbURL,
                    $pic->meta_data['width'],
                    $pic->meta_data['height'],
                    $pic->thumbcode,
                    $pic->description,
                    $pic->alttext,
                    $pic->imagedate
                );           
                 
                array_push($gallery, $new_pic); 
            }            
        }
    }        
    
    return $gallery;      
}

function dcf_getNGGRandomImages($number = 1, $gid = 0)
{
    global $nggdb;
    $gallery = false;
    if(isset($nggdb))
    {
        $result = $nggdb->get_random_images($number, $gid); 
        if($result !== null)
        {
            $gallery = array();
            // Now added all image data
            foreach($result as $pic)
            {
                $new_pic = new DCC_NGGImage(
                    $pic->pid,
                    $pic->imageURL,
                    $pic->thumbURL,
                    $pic->meta_data['width'],
                    $pic->meta_data['height'],
                    $pic->thumbcode,
                    $pic->description,
                    $pic->alttext,
                    $pic->imagedate
                );           
                 
                array_push($gallery, $new_pic); 
            }            
        }
    }        
    
    return $gallery;          
}

function dcf_getNGGInfo($gid)
{    
    global $nggdb;
    $gallery = false;
    if(isset($nggdb))
    {
        $gallery = $nggdb->find_gallery($gid); 
    }        
    
    return $gallery;  
}

function dcf_getWholeNGG($gid, & $ret_count=null)
{
    
    global $nggdb;
    $objs = array();
    if(isset($nggdb))
    {
        $gallery = $nggdb->find_gallery($gid); 
        if($gallery !== false)
        {
            $pics = $nggdb->get_gallery($gid); 
            
            $count = 0;
            if(is_array($pics)) { $count = count($pics); } 
            if($ret_count !== null) { $ret_count = $count; } 
            
            foreach($pics as $pic)
            {
                $new_pic = new DCC_NGGImage(
                    $pic->pid,
                    $pic->imageURL,
                    $pic->thumbURL,
                    $pic->meta_data['width'],
                    $pic->meta_data['height'],
                    $pic->thumbcode,
                    $pic->description,
                    $pic->alttext,
                    $pic->imagedate
                );           
                 
                array_push($objs, $new_pic); 
            }                                        
        }
    }        
    
    return $objs;  
}

function dcf_sortPostInUserOrder($id_array, $data)
{
    $new_posts_array = Array(); 
    $count = count($data);
    foreach($id_array as $us_id)
    {
        $index = -1;
        for($i = 0; $i < $count; $i++)
        {
            if($data[$i]->ID == $us_id)
            {
                $index = $i;
                break;
            }
        }
        if($index != -1)
        {
            array_push($new_posts_array, $data[$index]);
        }
    }
    return $new_posts_array;                  
}   

function dcf_GetWPMainDir() 
{
    $value = CMS_THEME_PATH;
    $pos = strpos(CMS_THEME_PATH, 'wp-content');
    $value = substr($value, 0, $pos);
    return $value;
}

function dcf_isNGGImageID($path, $object=false)
{
    $value = $path;
    if($value == '') return $value;
    
    $numeric = is_numeric(trim($path));       
    if($numeric)
    {
        
        global $nggdb;
        if(isset($nggdb))
        {
            $id = (int)$path;
            $list = array();
            $list[0] = $id;
            $pics = $nggdb->find_images_in_list($list, false);
            $pics = array_values($pics);
            $count = count($pics);
            if($count == 0)
            {
                $value = '';    
            } else
            {
                if($object)
                {
                    $new_pic = new DCC_NGGImage(
                        $pics[0]->pid,
                        $pics[0]->imageURL,
                        $pics[0]->thumbURL,
                        $pics[0]->meta_data['width'],
                        $pics[0]->meta_data['height'],
                        $pics[0]->thumbcode,
                        $pics[0]->description,
                        $pics[0]->alttext,
                        $pics[0]->imagedate
                    );                       
                    
                    $value = $new_pic;    
                } else
                {
                    $value = $pics[0]->imageURL; 
                }
            }
        }    
    }
    return $value; 
}

function dcf_getNGGImagesFromGallery($gid, & $ret_count=null, $num=null)
{
    $pics = array();
    if($gid != CMS_NOT_SELECTED)
    {
        global $nggdb;
        if(isset($nggdb))
        {
            $gallery = $nggdb->find_gallery($gid);
            if($gallery != false)
            {                 
                $pics = $nggdb->get_gallery($gid);
            }
        }
    }

    $count = count($pics);
    if($ret_count !== null) { $ret_count = $count; }    
    $objs = array();
    
    $counter = 0;
    foreach($pics as $pic)
    {
        $new_pic = new DCC_NGGImage(
            $pic->pid,
            $pic->imageURL,
            $pic->thumbURL,
            $pic->meta_data['width'],
            $pic->meta_data['height'],
            $pic->thumbcode,
            $pic->description,
            $pic->alttext,
            $pic->imagedate 
        );           
         
        array_push($objs, $new_pic); 
        
        if($num !== null)
        {
            $counter++;
            if($counter >= $num)
            {
                break;
            }    
        }
    }
        
    return $objs;    
}

/*****************************************************************
    NAME: dcf_getNGGImagesFromIDList  
    
    PARAMETERS:
        $img_ids - string with images id's
        $ret_count - optional, variable in which will be return number of images
        $num - optional number of images to get
        
    RETURN VALUE:
        array of image objects
         
*****************************************************************/ 
function dcf_getNGGImagesFromIDList($img_ids, & $ret_count=null, $num=null)
{
    $imga_ids = null;
    
    $pos = strpos($img_ids, '-');
    if($pos !== false)
    {
        $values = explode('-', $img_ids);
        $imga_ids = array();
        for($i = (int)$values[0]; $i <= (int)$values[1]; $i++)
        {
            array_push($imga_ids, $i);    
        }        
    } else
    {
        $imga_ids = explode(',', $img_ids);
    }
    $count = count($imga_ids);
    if($ret_count !== null) { $ret_count = $count; }
    $pics = null;
    if($count > 0)
    {
        global $nggdb;
        if(isset($nggdb))
        {
            $new_array = array();
            if($num !== null)
            {
                for($i = 0; $i < $num; $i++)
                {
                    array_push($new_array, $imga_ids[$i]);     
                }
                $imga_ids = $new_array;    
            }
            $pics = $nggdb->find_images_in_list($imga_ids, false);
        }
    }

    $objs = array();
    if(is_array($pics))
    {
        foreach($pics as $pic)
        {
            $new_pic = new DCC_NGGImage(
                $pic->pid,
                $pic->imageURL,
                $pic->thumbURL,
                $pic->meta_data['width'],
                $pic->meta_data['height'],
                $pic->thumbcode,
                $pic->description,
                $pic->alttext,
                $pic->imagedate 
            );           
             
            array_push($objs, $new_pic); 
        }
    }
        
    return $objs;       
}



function dcf_getWPDBFoundRows()
{
    global $wpdb;
    $querystr = "SELECT FOUND_ROWS();";
    $allitems = $wpdb->get_results($querystr, ARRAY_N);
    $allitems = (int)$allitems[0][0]; 
    
    return $allitems;   
}



    
  
/*****************************************************************
    NAME: dcf_neatTrim
    
    PARAMETERS:
        $str - string to trim
        $n - max number of displayed chars
        $delim - small string added on the end of generated string
        $cuted - true if string was cuted  
        
    RETURN VALUE:
        Cuted string  
*****************************************************************/ 
function dcf_neatTrim($str, $n, $delim='...', & $cuted=null) 
{
    $str = str_replace("\n",'',$str);
    $str = str_replace("\r",'',$str);
    $str = strip_tags($str);
 
   $len = strlen($str); 
   if ($len > $n) { 
       
       if(isset($cuted))
       {
           $cuted = true;
       }
       
       
       preg_match('/(.{' . $n . '}.*?)\b/', $str, $matches);           
        
       return rtrim($matches[1]) . $delim; 
   } 
   else { 
       if(isset($cuted))
       {
           $cuted = false;
       }           
       
       return $str; 
   } 
}




/*****************************************************************
    NAME: dcf_comments_number   
*****************************************************************/
function dcf_calculatePastTime($pre, $hour, $minute, $second, $month, $day, $year)
{
    $old = mktime($hour, $minute, $second, $month, $day, $year); 
    $new = current_time('timestamp');
    $value = $new - $old;
    
    $second = $value;
    
    if($second < 0) { $second = 0; } 
    $minute = floor($second/60);
    $hour = floor($second/60/60);
    $day = floor($second/60/60/24);
    $month = floor($second/60/60/24/30);
    $year = floor($second/60/60/24/365);
    
    
    if($pre != '') { $pre .= ' '; }
    
    // check years
    if($year > 0)
    {
        if($year == 1) { $value = $pre.__('1 year ago', CMS_TXT_DOMAIN); } else { $value = $pre.$year.' '.__('years ago', CMS_TXT_DOMAIN); }
    } else // check months
    if($month > 0)
    {
        if($month == 1) { $value = $pre.__('1 month ago', CMS_TXT_DOMAIN); } else { $value = $pre.$month.' '.__('months ago', CMS_TXT_DOMAIN); }
    } else // check days
    if($day > 0)
    {
        if($day == 1) { $value = $pre.__('1 day ago', CMS_TXT_DOMAIN); } else { $value = $pre.$day.' '.__('days ago', CMS_TXT_DOMAIN); }
    } else // check hours
    if($hour > 0)
    {
        if($hour == 1) { $value = $pre.__('1 hour ago', CMS_TXT_DOMAIN); } else { $value = $pre.$hour.' '.__('hours ago', CMS_TXT_DOMAIN); }
    } else // check minutes        
    if($minute > 0)
    {
        if($minute == 1) { $value = $pre.__('1 minute ago', CMS_TXT_DOMAIN); } else { $value = $pre.$minute.' '.__('minutes ago', CMS_TXT_DOMAIN); }
    } else // check seconds
    if($second >= 0)
    {
        if($second == 0) { $value = __('Right now', CMS_TXT_DOMAIN); } else
        if($second == 1) { $value = $pre.__('1 second ago', CMS_TXT_DOMAIN); } else { $value = $pre.$second.' '.__('seconds ago', CMS_TXT_DOMAIN); }
    }                        
    
    return $value;
}

function dcf_getPastTime($date, $pre='')
{
    $hour = mysql2date('H', $date, true); 
    $minute = mysql2date('i', $date, true);
    $second = mysql2date('s', $date, true);
    $month = mysql2date('n', $date, true);
    $day = mysql2date('j', $date, true);
    $year = mysql2date('Y', $date, true);    
    
    $old = mktime($hour, $minute, $second, $month, $day, $year);
    $new = mktime();
    $value = $new - $old;
    
    $second = $value;
    if($second < 0) { $second = 0; } 
    $minute = floor($second/60);
    $hour = floor($second/60/60);
    $day = floor($second/60/60/24);
    $month = floor($second/60/60/24/30);
    $year = floor($second/60/60/24/365);
    
    if($pre != '') { $pre .= ' '; }
    
    // check years
    if($year > 0)
    {
        if($year == 1) { $value = $pre.__('1 year ago', CMS_TXT_DOMAIN); } else { $value = $pre.$year.' '.__('years ago', CMS_TXT_DOMAIN); }
    } else // check months
    if($month > 0)
    {
        if($month == 1) { $value = $pre.__('1 month ago', CMS_TXT_DOMAIN); } else { $value = $pre.$month.' '.__('months ago', CMS_TXT_DOMAIN); }
    } else // check days
    if($day > 0)
    {
        if($day == 1) { $value = $pre.__('1 day ago', CMS_TXT_DOMAIN); } else { $value = $pre.$day.' '.__('days ago', CMS_TXT_DOMAIN); }
    } else // check hours
    if($hour > 0)
    {
        if($hour == 1) { $value = $pre.__('1 hour ago', CMS_TXT_DOMAIN); } else { $value = $pre.$hour.' '.__('hours ago', CMS_TXT_DOMAIN); }
    } else // check minutes        
    if($minute > 0)
    {
        if($minute == 1) { $value = $pre.__('1 minute ago', CMS_TXT_DOMAIN); } else { $value = $pre.$minute.' '.__('minutes ago', CMS_TXT_DOMAIN); }
    } else // check seconds
    if($second >= 0)
    {
        if($second == 0) { $value = __('Right now', CMS_TXT_DOMAIN); } else
        if($second == 1) { $value = $pre.__('1 second ago', CMS_TXT_DOMAIN); } else { $value = $pre.$second.' '.__('seconds ago', CMS_TXT_DOMAIN); }
    }                        
    
    return $value;
}


/*****************************************************************
    NAME: dcf_next_post 
*****************************************************************/
function dcf_twitterify($text) 
{
    $text = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)[a-z0-9A-Z]*#", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $text);
    $text = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)[a-z0-9A-Z]*#", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $text);
    $text = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $text);
    $text = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=\\1\" target=\"_blank\">#\\1</a>", $text);
    return $text;
} 

/*****************************************************************
    NAME: dcf_next_post 
*****************************************************************/
function dcf_nextPost($type='post', $tax='', $terms='')
{   
    global $wpdb;
    global $post;
                             
    $current_date = $post->post_date;
    
    $querydate = '';
    $querydate .= " AND $wpdb->posts.post_date > TIMESTAMP('$current_date') ";                   
    
    $subquery = '';        
    if($terms != '')
    {
        $a_terms = explode(',', $terms);
        $count_terms = count($a_terms);                
        if($count_terms > 0)
        {
            for($i = 0; $i < $count_terms; $i++)
            {
                if($i > 0)
                {
                    $subquery .= ' OR ';    
                }
                $subquery .= "$wpdb->terms.slug = '".$a_terms[$i]."' ";
            }
            $subquery = ' AND ('.$subquery.') ';
        }
    }          

    $querytax = '';
    if($tax != '')
    {
        $querytax = " AND $wpdb->term_taxonomy.taxonomy = '$tax' "; 
    }
    
    $querystr = "
        SELECT ID, post_title, post_date
        FROM $wpdb->posts
        LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
        LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
        LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
        WHERE $wpdb->posts.post_type = '$type'".
        $querydate.
        "AND $wpdb->posts.post_status = 'publish' ".
        $querytax.
        $subquery.
        "GROUP BY $wpdb->posts.ID ORDER BY $wpdb->posts.post_date ASC LIMIT 1";

    $list = $wpdb->get_results($querystr, OBJECT);                
    $count = count($list);    
    
    $value = false;
    if($count > 0) { $value = $list[0]; }
    return $value;
}  

/*****************************************************************
    NAME: dcf_prev_post 
*****************************************************************/
function dcf_prevPost($type='post', $tax='', $terms='')
{   
    global $wpdb;
    global $post;
                             
    
    $current_date = $post->post_date;
    
    $querydate = '';
    $querydate .= " AND $wpdb->posts.post_date < TIMESTAMP('$current_date') ";                   
    
    $subquery = '';        
    if($terms != '')
    {
        $a_terms = explode(',', $terms);
        $count_terms = count($a_terms);                
        if($count_terms > 0)
        {
            for($i = 0; $i < $count_terms; $i++)
            {
                if($i > 0)
                {
                    $subquery .= ' OR ';    
                }
                $subquery .= "$wpdb->terms.slug = '".$a_terms[$i]."' ";
            }
            $subquery = ' AND ('.$subquery.') ';
        }
    }          
    
    $querytax = '';
    if($tax != '')
    {
        $querytax = " AND $wpdb->term_taxonomy.taxonomy = '$tax' "; 
    }
    
    $querystr = "
        SELECT ID, post_title, post_date
        FROM $wpdb->posts
        LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
        LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
        LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
        WHERE $wpdb->posts.post_type = '$type'".
        $querydate.
        "AND $wpdb->posts.post_status = 'publish' ".
        $querytax.
        $subquery.
        "GROUP BY $wpdb->posts.ID ORDER BY $wpdb->posts.post_date DESC LIMIT 1";

    $list = $wpdb->get_results($querystr, OBJECT);             
    $count = count($list); 
    
    $value = false;
    if($count > 0) { $value = $list[0]; }
    return $value;       
} 

?>
