<?PHP

// some function to power my own small blog

/*

    This file was written by Thorsten Gunkel <tgunkel@gmx.de> for
    his blog on <url:http://www.tgunkel.de>.
    Copyright (C) 2004 Thorsten Gunkel

    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 version 2 of the License.

    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

*/

// lists mybbcode examples
function get_mybbcode_help()
{
  
$txt='<ul>';
  
$txt.='<li>[b][/b]</li>';
  
$txt.='<li>[quote][/quote]</li>';
  
$txt.='<li>[del][/del]</li>';
  
$txt.='<li>[sub][/sub]</li>';
  
$txt.='<li>[ul][li][/li][li][/li][/ul]</li>';
  
$txt.='<li>[br]</li>';
  
$txt.='<li>[pic=\'FOLDER\']PICTURE[/pic] [pic=\'EigeneBilder\']heinz.jpg[/pic]</li>';
  
$txt.='<li>[url=\'\'][/url]<br />[url=\'_REPLACE_HEREPFAD_files/foobar\'][/url]<br />[url=\'_REPLACE_BACKPFAD_foo/bar\'][/url]</li>';
  
$txt.='<li>[img=\'\'][/img]<br />[img=\'_REPLACE_HEREPFAD_files/foobar\'][/img]<br />[img=\'_REPLACE_BACKPFAD_foo/bar\'][/img]</li>';
  
$txt.='</ul>';
  
$txt.="\n".'

<a href="javascript:void(0)" onclick="disp_prompt()">quote insert per Java Script Test</a>


<script type="text/javascript">
//<![CDATA[

function disp_prompt()
{
var yourinput=prompt("Text to quote:","")
if (yourinput!=null && yourinput!="")
{
alert("[quote]" + yourinput + "[/quote]")
}
}

//]]>
</script>

'
."\n";
  return 
$txt;
}

function 
importFromPictureGal($folder$picture$blogconfig)
{
 if (
$picture=='ERROR: No content'$picture='';
 require_once(
$blogconfig['backpfad'].'../php-bin/picturegal.inc.php');
 return 
pictureAccessForOthers($folder$picture$blogconfig);
}

// parses my bbcode and translate it into html
function mybbcode2html($string$config)
{
  
/* Syntax:
   *         [b]foo[/b]            <em>foo</em>
   *         [br]                  <br />
   *         [ul][li]foo[li]+[/ul] <ul><li>foo</li>+</ul>
   *         [pic='folder1/']picture1[/pic]
   *         [url='foo']bar[/url]  <a href="foo">bar</a>
   *         [img='foo']bar[/img]  <img src="foo" alt="bar" />
   *         [sub]foo[/sub]        <?>foo</?>
   *         [quote][/quote]       <?>foo</?>
   *         [del][/del]           <?>foo</?>
   */

  // enforces that [br] is open/close tag
  
$string=preg_replace('/([^\\\])\[br\]\[\/br\]/''$1[br]'$string);
  
$string=preg_replace('/([^\\\])\[br\]/''$1[br][/br]'$string);
  
  
//split string into [] tags and no tags
  
$invalid=false;
  
$my_stack=array();

  
// FIXME: ignore \[ \]

  // split aaa[bbb]ccc into aaa, [bbb], ccc
  
$splitted=preg_split('/(\[[^\]]*\])/'$string, -1PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
  foreach (
$splitted as $apiece)
    {
      
//DEBUG echo 'New :"'.$apiece."\"<br>\n";
      
$entry=array();

      
// is it a tag?
      
if ((!$invalid) && (preg_match('/^\[(|\/)[a-z]{1,5}(|=\'[^\']+\')\]/',$apiece)))
        {
          
$apiece=preg_replace('/^\[(.*)\]$/',"$1",$apiece);
          
//DEBUG echo 'OK :"'.$apiece."\"<br>\n";

          // open or close tag?
          
if (preg_match('/^[^\/]/',$apiece))
            {
              
$entry['istag']=true;
              
// get extra attributes from tag
              
$tag_content=preg_split('/=/'$apiece2);
              
// extra attribute?
              
if (array_key_exists(1,$tag_content))
                {
                  if (
preg_match('/^\'(.*)\'$/',$tag_content[1]))
                    {
                      
$tag_content[1]=preg_replace('/^\'(.*)\'$/',"$1",$tag_content[1]);
                    }
                  else
                    {
                      
$tag_content[1]='ERROR';
                      
$invalid=true;
                    }
                }
              else
                {
                  
$tag_content[1]='';
                }
              
$entry['content']=$tag_content[0];
              
$entry['extra']=$tag_content[1];
              
array_push($my_stack,$entry);
            }
          else
            {
              
$apiece=preg_replace('/^\//','',$apiece);
              
// search where the curent tag was opened
              
$pos=count($my_stack)-1;
              if (
$pos>=0)
                {
                  
// the previous field may be content
                  
if (!$my_stack[$pos]['istag'])
                    {
                      
$tmp_content=$my_stack[$pos]['content'];
                      
$pos--;
                      
array_pop($my_stack);
                    }
                  else
                    {
                      
$tmp_content='ERROR: No content';
                    }
                  if ( (
$pos>=0) && ($my_stack[$pos]['istag']) && ($my_stack[$pos]['content']==$apiece) )
                    {
                      
// replace bbcode with html
                      
unset($new_string);
                      switch(
$apiece)
                        {
                        case 
'b':
                          
$new_string='<em>'.$tmp_content.'</em>';
                          break;
                        case 
'sub':
                          
$new_string='<hr /><em>'.$tmp_content.'</em><br />';
                          break;
                        case 
'del':
                          
$new_string='<del>'.$tmp_content.'</del>';
                          break;
                        case 
'quote':
                          
$new_string='<div class="blog-quote">'.$tmp_content.'</div>';
                          break;
                        case 
'img':
                          
$new_string='<img class="blog-img" src="'.$my_stack[$pos]['extra'].'" alt="'.$tmp_content.'" title="'.$tmp_content.'" />';
                          break;
                        case 
'li':
                          
$new_string='<li>'.$tmp_content.'</li>';
                          break;
                        case 
'ul':
                          
$new_string='<ul>'.$tmp_content.'</ul>';
                          break;
                        case 
'url':
                          
$new_string='<a href="'.$my_stack[$pos]['extra'].'">'.$tmp_content.'</a>';
                          break;
                        case 
'pic';
                          
$new_string.=importFromPictureGal($my_stack[$pos]['extra'], $tmp_content$config);
                          break;
                        case 
'br':
                          
$new_string='<br />';
                          break;  
                        default:
                          if (
$my_stack[$pos]['extra']!='')
                            {
                              
$new_string='['.$apiece.'=\''.$my_stack[$pos]['extra'].'\']'.$tmp_content.'[/'.$apiece.']';
                            }
                          else
                            {
                              
$new_string='['.$apiece.']'.$tmp_content.'[/'.$apiece.']';
                            }
                          
$invalid=true;
                          break;
                        }
                      
array_pop($my_stack);
                      
// push string back on stack
                      
$new_entry=array();
                      
$new_entry['istag']=false;
                      
$new_entry['content']=$new_string;
                      
$new_entry['extra']='';
                      
array_push($my_stack,$new_entry);
                    }
                  else
                    
$invalid=true;
                }
            }
        }
      else
        {
          
// put our non-tag on the stack
          
$new_entry['istag']=false;
          
$new_entry['content']=$apiece;
          
$new_entry['extra']='';
          
array_push($my_stack,$new_entry);
        }
      
// Merge the last non-tag entries on the stack
      
if (count($my_stack)>=2)
        {
          if (!(
$my_stack[count($my_stack)-1]['istag'] || $my_stack[count($my_stack)-2]['istag']))
            {
              
$my_stack[count($my_stack)-2]['content'].=$my_stack[count($my_stack)-1]['content'];
              
array_pop($my_stack);
            }
        }
      
//DEBUG: foreach ($my_stack as $tg) { echo '- '.$tg['content']."<br>\n"; echo "<hr>";
    
}

  
// Check if stack contains unparsed elementes
  
if (count($my_stack)>1$invalid=true;

  
// rebuild string from the stack
  
$ret_string='';
  if (
$invalid$ret_string='[With ERRORS] ';
  foreach (
$my_stack as $one_entry)
    
$ret_string.=$one_entry['content'];
  return 
$ret_string;
}

// secure text
function format_txt_secure($string)
{
  
$string=htmlspecialchars($string);
  return 
$string;
}

// Take text user enters, secures it, replace line breaks with [br]
function format_txt_input_2_saveable($string)
{
  
$string=replace_line_break(get_fixed_line_break($string),'[br]');
  
$string=format_txt_secure($string);
  return 
$string;
}

// Take saved text, and replace a variant easy to edit
function format_txt_savable_2_editable($string)
{
  
$string=preg_replace('/\[br\]/',"\n".'_REPLACE_POS1_',$string);
  return 
$string;
}

// Take text user enters, secures it, replace line breaks with [br]
function format_txt_saveable_2_output($string$backpfad$destpath$config)
{
  
$string=mybbcode2html($string$config);
  
$string=replace_backpfad($string,$backpfad);
  
$string=replace_herepfad($string,$backpfad,$destpath);
  return 
$string;
}

// Take text user enters and secures it
function format_txt_input_2_input($string)
{
  
$string=preg_replace('/\[br\]/',"\n".'_REPLACE_POS1_',$string);
  
$string=format_txt_secure($string);
  return 
$string;
}

// send changes via mail
function send_mail($dest_adress,$mode,$date,$lmod,$ip,$id,$topic,$title_de,$text_de,$title_en,$text_en,$title_fr,$text_fr)
{
  
$m_subject='Mein Blog: '.$mode.' ID: '.$id;
  
$m_txt='';
  
$m_txt.='Anweisung: '.$mode."\n";
  
$m_txt.='Datum    : '.$date."\n";
  
$m_txt.='Geaendert: '.$lmod."\n";
  
$m_txt.='IP       : '.$ip."\n";
  
$m_txt.='ID       : '.$id."\n";
  
$m_txt.='Kategorie: '.$topic."\n";
  
$m_txt.='Titel DE : '.$title_de."\n";
  
$m_txt.='Text  DE : '.$text_de."\n";
  
$m_txt.='Titel EN : '.$title_en."\n";
  
$m_txt.='Text  EN : '.$text_en."\n";
  
$m_txt.='Titel FR : '.$title_fr."\n";
  
$m_txt.='Text  FR : '.$text_fr."\n";

  
mail($dest_adress,$m_subject,$m_txt);
}

// get form values and secure them
function secure_formdata(&$formdata)
{
  foreach (
$formdata as $formkey => $formdat)
    {
      
$formdata[$formkey]=get_form_undo_escaped($formdat);
      switch(
$formkey)
        {
          
// enforce valid numbers
        
case 'f_topic':
        case 
'id_count':
        case 
'id':
        case 
'topicfiler':
        case 
'id_skip':
          
$formdata[$formkey]=preg_replace('/[^0-9]/','',$formdata[$formkey]);
          break;
          
// enforce valid numbers seperated by -
        
case 'f_date':
          
$formdata[$formkey]=preg_replace('/[^0-9-]/','',$formdata[$formkey]);
          break;
        }
    }
}

/* there are 3 ways to specify a filter on which blog topics to show:
 * 1) ?topicfilter=NR where NR is a decimal number.
 * 2) formdata['f_topic'] an array with all topic ids
 * 3) a bin number with 1 if you want that topic and 0 if not
 * 
 * This functions returns the 3. variant
 */
function get_all_selected_topics($filter_dez$filter_topic_array)
{
  
$result=array();
  
// filter_dez has precedence
  
if (isset($filter_dez) && (@$filter_dez!=0) )
    {
      
// just convert the one dez into bin. That's all
      
$result=nrconvert_dez_to_bin($filter_dez);
    }
  else
    {
      if (isset(
$filter_topic_array) && is_array($filter_topic_array) )
        {
          
$filter_dez=0;
          
// take all dez, sum, convert to bin
          
foreach($filter_topic_array as $topic_id)
            {
              
$filter_dez+=$topic_id;
            }
          
$result=nrconvert_dez_to_bin($filter_dez);
        }
    }

  return 
$result;
}

/* store the content of a posting in a csv file
 * or replace an entry
 * or delete an entry
 */
function txt_store($emailaddr,$filename,$max_line_lenght,$delete_only,$id,$date,$topic,$title,$text,$trackbackstring)
{
  
$mode_desc='';

  
$data_to_write=array();
  
$file_position_to_write=0;
  
// open data file
  
if ($handle1=fopen($filename'r+'))
    {
      
fseek($handle10);
      if (
$id==0)
        {
          if (
$delete_only)
            {
              echo 
"<br />\nERROR: I should delete an entry but got no id";
              exit();
            }
          else
            {
              
$mode_desc='New';
            }
          
// search for a free id
          
$min_free_id=1;
          while (
$tmp_line=fgetcsv($handle1$max_line_lenght))
            {
              
// read id of current line and change min_free_id if it isn't the largest one
              
if ($min_free_id<=$tmp_line[2])
                {
                  
$min_free_id=$tmp_line[2]+1;
                }
            }
          
$id=$min_free_id;
          
$file_position_to_write=ftell($handle1);
        }
      else
        {
          
$mode_desc='Edit';

          
// search for an already existing id to be replaced
          
$found_id=false;
          while (
$tmp_line=fgetcsv($handle1$max_line_lenght))
            {
              
// did we found our id yet?
              
if ($found_id==false)
                {
                  
// Is the current id the searched one?
                  
if ($tmp_line[2]==$id)
                    {
                      
$found_id=true;
                    }
                  else
                    {
                      
// store the last file position that needs no changes
                      
$file_position_to_write=ftell($handle1);
                    }
                }
              else
                {
                  
// all lines after the id will have to be rewritten
                  
$data_to_write[]=$tmp_line;
                }
            }
          if (!
$found_id)
            {
              echo 
"<br />\nERROR: I should delete an entry but I couldn't find an entry with this id";
              exit();
            }
        }
           
      
// We have a posting to save. Add it to the list of unsaved entries
      
if (!$delete_only)
        {
          
$new_line=array();
          
$new_line[0]=$date;
          
$new_line[1]=time();
          
$new_line[3]=$_SERVER["REMOTE_ADDR"];
          
$new_line[2]=$id;
          
$new_line[4]=$topic;
          
$new_line[5]=$title['de'];
          
$new_line[6]=$title['en'];
          
$new_line[7]=$title['fr'];
          
$new_line[8]=$text['de'];
          
$new_line[9]=$text['en'];
          
$new_line[10]=$text['fr'];
          
$new_line[11]=$trackbackstring;
          
send_mail($emailaddr,$mode_desc,$new_line[0],$new_line[1],$new_line[3],$new_line[2],$new_line[4],$new_line[5],$new_line[8],$new_line[6],$new_line[9],$new_line[7],$new_line[10],$new_line[11]);
          
$data_to_write[]=$new_line;
        }
      else
        {
          
$id=0;
          
$mode_desc='Delete';
        }
           
      
// Jump after the last position in the file the stays unchanged
      
if (fseek($handle1$file_position_to_write)==0)
        {
          for (
$c1=0$c1<count($data_to_write); $c1++)
            {
              
$string='';
              
$string.='"'.$data_to_write[$c1][0].'"';
              
$string.=',"'.$data_to_write[$c1][1].'"';
              
$string.=',"'.$data_to_write[$c1][2].'"';
              
$string.=',"'.$data_to_write[$c1][3].'"';
              
$string.=',"'.$data_to_write[$c1][4].'"';
              
$string.=',"'.$data_to_write[$c1][5].'"';
              
$string.=',"'.$data_to_write[$c1][6].'"';
              
$string.=',"'.$data_to_write[$c1][7].'"';
              
$string.=',"'.$data_to_write[$c1][8].'"';
              
$string.=',"'.$data_to_write[$c1][9].'"';
              
$string.=',"'.$data_to_write[$c1][10].'"';
              
$string.=',"'.$data_to_write[$c1][11].'"';
              
$string.="\n";
              
// check that we don't create a line that is too long to be read
              
if (strlen($string)<$max_line_lenght)
                {
                  
fwrite($handle1,$string);
                }
              else
                {
                  echo 
"<br />\nERROR: I should write an entry that is too long";
                  exit(); 
                }
            }
          
// Insert EOF here
          
ftruncate($handle1,ftell($handle1));
        }
      else
        {
          echo 
"<br />\nERROR: Could not jump arround in the data file";
          exit(); 
        }
      
fclose($handle1);
    }
  else
    {
      echo 
"<br />\nERROR: Could not open data file for r/w";
    }
  return 
$id;
}

// load all postings
function txt_load($filename,$max_line_lenght)
{
  
$data=array();
  
// open data file
  
$tmp_old_error_level=error_reporting(0);
  if (!(
$handle1=fopen($filename'r')))
    {
      
error_reporting($tmp_old_error_level);
      
// open failed, try to create file
      
if (($handle1=fopen($filename'a')))
        {
          
fclose($handle1);
          
// OK next try
          
if (!($handle1=fopen($filename'r')))
            {
              echo 
"<br />\nERROR: Could not open data, even after I created the file.";
              exit();
            }
        }
      else
        {
          echo 
"<br />\nERROR: Could not open data file and failed to create it.";
          exit();
        }
    }
  
error_reporting($tmp_old_error_level);
  
// if we reach this line we could open the file
  
$line=array();
  while (
$line=fgetcsv($handle1$max_line_lenght,','))
    {
      
$data[]=$line;
    }
  return 
$data;
}

// get a dez nr and convert it to a bin nr (array with 0/1)
function nrconvert_dez_to_bin($dez)
{
  
// secure parameter
  
if (($dez>=67108864) || ($dez<0) || (($dez-floor($dez))<>0))
    {
      echo 
'Error: Number is out of bound'."\n";
      exit();
    }
  
$bin=array();
  
$pos=0;
  
// find start value for $pos
  
while ((pow(2,$pos))<$dez)
    {
      
$pos++;
    }
  
$leading_zero=true;
  for (
$c1=$pos$c1>=0$c1--)
    {
      
$bin_val=pow(2,$pos);
      
// check if pos is in $dez
      
if (($dez-$bin_val)>=0)
        {
          
$bin[$pos]=1;
          
$dez-=$bin_val;
          
$leading_zero=false;
        }
      else
        {
          if (!
$leading_zero$bin[$pos]=0;
        }
      
$pos--;
    }
  return 
$bin;
}

// get a bin nr (array with 0/1) and convert it to a dez nr
function nrconvert_bin_to_dez($bin)
{
  
$dez=0;
  for (
$c1=0$c1<count($bin); $c1++)
    {
      if (
$bin[$c1])
        {
          
$dez+=pow(2,$c1);
        }
    }
  return 
$dez;
}

/* get a bin nr (array with 0/1) and convert it to a topic list (array)
 * e.g.
 *    dez:   13
 * => bin:   1101
 * => topic: 1, 4, 8
 */
function nrconvert_bin_to_topiclist($bin)
{
  
$result=array();
  for (
$c1=0$c1<count($bin); $c1++)
    {
      if (
$bin[$c1]>0)
        {
          
$result[]=pow(2,$c1);
        }
    }
  return 
$result;
}

/*
 * Get all available topics from our topics data file
 *
 */
function get_topic_data_complete($data_file,$pic_path,$max_line_lenght,$lang)
{
  
$all_topics=array();
  
$pos=0;
  if (
$handle1=fopen($data_file'r'))
    {
      while (
$tmp_line=fgetcsv($handle1$max_line_lenght))
        {
          
$all_topics[$pos]['id']=$tmp_line[0];
          
$all_topics[$pos]['url']=$pic_path.$tmp_line[1];
          switch(
$lang)
            {
            case 
'de':
              
$all_topics[$pos]['desc']=$tmp_line[2];
              break;
            case 
'en':
              
$all_topics[$pos]['desc']=$tmp_line[3];
              break;
            case 
'fr':
              
$all_topics[$pos]['desc']=$tmp_line[4];
              break;
            default:
              echo 
"<br />\nERROR: Unspported language requested";
              exit();
              break;
            }
          
$pos++;
        }
      
fclose($handle1);
    }
  else
    {
      echo 
"<br />\nERROR: Could not open topic-data file for r";
      exit();
    }
  return 
$all_topics;
}

// return the topics matching the topic filter
function get_topic_data($data_file,$pic_path,$max_line_lenght,$lang,$topic_filter)
{
  
$topic_selected=array();
  
$topic_all=array();
  
$topic_all=get_topic_data_complete($data_file,$pic_path,$max_line_lenght,$lang);

  for (
$c1=0$c1<count($topic_all); $c1++)
    {
      
$tmp_topic_id=$topic_all[$c1]['id'];
      if (
array_key_exists$tmp_topic_id-1$topic_filter))
        {
          if (
$topic_filter[$tmp_topic_id-1]==1)
            {
              
$topic_selected[]=$topic_all[$c1];
            }
        }
    }

  return 
$topic_selected;
}

// helper function for usort to sort array() according to array(array(date))
function usort_comp_date($val_1$val_2)
{
  
$comp_a=$val_1[0];
  
$comp_b=$val_2[0];
  
$retVal 0;
  if(
$comp_a $comp_b)
    
$retVal = -1;
  elseif(
$comp_a $comp_b)
    
$retVal 1;
  return 
$retVal;
}

// test if an entry with a given topic list matches a topic filter
function is_within_topic_filter($topic_entry_list$topic_filter_list)
{
  
$result=true;
  for (
$c2=0$c2<count($topic_filter_list); $c2++)
    {
      if (
$topic_filter_list[$c2]==1)
        if (
array_key_exists($c2$topic_entry_list))
          {
            if (
$topic_entry_list[$c2]!=1)
              
$result=false;
          }
        else 
$result=false;
    }
  return 
$result;
}

/* requires a datafilename, topicfilename, path to pics, max linelength, language, topic filter, id_filter
 * returns an array with the data of all matching postings
 */
function get_entry_data($filename_data$filename_topics$pic_path$max_line_lenght$max_line_lenght_topic$lang$topic_filter$id_filter)
{

  
$blog_data=array();
  
$data=txt_load($filename_data,$max_line_lenght);

  
// permanetly resort array according to uasort_comp_date function
  
usort($data"usort_comp_date");

  for (
$c1=0$c1<count($data); $c1++)
    {
      if ((
$id_filter==0) || ($id_filter==$data[$c1][2]))
        {
          
$blog_entry=array();
          
$blog_entry['date']=$data[$c1][0];

         
// skip entries from the future to be able to publish entries in the future
         
if($blog_entry['date']<time() || (session_is_admin()))
         {

          
$blog_entry['lmodified']=$data[$c1][1];
          
$blog_entry['ip']=$data[$c1][3];

          
$blog_entry['id']=$data[$c1][2];
                    
          
$topic_string=$data[$c1][4];
          
$title=array();
          
$title['de']=$data[$c1][5];
          
$title['en']=$data[$c1][6];
          
$title['fr']=$data[$c1][7];
          
$text=array();
          
$text['de']=$data[$c1][8];
          
$text['en']=$data[$c1][9];
          
$text['fr']=$data[$c1][10];
          
$blog_entry['trackback_string']=$data[$c1][11];

          
// restore csv
          
foreach ((array_keys($text)) as $tmp_lang)
            {
              
$text[$tmp_lang]=$text[$tmp_lang];
            }

          
$blog_entry['title']=$title[$lang];
          
$blog_entry['title_all']=$title;
          
$blog_entry['text']=$text[$lang];
          
$blog_entry['text_all']=$text;

          
$topic=nrconvert_dez_to_bin($topic_string);

          
$blog_entry['topic']=get_topic_data($filename_topics,$pic_path,$max_line_lenght_topic,$lang,$topic);

          
// Filter out all topics that don't match topic_filter
          
if (is_within_topic_filter($topic$topic_filter))
            
$blog_data[]=$blog_entry;
         }
        }
    }
  return 
$blog_data;
}

// returns a permanent link to a blog entry 
function get_permanent_link_to_a_blog_entry($backpfad$destpath$entry_id$lang)
{
  
// http://www.tgunkel.de/blog/blog_id_76.de.html
  
$destination=$backpfad.$destpath.'blog_id_'.$entry_id.'.'.$lang.'.html';
  return 
$destination;
}

// returns a permanent html link to a blog entry
function get_permanent_html_link_to_a_blog_entry($backpfad$destpath$entry_id$lang$desc)
{
  
$destinationget_permanent_link_to_a_blog_entry($backpfad$destpath$entry_id$lang);
  
$result='<a href="'.$destination.'">'.$desc.'</a>';
  return 
$result;
}


/* returns html for one link in the topic menu
 * '    '.<span><a href="$linkdst">$linktxt</a></span>
 */
function get_one_topic_menu_link($txt_indent$txt_linkdst$txt_linktxt$logo_pic$logo_desc)
{
  
$txt='';
  
$txt.=$txt_indent.'<span class="blog-menu-item">'."\n";
  
$txt.=$txt_indent.' <a href="';
  
$txt.=$txt_linkdst;
  
$txt.='">';
  if ( 
$logo_pic!='' && $logo_desc!='')
    {
      
$txt.='<img class="imgnobrd" src="'.$logo_pic.'" alt="'.$logo_desc.'" />';
    }

  
$txt.=$txt_linktxt;
  
$txt.='</a>'."\n";
  
$txt.=$txt_indent.' </span>'."\n";
  return 
$txt;
}

/* Display all available topics, offer for each one a checkbox, preselect checkboxes
 *
 * 2^(topic[$i]['id']-1)<=> $selected_topics[$i]
 *     or if not 2^(X-1):
 *    topic[$i]['id']   <=> $selected_topics[$i]
 *
 */
function get_all_topics_for_selection($config$selected_topics$selected_is_pow2$pre_txt$post_txt)
{
  
$txt='';
 
  
$topic_array=get_topic_data_complete($config['topicsdata'],$config['picsdatapath'],$config['topicdata_max_line_length'],$config['lang']);

  
// all topics
  
$txt.='<div class="blog-all-topics-column">'."\n";

  
$txt.=$pre_txt;

  
$txt.='  <div>'."\n";

  for (
$c1=0$c1<count($topic_array); $c1++)
    {
      
$txt.='     <div class="blog-one-topic">';
      
// open the input tag
      // topic nr 5 has a value of 2^4
      
$txt.='<input type="checkbox" name="f_topic[]" value="'.pow(2,$topic_array[$c1]['id']-1).'" ';
      
// which topics are preselected?
      
for ($c2=0$c2<@count($selected_topics); $c2++)
        {
          
// check if the current topic is equal to one of the selected topics
          
if (
              ( (
$selected_is_pow2)  && (pow(2,$topic_array[$c1]['id']-1)==$selected_topics[$c2]) ) ||
              ( (!
$selected_is_pow2) && (      $topic_array[$c1]['id']   ==$selected_topics[$c2]) )
              )
            {
              
$txt.=' checked="checked" ';
              
// set c2 beyond the for limit to leave the for
              
$c2=count($selected_topics)+1;
            }
        }
      
// close the input tag
      
$txt.='/>';
      
$txt.='<a href="'.$config['backpfad'].$config['destpath_noindex'].$config['thisfilename'].'?topicfilter='.pow(2,$topic_array[$c1]['id']-1).'">';
      
$txt.='<img src="'.$topic_array[$c1]['url'].'" alt="'.$topic_array[$c1]['desc'].'"  title="'.$topic_array[$c1]['desc'].'" />';
      
$txt.='</a>';
      
$txt.='</div>'."\n";
    }
  
$txt.='<p style="clear:left;" />';
  
$txt.='  </div>'."\n";

  
$txt.=$post_txt;

  
$txt.='</div>'."\n";
  return 
$txt;
}

/* get some html lines to select the disired topic(s) and some
 * links to blog internals (linke fileupload, calendar, ..
 */
function get_topic_menu($config$topic_filter$id_selected$is_admin$in_calendar)
{
  
$menu_text='';

  
// topics
  
$topic_filter_list=nrconvert_bin_to_topiclist($topic_filter);

  
$button_txt='  <div class="blog-topic-buttons"><input type="submit" value="'.$config['text'][46].'" /></div>'."\n";

  
$pre_txt=' <form action="'.$config['backpfad'].$config['destpath_noindex'].$config['thisfilename'].'" method="get">'."\n";

  
$post_txt=$button_txt;
  
$post_txt.=' </form>'."\n";

  
// links
  
$menu_text.='<div class="blog-menu-bar">'."\n";

  
// offer the stop filtering
  
if (($id_selected!=0) || (count($topic_filter_list)!=0))
    {
      
$menu_text.=get_one_topic_menu_link(' ',
                                          
$config['backpfad'].$config['destpath'].$config['thisfilename'],
                                          
$config['text'][18],
                                          
$config['backpfad'].$config['destpath'].'pics/logo_filter',
                                          
'filter'
                                          
);
    }

  
// link to the calendar view or to the normal view - depending on where you already are
  
if ($in_calendar)
    {
      
// normal
      
$menu_text.=get_one_topic_menu_link(' ',
                                          
$config['backpfad'].$config['destpath'].$config['thisfilename'],
                                          
$config['text'][27],
                                          
$config['backpfad'].$config['destpath'].'pics/logo_default',
                                          
'default');
    }
  else
    {
      
// calendar
      
$menu_text.=get_one_topic_menu_link(' ',
                                          
$config['backpfad'].$config['destpath'].'blogmap.'.$config['lang'].'.html',
                                          
$config['text'][26],
                                          
$config['backpfad'].$config['destpath'].'pics/logo_calendar',
                                          
'cal');
    }

  
// rdf link
  
$menu_text.=get_one_topic_menu_link(' ',
                                      
$config['backpfad'].$config['destpath'].'rss.'.$config['lang'].'.php',
                                      
$config['text'][20],
                                      
$config['backpfad'].$config['destpath'].'pics/logo_rss',
                                      
'RSS Logo');
  
$menu_text.='<br />';
  
$menu_text.=get_one_topic_menu_link(' ',
                                      
$config['backpfad'].$config['destpath'].'rss.'.$config['lang'].'.php'.'?topicfilter='.nrconvert_bin_to_dez($topic_filter),
                                      
$config['text'][48], $config['backpfad'].$config['destpath'].'pics/logo_rss',
                                      
'RSS Logo');

  
// Admin Login                                    
  
if ($is_admin)
    {
      
// new entry
      
$menu_text.=get_one_topic_menu_link(' ',
                                          
$config['backpfad'].$config['destpath_noindex'].$config['thisfilename'].'?mode=new',
                                          
$config['text'][2],
                                          
$config['backpfad'].$config['destpath'].'pics/logo_newentry',
                                          
'New');

      
// fileupload
      
$menu_text.=get_one_topic_menu_link(' ',
                                          
$config['backpfad'].$config['destpath_noindex'].$config['thisfilename'].'?mode=fileupload',
                                          
$config['text'][32],
                                          
$config['backpfad'].$config['destpath'].'pics/logo_upload',
                                          
'Upload'
                                          
);

      
// logout
      
$menu_text.=get_one_topic_menu_link(' ',
                                          
$config['backpfad'].$config['destpath_noindex'].$config['thisfilename'].'?mode=logout',
                                          
$config['text'][5],
                                          
$config['backpfad'].$config['destpath'].'pics/logo_exit',
                                          
'Exit');

    }
  else
    {
      
// admin login
      // jump directly to an entry if you click the login option of an entry
      
if ($id_selected!=0)
        {
          
$menu_text_extra='&amp;id='.$id_selected;
        }
      else
        {
          
$menu_text_extra='';
        }
      
$menu_text.=get_one_topic_menu_link(' ',
                                          
$config['backpfad'].$config['destpath_noindex'].$config['thisfilename'].'?mode=login'.$menu_text_extra,
                                          
$config['text'][6],
                                          
$config['backpfad'].$config['destpath'].'pics/logo_adminlogin'
                                          
'admin');
    }

  
$menu_text.=get_all_topics_for_selection($config$topic_filter_listtrue$pre_txt$post_txt);

  
$menu_text.='</div>'."\n";

  return 
$menu_text;
}

function 
trackback_string_2_idarray($trackbackstring)
{
  if (
$trackbackstring=='') return array();
  
$trackbackstring=preg_replace('/[^0-9\-]/','',$trackbackstring);
  
$result=explode('-',$trackbackstring);
  
sort($result);
  return 
$result;
}

function 
trackack_array2_string($trackbackarray)
{
  return 
implode(',',$trackbackarray);
}

/** 
 * Link to relevant articles
 * 
 * @param trackbackstring String which contains the ids of all relevant articles
 * @param config tgunkel.de config
 * @param lang Current language
 * @param current_id Current id
 * 
 * @return String which all relevant articles
 */
function show_trackback($trackbackstring,$config,$lang,$current_id,$do_reverse_search,$heading_txt)
{
  
$entries=get_entry_data($config['savedata'], $config['topicsdata'], $config['picsdatapath'], $config['savedata_max_line_length'], $config['topicdata_max_line_length'], $lang, array(), 0);

  
$tmp_txt='';
  
$tb_array=trackback_string_2_idarray($trackbackstring);

  if (
$current_id>=0)
    {
      
// reverse search for trackback
      
for($c1=0$c1<count($entries); $c1++)
        {
          
$cur_tb_array=trackback_string_2_idarray($entries[$c1]['trackback_string']);
          for (
$c2=0$c2<count($cur_tb_array); $c2++)
            {
              if (
$cur_tb_array[$c2]==$current_id)
                {
                  
$tb_array[]=$entries[$c1]['id'];
                }
            }
          
        }
      
//sort($tb_array);
      
$tb_array=array_unique($tb_array);
    }

  if (
count($tb_array)>0)
    {
      
$tmp_txt.="\n";
      
$tmp_txt.=$heading_txt;
      
$tmp_txt.='<ul>'."\n";
      
      for(
$tbi=count($tb_array)-1$tbi>=0$tbi--)
        {
          
$tmp_txt.='<li>';
          
$tmp_id=$tb_array[$tbi];
          
$entry_id=-1;
          
// find entry with the right id
          
for($c1=0$c1<count($entries); $c1++)
            {
              if (
$entries[$c1]['id']==$tmp_id)
                {
                  
$entry_id=$c1;
                  break;
                }
            }
          if (
$entry_id==-1)
            {
              
$tmp_txt.='Error: Invalid id: '.$tmp_id;
            }
          else
            {
              
$tmp_title=$entries[$entry_id]['title_all'][$lang];
              if (
$tmp_title!='')
                {
                  
$tmp_txt.=get_permanent_html_link_to_a_blog_entry($config['backpfad'], $config['destpath'], $tmp_id$lang$tmp_title);
                }
              else
                {
                  
// this entry is not availabe for this language, list other languages ...
                  
$tmp_txt.='<ul>';
                  foreach (
$entries[$entry_id]['title_all'] as $tmp_key => $tmp_other_title)
                    {
                      if (
$tmp_other_title!='')
                        {
                          
$tmp_txt.='<li>';
                          
$tmp_txt.=get_permanent_html_link_to_a_blog_entry($config['backpfad'], $config['destpath'], $entries[$c1]['id'], $tmp_keyget_flag_image($config['backpfad'],$tmp_key).$tmp_other_title);
                          
$tmp_txt.='</li>';
                        }
                    }
                  
$tmp_txt.='</ul>';
                }

            }

          
$tmp_txt.='</li>';
        }
      
$tmp_txt.='</ul>'."\n";
    }
  return 
$tmp_txt;
}

?>