<?php

define
('SF_THEME_VERSION','$ bzr-revision-id $');
define('SFIT_WIKI','http://wiki.sfit.dk/');

require_once (
ABSPATH WPINC '/rss-functions.php');

$sf_theme_logo=array('top970fyr.jpg'=>'Fyrtårn''top970demo.jpg'=>'Demo''top970vindmoller.jpg'=>'Vindmøller');
$sf_theme_links=array('sf_toplinie_link_kategori'=>'Toplinie-links','sf_sidemenu_link_kategori'=>'Ekstra sidemenu-links');
$sf_theme_content=array('sf_indhold_top'=>'Øverst på forsiden','sf_indhold_bund'=>'Nederst på siderne');

$sf_theme_box = array(
    
'prew' => '
<div class="box">
  <div class="boxa"><div class="boxb"></div></div>
  <div class="boxcontent">
    <div class="boxbox">
      '
,
    
'pret' => '<h2>',
    
'postt' => '</h2>
      '
,
    
'prel' => '
    </div>
  </div>
  <div class="boxc">
    <div class="boxd">
      '
,
    
'postl' => '',
    
'postw' => '
    </div>
  </div>
</div>'
);

function 
sf_theme_box_top($header=''$type='') {
    global 
$sf_theme_box;
    return 
"\n".str_replace('class="box"''class="box'.(''!=$type?' '.$type:'').'"'$sf_theme_box['prew']) .
            (
''!=$header?$sf_theme_box['pret'].$header.$sf_theme_box['postt']:'');
}

function 
sf_theme_box_bottom($link='') {
    global 
$sf_theme_box;
    return 
$sf_theme_box['prel'].$link.$sf_theme_box['postl'].$sf_theme_box['postw']."\n";
}

function 
sf_theme_editable_authors($authors) {
    global 
$wpdb;
    if (
is_array($authors) && 1==sizeof($authors)) {
        
$user = new WP_User$authors[0]->ID );
        if (
$user->has_cap('edit_others_posts'))
            
$authors $wpdb->get_results"SELECT * FROM $wpdb->users" );
    }
    return 
$authors;
}

function 
sf_theme_pre_get_posts() {
    global 
$wp_query;
    if (
is_home() && !$wp_query->query_vars['cat']
            && 
get_settings('sf_forside_2kolonner') && '-1'!=get_settings('sf_speciel_kategori')) {
        
$wp_query->query_vars['cat']='-'.get_settings('sf_speciel_kategori');
    } elseif (
is_author() && !preg_match('|nej|i', @$_GET['profil']) && get_settings('sf_forfatter_profil')) {
        
$wp_query->query_vars['nopaging']=true;
    }
}

function 
sf_theme_posts_where($where) {
    if (
is_search()) {
        
$where str_replace(" AND () "" "$where);
        
$where str_replace(" AND (post_status = 'publish'"" AND ((post_status = 'static' or post_status = 'publish')"$where);
        
$where str_replace(" AND (post_type = 'post'"" AND ((post_type = 'post' OR post_type='page')"$where);
        if (
sizeof($pages=sf_theme_protected_pages()))
          
$where .= ' AND ID<>' join(' AND ID<>'$pages).' ';
    }
    return 
$where;
}

function 
sf_theme_wp_title($title$sep) {
    global 
$s;
    if (
is_search())
        return 
" $sep Søgning $sep ".htmlspecialchars($s);
    else
        return 
$title;
}

function 
sf_theme_activity_box_end() {
    print 
'</div><div id="sfit-feed">';
    
$rss sf_theme_fetch_rss('http://blog.sfit.dk/kategori/wordpress/feed/rdf/');
    if ( isset(
$rss->items) && != count($rss->items) ) {
        
?><div id="sfit-news"><h3>Nyt om WordPress/SF fra SF's it-politiske netværk <a href="http://blog.sfit.dk/"><?php _e('more'); ?> &raquo;</a></h3><ul><?php
        $rss
->items array_slice($rss->items06);
        foreach (
$rss->items as $item )
            print 
'<li><a title="'wp_specialchars(strip_tags($item['description']), 1) .'" href="'.wp_filter_kses($item['link']).'">'.wp_specialchars($item['title']).'<span class="date">'.mysql2date(get_settings('date_format'),date('Y-m-d',$item['date_timestamp'])).' '.date(get_settings('time_format'),$item['date_timestamp']).'</span></a><br /></li>';
        print 
'</ul></div>';
    }
    print 
'</div><div>';
}

function 
sf_theme_admin_head() {
  print 
'<link rel="shortcut icon" href="'.get_template_directory_uri().'/images/favicon.ico" />';
    print 
'<link rel="stylesheet" type="text/css" href="';
    
bloginfo('template_directory');
    print 
'/wp-admin.css" />';
  print 
"
  <script type='text/javascript'>
  function adresser_onload() {
    var form = document.getElementById('your-profile');
    if (!form)
      return;
    var inputs = form.getElementsByTagName('input');
    for ( var i = 0; i < inputs.length; i++ ) {
      if ( inputs[i].getAttribute('name')!='' ) {
        if ( inputs[i].getAttribute('name') == 'aim' )
          adresser_setNewLabel(inputs[i], 'Adresse');
        if ( inputs[i].getAttribute('name') == 'yim' )
          adresser_setNewLabel(inputs[i], 'Postnummer og by');
        if ( inputs[i].getAttribute('name') == 'jabber' )
          adresser_setNewLabel(inputs[i], 'Telefonnummer');
      }
    }
  }
  function adresser_setNewLabel(input, label) {
    var le = input.parentNode;
    var lt = document.createTextNode (label);
    le.replaceChild(lt, le.firstChild);
  }
  addLoadEvent(adresser_onload);
  </script>
  "
;
}

function 
sf_theme_admin_footer() {
    if(
strpos($_SERVER['REQUEST_URI'], 'post.php')
      || 
strpos($_SERVER['REQUEST_URI'], 'page.php')
        || 
strpos($_SERVER['REQUEST_URI'], 'post-new.php')
            || 
strpos($_SERVER['REQUEST_URI'], 'page-new.php') ) {
        
$o['buttons']=array(array(
            
'start'=>'<h3>',
            
'end'=>'</h3>',
            
'text'=>'Overskrift'
        
));
        echo <<<EOT
<script type="text/javascript">
<!--
    if(sf_themeToolbar = document.getElementById("ed_toolbar")){
        var sf_themeNr, sf_themeBut, sf_themeStart, sf_themeEnd;
        if(sf_themeLookup = document.getElementById("ed_spell")){
            sf_themeToolbar.removeChild(sf_themeLookup);
        }
        if(sf_themeDel = document.getElementById("ed_del")){
            sf_themeToolbar.removeChild(sf_themeDel);
        }
        if(sf_themeIns = document.getElementById("ed_ins")){
            sf_themeToolbar.removeChild(sf_themeIns);
        }
EOT;
        for (
$i 0$i count($o['buttons']); $i++) {
            
$b $o['buttons'][$i];
            
$start preg_replace('![\n\r]+!'"\\n"$b['start']);
            
$start str_replace("'""\'"$start);
            
$end preg_replace('![\n\r]+!'"\\n"$b['end']);
            
$end str_replace("'""\'"$end);
            echo <<<EOT
                            sf_themeStart = '{$start}';
                            sf_themeEnd = '
{$end}';
                            sf_themeNr = edButtons.length;
                            edButtons[sf_themeNr] = new edButton('ed_sf_theme
{$i}','{$b['text']}',sf_themeStart, sf_themeEnd,'');
                            var sf_themeBut = sf_themeToolbar.lastChild;
                            while (sf_themeBut.nodeType != 1){
                                sf_themeBut = sf_themeBut.previousSibling;
                            }
                            sf_themeBut = sf_themeBut.cloneNode(true);
                            sf_themeToolbar.appendChild(sf_themeBut);
                            sf_themeBut.value = '
{$b['text']}';
                            sf_themeBut.title = sf_themeNr;
                            sf_themeBut.onclick = function () {edInsertTag(edCanvas, parseInt(this.title));}
                            sf_themeBut.id = "ed_sf_theme
{$i}";
EOT;
        }
        echo <<<EOT
    }
//-->
</script>
EOT;
    }
};

function 
sf_theme_admin_notices() {
    
$title=html_entity_decode(get_admin_page_title());
    if (!
seems_utf8($title))
        
$title=utf8_encode($title);
    
$title=ucfirst(sanitize_title($title));
    
$title=preg_replace('|-([a-z])|e','strtoupper($1)',$title);
    print 
'<div id="sf-help"><a title="'.get_admin_page_title().'" href="'.SFIT_WIKI.'WordPressHj%C3%A6lp/Administration/'.$title.'">SF-Hjælp</a></div>';
};

function 
sf_theme_admin_menu() {
    global 
$sf_theme_links$sf_theme_content;

    
$page 'sf_theme';
    if ( 
$_GET['page'] == $page ) {
        if ( 
'update' == $_REQUEST['action'] ) {
            
$options = array(
              
'sf_forside_top'=>'',
              
'sf_forside_profil'=>'',
              
'sf_forside_forfatter'=>'',
              
'sf_forside_2kolonner'=>'',

              
'sf_speciel_kategori'=>'',
              
'sf_forside_arkiv'=>'',
              
'sf_forside_kalender'=>'',

              
'sf_top_billede'=>'',
              
'sf_forfatter_dato_separat'=>'',

              
'sf_forfatter_profil'=>'',
              
'sf_historiske_aktiviteter'=>'',
              
'sf_linkede_datoer'=>'',
              
'sf_medlemmer_brugernavn'=>'',
              
'sf_medlemmer_adgangskode'=>'',
              
'sf_interesser_tekst'=>'');
            foreach (
$options as $k => $v)
                
$options[$k]=@$_POST[$k];
            foreach (
$sf_theme_links as $k => $v)
                
$options[$k]=@$_POST[$k];
            foreach (
$sf_theme_content as $k => $v)
                
$options[$k]=stripslashes(@$_POST[$k]);
            
$options['sf_speciel_kategori']=@$_POST['cat'];
            foreach (
$options as $option => $value) {
                if (!
$value)
                    
$value='';
                
update_option($option$value);
            }
            
header("Location: edit.php?page=$page&saved=true");
            die;
        }
    }
    
add_submenu_page('edit.php''Layout-opsætning''Layout'5$page'sf_theme_page');

}

function 
sf_theme_page() {
    global 
$wpdb$sf_theme_links$sf_theme_content$sf_theme_logo;

    if ( 
$_REQUEST['saved'] )
        print 
'<div id="message" class="updated fade"><p><strong>Opsætningen er nu gemt.</strong></p></div>';
    
  
$linkcats = array();
  if (
function_exists('get_terms')) {
      
$results get_terms('link_category''hide_empty=0');
      foreach (
$results as $t => $o) {
          
$results[$t]->ID $o->term_id;
          
$results[$t]->cat_name $o->name;
      }
    }
    elseif (
''!=$wpdb->link2cat)
    
$results $wpdb->get_results("SELECT cat_ID as ID, cat_name FROM $wpdb->categories ORDER BY cat_name");
    else
    
$results $wpdb->get_results("SELECT cat_id as ID, cat_name FROM $wpdb->linkcategories ORDER BY cat_name");
  foreach (
$results as $row)
      
$linkcats[$row->ID] = wp_specialchars($row->cat_name);
?>
<div class='wrap'>
<h2>Layout-opsætning</h2>
<div id="your-profile">
    <form id="sf_theme" method="post">
        <fieldset id="sf-forside">
            <legend>Forside<legend>
            <label for="sf_forside_top">Øverst:</label>
            <br/>
            <select name="sf_forside_top">
            <?php
        $top
=array('auto'=>'Automatisk (HTML, ellers indlæg)''html'=>'HTML''artikel'=>'Seneste indlæg');
        while (list(
$id,$name)=each($top)) {
            print 
'<option ';
            if (
get_settings('sf_forside_top')==$id)
                print 
' selected="selected"';
            print 
'value="'.$id.'">'.$name.'</option>';
        }
            
?>
            </select>
            <br/>
            <?php if ( $authors $wpdb->get_results('SELECT ID, display_name FROM '.$wpdb->users.' JOIN '.$wpdb->usermeta.' WHERE ID=user_id AND meta_key="sf_theme_image" AND meta_value>0 ORDER BY display_name') ) : ?>
            <label for="sf_forside_profil">Profil under toppen:</label>
            <br/>
            <select name="sf_forside_profil" id="sf_forside_profil">
                <option <?php if (!get_settings('sf_forside_profil')) print 'selected="selected"'?> value="0">Ingen</option>
      <?php 
      
foreach ($authors as $o) {
              print 
'<option ';
              if (
get_settings('sf_forside_profil')==$o->ID)
                  print 
' selected="selected"';
        
$o get_userdata$o->ID );
              print 
'value="'.$o->ID.'">'.$o->display_name.'</option>';        
      }
            
?>
            </select>
            <br/>
      <?php endif; ?>            
            <input id="sf_forside_forfatter" name="sf_forside_forfatter" type="checkbox" value="1" <?php if (get_settings('sf_forside_forfatter')) print 'checked="checked"'?>" />
            <label for="sf_forside_forfatter">Vis forfatternavn?</label>
            <br/>
            <input id="sf_forside_2kolonner" name="sf_forside_2kolonner" type="checkbox" value="1" <?php if (get_settings('sf_forside_2kolonner')) print 'checked="checked"'?> />
            <label for="sf_forside_2kolonner">2 kolonner?</label>
        </fieldset>
        <fieldset id="sf-layout">
            <legend>Layout<legend>
            <?php foreach($sf_theme_links as $v => $l) { ?>
              <label for="<?php print $v?>"><?php print $l?>:</label>
              <br/>
              <select id="<?php print $v?>" name="<?php print $v?>">
                <option <?php if (!get_settings($v)) print ' selected="selected"'?> value="0">Ingen</option>
                <?php 
                reset
($linkcats);
                while (list(
$id,$name)=each($linkcats)) {
                    print 
'<option ';
                    if (
get_settings($v)==$id)
                        print 
' selected="selected"';
                    print 
'value="'.$id.'">'.$name.'</option>';
                }
                
?>
              </select>
              <br/>
            <?php ?>
<label for="sf_top_billede">Top-billede:</label>
<br/>
<select id="sf_top_billede" name="sf_top_billede">
<?php 
foreach ($sf_theme_logo as $id => $name) {
    print 
'<option ';
    if (
get_settings('sf_top_billede')==$id)
        print 
' selected="selected"';
    print 
'value="'.$id.'">'.$name.'</option>';
}
?>
</select>
<br/>
            <input id="sf_forfatter_dato_separat" name="sf_forfatter_dato_separat" type="checkbox" value="1" <?php if (get_settings('sf_forfatter_dato_separat')) print 'checked="checked"'?> />
            <label for="sf_forfatter_dato_separat">Vis navn og dato separat?</label>
        </fieldset>
        <fieldset id="sf-2kolonner">
            <legend>2 kolonner<legend>
            <label for="cat">Højre kolonne:</label>
            <br/>
            <?php dropdown_cats(0'''count''desc'001trueget_settings('sf_speciel_kategori')); ?>
            <br/>
            <input id="sf_forside_arkiv" name="sf_forside_arkiv" type="checkbox" value="1" <?php if (get_settings('sf_forside_arkiv')) print 'checked="checked"'?> />
            <label for="sf_forside_arkiv">Vis arkiv-oversigt nederst til venstre?</label>
            <br/>
            <input id="sf_forside_kalender" name="sf_forside_kalender" type="checkbox" value="1" <?php if (get_settings('sf_forside_kalender')) print 'checked="checked"'?>" />
            <label for="sf_forside_kalender">Vis kalender-uddrag nederst til højre?</label>
        </fieldset>
        <fieldset id="sf-funktioner">
            <legend>Funktioner<legend>
            <input id="sf_forfatter_profil" name="sf_forfatter_profil" type="checkbox" value="1" <?php if (get_settings('sf_forfatter_profil')) print 'checked="checked"'?> />
            <label for="sf_forfatter_profil">Vis billede og profil på forfatterside?</label>
            <br/>
            <input id="sf_linkede_datoer" name="sf_linkede_datoer" type="checkbox" value="1" <?php if (get_settings('sf_linkede_datoer')) print 'checked="checked"'?> />
            <label for="sf_linkede_datoer">Vis datoer som links?</label>
            <br/>
            <label for="sf_medlemmer_brugernavn">Brugernavn til medlemssider:</label>
            <br/>
            <input id="sf_medlemmer_brugernavn" name="sf_medlemmer_brugernavn" type="text" value="<?php print get_settings('sf_medlemmer_brugernavn'); ?>" />
            <br/>
            <label for="sf_medlemmer_adgangskode">Adgangskode til medlemssider:</label>
            <br/>
            <input id="sf_medlemmer_adgangskode" name="sf_medlemmer_adgangskode" type="text" value="<?php print get_settings('sf_medlemmer_adgangskode'); ?>" />
            <br/>
            <label for="sf_interesser_tekst">Tekst før interesser (brugervalgte emner):</label>
            <br/>
            <input id="sf_interesser_tekst" name="sf_interesser_tekst" type="text" value="<?php print get_settings('sf_interesser_tekst'); ?>" />
            <br/>
            <label for="sf_historiske_aktiviteter">Linktekst til historiske aktiviteter:</label>
            <br/>
            <input id="sf_historiske_aktiviteter" name="sf_historiske_aktiviteter" type="text" value="<?php print get_settings('sf_historiske_aktiviteter'); ?>" />
        </fieldset>
        <br style="clear: left" />
        <?php foreach($sf_theme_content as $v => $l) { ?>
        <fieldset id="<?php print $v?>_fieldset">
            <legend><?php print $l?><legend>
            <label for="<?php print $v?>">HTML:</label>
            <br/>
            <textarea id="<?php print $v?>" name="<?php print $v?>" rows="5" cols="40" style="width: 99%"><?php print get_settings($v); ?></textarea>
            <br/>
            <label>Eksempel:</label>
            <br/>
            <?php print get_settings($v); ?>
        </fieldset>
        <?php ?>
        <div class="submit">
            <input type="hidden" name="action" value="update" />
            <input type="submit" class="defbutton" name="submitform" value="Opdatér" />
        </div>
    </form>
</div>
</div>
<?php
}

function 
sf_theme_sanitize_text($txt) {
    
$txt=str_replace('</p>',"\n",$txt);
    
$txt=preg_replace('|<br\s*?/>|',"\n",$txt);
    
$txt=preg_replace("|\n+|","\n",$txt);
    
$txt=trim(strip_tags($txt));
    if (
strlen($txt)>300 && preg_match('|^(.+?\s[^\.\d]+?[\.!?:])(\s+[A-Z\d].*)$|m',$txt,$M)) {
        
$newtxt=$M[1];
        
$txt=$M[2];
        while (
preg_match('|^(.+?\s[^\.\d]+?[\.!?:])(\s+[A-Z\d].*)$|m',$txt,$M) && ((strlen($newtxt)+strlen($M[1]))<300)) {
            
$newtxt.=' '.$M[1];
            
$txt=$M[2];
        }
        
$txt=str_replace('[...]','[&#8230;]',$newtxt);
        if (
false===strpos($txt'[&#8230;]'))
            
$txt.=' [&#8230;]';
    } else {
      
$txt=preg_replace('|\s+&#8230;\s*?$|s','',$txt);
  }
    
$txt='<p>'.str_replace("\n",'</p> <p>',$txt).'</p>';
    
$txt=str_replace('<p></p>','',$txt);
    return 
$txt;
}

function 
sf_theme_split_content($excerpt=false) {
  global 
$post;
    
$content trim($post->post_content);
    if (!
$excerpt)
      return array(
''str_replace(']]>'']]&gt;'apply_filters('the_content'$content)));
    if (
''!=trim($post->post_excerpt)) {
      
$txt apply_filters('the_excerpt'$post->post_excerpt);
    return array(
sf_theme_sanitize_text($txt), str_replace(']]>'']]&gt;'apply_filters('the_content'$content)));
    }
    if (
preg_match('|^(.+?)<!--more-->(.+?)$|s'$content$M))
      return array(
str_replace(']]>'']]&gt;'apply_filters('the_content'$M[1])), str_replace(']]>'']]&gt;'apply_filters('the_content'$M[2])));
    
$txt='';
  
$content str_replace(']]>'']]&gt;'apply_filters('the_content'$content));
    if (
preg_match('|^<p>(.+?)</p>(.*)?$|m',$content,$M) && (strlen($M[1])<300)) {
        while (
preg_match('|^<p>(.+?)</p>(.*)?$|m',$content,$M) && ((strlen($txt)+strlen($M[1]))<300)) {
            
$txt=$M[1].' <br />';
            
$content=$M[2];
        }
    } elseif (
strlen($content)>300)
        return array(
sf_theme_sanitize_text($content), $content);
    return array(
sf_theme_sanitize_text($txt), $content);
}

function 
sf_theme_get_the_teaser($linked=true) {
    list(
$txt,$content) = sf_theme_split_content(true);
    if (
false===strpos($txt'[&#8230;]')) {
      if (
preg_match('|^(.+?)\s*</p>$|s'trim($txt), $M))
        
$txt $M[1] . ' [&#8230;]</p>';
      else
        
$txt.=' [&#8230;]';
    }
    if (
$linked)
      
$txt=str_replace('[&#8230;]'' [<a href="'.get_permalink().'" title="'.get_the_title().'">&#8230;</a>]'$txt);
    return 
$txt;
}

function 
sf_theme_get_the_content($complete=true) {
    list(
$txt,$content) = sf_theme_split_content(!$complete);
    return 
$content;
}

function 
sf_theme_the_content($content) {
    
$content=preg_replace_callback('|(<p>)?\(\(sfbruger:([^\)\s]+)\)\)(</p>)?|'create_function(
        
'$matches''
        $user = get_userdatabylogin($matches[2]);
        if ($user) {
          if (""!=($interests=get_settings("sf_interesser_tekst"))) {
              $ilist = preg_split("/,/", get_user_option("sf_theme_interests", $user->ID), -1, PREG_SPLIT_NO_EMPTY);
              if (sizeof($ilist)) {
                  foreach ($ilist as $i => $interest)
                      $ilist[$i] = "<a href=\"" . get_category_link($interest) . "\">" . get_the_category_by_ID($interest) . "</a>";
                    $interests = " (" . $interests . ": " . join(", ", $ilist) . ")";
                } else
                  $interests="";
          }
            return "<div class=\"vcard\">" . sf_theme_linked_author_name($user) . $interests . sf_theme_the_address($user->ID) . "</div>";
        }
        '
), $content);
    
$content preg_replace('|</?font[^>]*?>|i'''$content);
    return 
$content;
}

function 
sf_theme_the_address($userid) {
    
$authordata get_userdata($userid);
    if (!(
''!=$authordata->yim && ''!=$authordata->aim && ''!=$authordata->jabber || ''!=$authordata->sf_theme_address))
      return 
'<div class="email">' $authordata->user_email '</div>';
    
$a '<div><div class="adr">';
    if (
''!=$authordata->yim && ''!=$authordata->aim && ''!=$authordata->jabber)
      
$a .= '<span class="street-address">'.$authordata->aim.'</span><br/>'.
          
'<span class="postal-code">'.$authordata->yim.'</span><br/>'.
          
'<span class="tel">'.$authordata->jabber.'</span><br/>';
    else
      
$a .= nl2br($authordata->sf_theme_address);
    
$a .= '</div><div class="email">' $authordata->user_email '</div></div>';
    return 
$a;
}

function 
sf_theme_query_vars($qv) {
    global 
$wp;
    
parse_str($wp->matched_query$q);
    if (isset(
$q['pagename']) && isset($q['feed'])) {
        global 
$wpdb;
        if (
'feed'==$q['feed'] && 'kalender.php'==$wpdb->get_var('SELECT meta_value FROM `'.$wpdb->posts.'` LEFT JOIN `'.$wpdb->postmeta.'` ON ID=post_ID WHERE post_name = "'.$wpdb->escape($q['pagename']).'" AND meta_key = "_wp_page_template" LIMIT 1')) {
            global 
$feed$cache_lastpostmodified$sf_theme_events_table;
            
$feed='ical';
            
$lc=$wpdb->get_var("SELECT created FROM $sf_theme_events_table ORDER BY created DESC LIMIT 1");
          
$lm=$wpdb->get_var("SELECT modified FROM $sf_theme_events_table ORDER BY modified DESC LIMIT 1");
          if (
$lc>$lm)
            
$lm=$lc;
            if (
''!=$lm)
                
$cache_lastpostmodified['GMT']=gmdate('Y-m-d H:i:s',mysql2date('U',$lm));
        }
    }
    return 
$qv;
}

function 
sf_theme_template_redirect() {
    global 
$feed;
    
    if (
'ical'==$feed) {
        
sf_theme_events_ical();
        exit;
    }
}

function 
sf_theme_get_event_page($return_pid=false) {
    global 
$wpdb;
    
$pid=$wpdb->get_var('SELECT ID FROM `'.$wpdb->posts.'` LEFT JOIN `'.$wpdb->postmeta.'` ON ID=post_ID WHERE meta_key = "_wp_page_template" AND meta_value = "kalender.php" LIMIT 1');
    if (
$pid && $return_pid)
        return 
$pid;
    elseif (
$pid)
      return 
get_permalink($pid);
    else
      return 
get_option('siteurl');
}

function 
sf_theme_fetch_rss($url) {
    require_once (
ABSPATH WPINC '/rss-functions.php');
    
$rss fetch_rss($url);
    if ( isset(
$rss->items) && is_array($rss->items) && != count($rss->items) ) {
        foreach (
$rss->items as $i => $item) {
            if (!isset(
$item['date_timestamp']) && isset($item['dc']['date']))
                
$item['date_timestamp'] = @parse_w3cdtf($item['dc']['date']);
            elseif (!isset(
$item['date_timestamp']) && isset($item['pubdate']))
                
$item['date_timestamp'] = @strtotime($item['pubdate']);
            
$rss->items[$i] = $item;
        }
    }
    return 
$rss;
}

function 
sf_theme_fix_feed_item($item) {
    while ( 
strstr($item['link'], 'http') != $item['link'] )
        
$item['link'] = substr($item['link'], 1);
    
$item['link'] = wp_specialchars(strip_tags($item['link']), 1);
    
$item['title'] = wp_specialchars(strip_tags($item['title']), 1);
    
$item['title'] = preg_replace('"&(amp|#038);([^;\s]+);"','&$2;',$item['title']);
    if ( empty(
$item['title']) )
        
$item['title'] = __('Untitled');
    if (!
seems_utf8($item['title']))
      
$item['title'] = utf8_encode($item['title']);
    
$summary $description str_replace(array("\n""\r"), ' 'wp_specialchars(strip_tags($item['description']), 1));
    if (empty(
$description) && !empty($item['content']['encoded']))
        
$summary $description str_replace(array("\n""\r"), ' 'wp_specialchars(strip_tags($item['content']['encoded']), 1));
    if (empty(
$description) && !empty($item['summary']))
        
$summary $description str_replace(array("\n""\r"), ' 'wp_specialchars(strip_tags($item['summary']), 1));
    if (!empty(
$item['content']['encoded']) && preg_match('|(<img[^>]+?>)|',$item['content']['encoded'],$M))
        
$summary $M[1];
    
$summary preg_replace('"&(amp|#038);([^;\s]+);"','&$2;',$summary);
    if (!
seems_utf8($summary))
      
$summary utf8_encode($summary);
    
$description preg_replace('"&(amp|#038);([^;\s]+);"','&$2;',$description);
    if (!
seems_utf8($description))
      
$description utf8_encode($description);
    
$item['summary'] = $summary;
    
$item['description'] = $description;
    if (!isset(
$item['date_timestamp']) && isset($item['modified']))
        
$item['date_timestamp'] = parse_w3cdtf($item['modified']);
    elseif (!isset(
$item['date_timestamp']) && isset($item['created']))
        
$item['date_timestamp'] = parse_w3cdtf($item['created']);
    if (isset(
$item['date_timestamp']))
        
$item['date'] = date('j/n H:i',$item['date_timestamp']);
    else
        
$item['date'] = '';
    return 
$item;
}

function 
sf_theme_profile($author) {
  
$description nl2br($author->user_description);
  return 
'<p class="profile">' sf_theme_linked_author_image($author).
         (
''!=$description?'<span class="profile_description">' $description '</span>':'') . '</p>' ;
}

function 
sf_theme_linked_author_image($author) {
  global 
$wpdb;
  
$src htmlspecialchars($wpdb->get_var"SELECT guid FROM $wpdb->posts WHERE ID='".get_user_option('sf_theme_image'$author->ID)."'" ), ENT_QUOTES);
  if (!
$src)
      return 
'';
  return 
sf_theme_linked_author_name($author$src);
}

function 
sf_theme_linked_author_name($author$imgsrc='') {
  
$title htmlspecialchars($author->display_nameENT_QUOTES);
  if (
is_author())
    
$link htmlspecialchars('http://'!=get_the_author_url()?get_the_author_url():'');
  elseif (
get_usernumposts($author->ID))
    
$link htmlspecialchars(get_author_link(0$author->ID$author->user_nicename), ENT_QUOTES);
  elseif (
''!=$author->user_url && 'http://'!=$author->user_url)
    
$link htmlspecialchars($author->user_url);
  else
    
$link '';
  if (
''!=$link)
    return 
'<a '.(''!=$imgsrc?'':'class="fn url" ').'href="'$link .'" title="'$title '">'.(''!=$imgsrc?'<img class="photo profile_image" src="' $imgsrc '" alt="' $title '" />':$title).'</a>';
  return (
''!=$imgsrc?'<img class="photo profile_image" src="' $imgsrc '" alt="' $title '" />':$title);
}

function 
sf_theme_postmeta($forceauthor=false) {
  return 
'<span class="postmeta'.(get_option('sf_forfatter_dato_separat')?' postmetaseparate':'').'">'.sf_theme_authorspan($forceauthor).sf_theme_datespan().'</span>';
}

function 
sf_theme_datespan($dt=0) {
  if (
get_settings('sf_linkede_datoer')) {
      if (!
$dt)
          
$dt get_the_time('U');
       list(
$y$m$d) = array(date('Y'$dt), date('m'$dt), date('j'$dt));
    
$date '<a href="' get_day_link($y$m$d) . '">' $d '.</a> ';
    
$date .= '<a href="' get_month_link($y$m) . '">' mysql2date('F'date('Y-m-d H:i:s'$dt)) . '</a> ';
    
$date .= '<a href="' get_year_link($y) . '">' $y '</a>';
  } else
    
$date get_the_time(get_settings('date_format'));
  return 
'<span class="date">'.$date.'</span>';
}

function 
sf_theme_authorspan($force=true) {
  global 
$post;
  if (!(
$sf_forside_forfatter=get_settings('sf_forside_forfatter')) && !$force)
    return 
'';
  
$authordata=get_userdata($post->post_author); 
  return 
'<span class="author">Af: '.sf_theme_linked_author_name($authordata).'</span>';
}

function 
sf_theme_profile_personal_options() {
  global 
$profileuser$wpdb;
  
$images $wpdb->get_results"SELECT * FROM $wpdb->posts WHERE (post_status = 'attachment' or post_type = 'attachment') and post_title = '".$wpdb->escape($profileuser->display_name)."' and post_mime_type like 'image/%'" );
  
?>
  <fieldset>
  <legend>Interesser</legend>
  <input type="hidden" name="sf_theme_user_id" value="<?php echo $profileuser->ID?>" />
  <div>
  <p class="desc">Politikområder:</p>
  <?php sf_theme_user_cats(split(',',get_user_option('sf_theme_interests'$profileuser->ID)), get_nested_categories()); ?>
  </div>
  </fieldset>
  <fieldset>
  <legend>Billede og lang profiltekst</legend>
  <?php if (''==get_user_option('yim'$profileuser->ID) && ''==get_user_option('aim'$profileuser->ID) && ''==get_user_option('jabber'$profileuser->ID)) { ?>
  <p>
  <label for="sf_theme_user_address">Adresse (brug separate adressefelter under "Kontaktinformationer" hvis muligt):</label>
  <br/>
  <textarea name="sf_theme_user_address" rows="3" cols="30"><?php echo get_user_option('sf_theme_address'$profileuser->ID); ?></textarea>
  </p>
  <?php ?>
  <?php
  
if (is_array($images) && sizeof($images)) {
    print 
'<p><label>Profilbillede:</label><br/>';
    foreach (
$images as $image)
      print 
'<label><input type="radio" '.($image->ID==get_user_option('sf_theme_image'$profileuser->ID)?'checked="checked"':'').' name="sf_theme_user_image" value="'.$image->ID.'" style="width: inherit"/><img src="'.$image->guid.'" alt="" /></label></p>';
  } else {
    print 
'<div class="error"><p>Der er ingen billeder med navnet "'.$profileuser->display_name.'", upload evt. et nyt billede.</p></div>';
  }
  
?>
  <p>
  <label for="sf_theme_user_feed">URL til eksternt artikel-feed:
  <br/>
  <input type="text" name="sf_theme_user_feed" value="<?php echo get_user_option('sf_theme_feed'$profileuser->ID); ?>"/>
  </label>
  </p>
  <p>
  <label for="sf_theme_user_description">Tekst der bliver vist på din personlige side (HTML muligt):</label>
  <textarea name="sf_theme_user_description" rows="10" cols="30"><?php echo get_user_option('sf_theme_description'$profileuser->ID); ?></textarea>
  </p>
  </fieldset>  
  <?php
}

function 
sf_theme_user_cats($interests$cats) {
  foreach (
$cats as $category) {
    echo 
'<label for="category-'$category['cat_ID'], '" class="interest selectit"><input value="'$category['cat_ID'], '" type="checkbox" name="sf_theme_user_interest[]" id="category-'$category['cat_ID'], '"', (in_array($category['cat_ID'], $interests) ? ' checked="checked"' ""), '/> 'wp_specialchars($category['cat_name']), "</label>\n";
    if (
sizeof($category['children'])) {
      echo 
"\n<span class='cat-nest'>\n";
      
sf_theme_user_cats($interests$category['children']);
      echo 
"</span>\n";
    }
  }
}

function 
sf_theme_personal_options_update() {
  global 
$wpdb;
  if (!isset(
$_POST['sf_theme_user_id']))
    return;
  if (
is_array($_POST['sf_theme_user_interest']))
    
$_POST['sf_theme_user_interest']=join(',',$_POST['sf_theme_user_interest']);
  
update_usermeta($_POST['sf_theme_user_id'], 'sf_theme_interests'$_POST['sf_theme_user_interest']);
  
update_usermeta($_POST['sf_theme_user_id'], 'sf_theme_address'$_POST['sf_theme_user_address']);
  
update_usermeta($_POST['sf_theme_user_id'], 'sf_theme_image'$_POST['sf_theme_user_image']);
  
update_usermeta($_POST['sf_theme_user_id'], 'sf_theme_feed'$_POST['sf_theme_user_feed']);
  
update_usermeta($_POST['sf_theme_user_id'], 'sf_theme_description'$_POST['sf_theme_user_description']);
}

function 
sf_theme_protected_pages() {
    global 
$wpdb;
    
# Find sider der bruger medlems-skabelon.
    
$prot $wpdb->get_results('SELECT DISTINCT post_id FROM '.$wpdb->postmeta.' WHERE meta_key = "_wp_page_template" AND meta_value = "medlemmer.php"');
    
$exclude = array();
    if (
sizeof($prot)) {
        
# Find underliggende sider.
        
$epages = array();
        foreach (
$prot as $m)
            
$epages[] = $m->post_id;
        
$exclude $epages;
        while (
$prot $wpdb->get_results('SELECT DISTINCT ID FROM '.$wpdb->posts.' WHERE (post_status="static" OR post_type="page") AND (post_parent='.join(' OR post_parent='$epages).')')) {
            
$epages = array();
            foreach (
$prot as $m)
                
$epages[] = $m->ID;
            
$exclude=array_unique(array_merge($exclude,$epages));
        }
    }
    return 
$exclude;
}

function 
sf_theme_topline_pages() {
    global 
$wpdb;
    
# Find sider der bruger toplinie-skabelon.
    
$top $wpdb->get_results('SELECT DISTINCT post_id FROM '.$wpdb->postmeta.' WHERE meta_key = "_wp_page_template" AND meta_value = "toplinie.php"');
    
$pages = array();
    foreach (
$top as $m)
        
$pages[] = $m->post_id;
    return 
$pages;
}

function 
sf_theme_init() {

    
add_action('pre_get_posts''sf_theme_pre_get_posts');
    
add_action('posts_where''sf_theme_posts_where');
    
add_action('admin_head''sf_theme_admin_head');
    
add_action('admin_footer''sf_theme_admin_footer');
    
add_action('admin_notices''sf_theme_admin_notices');
    
add_action('admin_menu''sf_theme_admin_menu');
    
add_action('activity_box_end''sf_theme_activity_box_end');
    
add_action('profile_personal_options''sf_theme_profile_personal_options');
    
add_action('personal_options_update''sf_theme_personal_options_update');
    
add_action('edit_user_profile''sf_theme_profile_personal_options');
    
add_action('check_passwords''sf_theme_personal_options_update');

    
add_filter('get_editable_authors''sf_theme_editable_authors');
    
add_filter('the_content''sf_theme_the_content');

    
add_filter('wp_title''sf_theme_wp_title'02);
    
add_filter('query_vars''sf_theme_query_vars');
    
add_action('template_redirect''sf_theme_template_redirect');

    
$sf_theme_version get_option('sf_theme_version');
    if (!
$sf_theme_version || $sf_theme_version != SF_THEME_VERSION) {
      
// Upgrade...
      
update_option(sf_theme_versionSF_THEME_VERSION);
    }

}

include_once(
TEMPLATEPATH '/events.php');
include_once(
TEMPLATEPATH '/widgets.php');

add_action('init''sf_theme_init');

?>