root > WikiSense-trunk > attic > CatTreeLight.php

CatTreeLight.php

application/x-php, 22678 bytes (load raw)
<?php

/************************************************
*  NOTE: TO ADOPT THIS SCRIPT TO YOUR SYSTEM,
*  GO TO THE SECTION MARKED "SETUP" BELOW!
*************************************************
*  NOTE: This tool requires MediaWiki 1.5 or
*        later to be installed and accessable.
*************************************************/


/*
CatTreeLight shows the category structure of a MediaWiki
as a dynamic tree.
Copyright (C) 2005, Daniel Kinzler, brightbyte.de

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/


#### SETUP ############################################################

    # Name of the root category.
    # use '_' instead of space in the name!
    $ctlRoot= 'Root';
   
    # mediawiki installation path:
    # (ignored if CatTreeLight is used as a library)
    $ctlMediaWiki= '.';
   
    # wiki database:
    # (ignored if CatTreeLight is used as a library)
    $ctlDB= array(
        'type' =>     'mysql',        # type of database
        'user' =>     'yourname',     # your database user
        'password' => 'yourpassword', # your database password
        'host' =>     'localhost',    # your database server
        'dbname' =>   'wiki',         # your wiki database
    );

#### INIT ################################################

if (defined('WS_WEB')) {
    define('CTL_WIKISENSE');
    define('CTL_AS_LIB');
}
else if (defined('MEDIAWIKI')) {
    define('CTL_MEDIAWIKI');
    define('CTL_AS_LIB');
}
else if (file_exists('WSInit.php')) {
    define('CTL_WIKISENSE');
    define('CTL_STANDALONE');
   
    define("WS_WEB",true);
    require_once( "WSInit.php" );
}

if (defined('CTL_WIKISENSE') && !$ctlDB) {
    $ctlDB= $wsgWikiDB;
}

if (!defined('CTL_MEDIAWIKI') && !defined('CTL_WIKISENSE') && $ctlMediaWiki) {
    ini_set('include_path', ini_get('include_path') . ":$wsgMediaWiki:$wsgMediaWiki/includes");
    $IP= $wsgMediaWiki;
 
    if (!defined('MEDIAWIKI')) define( 'MEDIAWIKI', true );

    require_once( 'includes/Defines.php' );
    require_once( 'includes/DefaultSettings.php' );
    require_once( 'includes/Namespace.php' );
    require_once( 'includes/WebRequest.php' );
    require_once( 'includes/Sanitizer.php' );
    require_once( 'includes/GlobalFunctions.php' );
    require_once( 'includes/DatabaseFunctions.php' );
    require_once( 'languages/Names.php' );
}

class CatTreeLight {
    var $db;

    function CatTreeLight( &$db ) {
        $this->db=& $db;
    }

    function printSection($cat, $node, $stub, $articles = false) {
      global $wsgCatTreeText;
   
      if ($stub) {
        $js= "javascript:expandNode('".addslashes($cat)."','$node');";
        $txt= "+";
      }
      else {
        $js= "javascript:collapseNode('".addslashes($cat)."','$node');";
        $txt= "&ndash;";
      }
     
      global $wikiInfo, $sectionLoadURL, $terse, $terseTarget;
      $label= escapeHtml(str_replace('_',' ',$cat));
     
      $wikiLink= NULL;
     
      if ($wikiInfo && $wikiInfo->baseURL) {
        $wikiLink= $wikiInfo->baseURL . '?title=Category:' . urlencode($cat);
      }
     
      $n= NULL;
     
      ?>
      <div class='section' id='<?="section-$node"?>'>
        <div class='sectionhead'>
          [<a href="<?=$js?>" id='<?="link-$node"?>' title='load' <?= $stub ? "" : "class='loaded'" ?>><?=$txt?></a>]
         
          <? if ($terse): ?>
            <span class='label'>
              <a href='<?=$wikiLink?>' <?= $terseTarget ?>><?=$label?></a>
            </span>
           
            <span class='links'>
              <a href="<?="$sectionLoadURL&amp;cat=".urlencode($cat)?>" target='_self'>^</a>
            </span>
          <? else: ?>
            <span class='label'>
              <?=$label?>
            </span>
           
            <span class='links'>
              [<a href='<?=$wikiLink?>'><?=escapeHtml($wikiInfo->family)?></a>]
              [<a href="<?="$sectionLoadURL&amp;cat=".urlencode($cat)?>"><?= $wsgCatTreeText->msg('open_link') ?></a>]
            </span>
          <? endif; ?>
        </div>
       
        <div class='content' id='<?="content-$node"?>' style='<?= $stub ? "display:none" : "display:block" ?>'>
        <? if (!$stub) $n= printSectionChildren($cat, $node, $articles); ?>
        </div>
      </div>
      <?
     
      return $n;
    }
   
    function printArticle($name, $tags= NULL) {
      global $wikiInfo, $sectionLoadURL, $terse, $terseTarget, $filterMode;
      $label= escapeHtml(str_replace('_',' ',$name));
     
      $wikiLink= NULL;
     
      if ($wikiInfo && $wikiInfo->baseURL) {
        $wikiLink= $wikiInfo->baseURL . '?title=' . urlencode($name);
      }
     
      $n= NULL;
     
      $class= 'dummy';
      if ($filterMode == 'h' && $tags) $class= 'highlite';
      ?>
      <div class='leaf'>
        <span class='<?= $class ?>'>
          <? if ($terse): ?>
              <span class='label'>
                <a href='<?=$wikiLink?>' <?= $terseTarget ?>><?=$label?></a>
              </span>
          <? else: ?>
              <span class='label'>
                <?=$label?>
              </span>
             
              <span class='links'>
                [<a href='<?=$wikiLink?>'><?=escapeHtml($wikiInfo->family)?></a>]
              </span>
          <? endif; ?>
         
          <? if ($tags): ?>
              <span class='tags'>
                (<?= escapeHtml($tags); ?>)
              </span>
          <? endif; ?>
        </span>
      </div>
      <?
     
      return $n;
    }
   
    /*
    function printParents( $cat, $decorate = false ) {
      $parents= getCategories( $cat );
      $ptext= '';
     
      global $sectionLoadURL;
     
      if ( $parents ) {
        $first= true;
        foreach ($parents as $p) {
          if ($first) $first= false;
          else if (!$decorate) $ptext.= ", ";
         
          $u= "$sectionLoadURL&amp;cat=".urlencode($p);
          if ($decorate) $ptext.= "^";
          $ptext.= "<a href='$u' target='_self' class='parent'>".escapeHtml(str_replace('_',' ',$p))."</a>";
          if ($decorate) $ptext.= "<br/>";
        }
       
        $ptext= " $ptext";
      }
     
      print $ptext;
    }
    */

    function printSectionChildren($cat, $node, $articles= false) {
      $cats= getSubcategories($cat,$articles);
     
      $n= 0;
      foreach ($cats as $c) {
        $n+= 1;
        if ($c['page_namespace']==NS_CATEGORY) printSection($c['page_title'],"$node.$n",true,$articles);
        else printArticle($c['page_title'],@$c['tags']);
      }
     
      return $n;
    }
   
    function getSubcategories( $cat, $articles= false ) {
      if ($cat==NULL || $cat=='*') {
        $sql= "SELECT cat.page_namespace, cat.page_title
              FROM page as cat
              LEFT JOIN categorylinks as c ON c.cl_from = cat.page_id
              JOIN categorylinks as m ON m.cl_to = cat.page_title
              JOIN page as p ON m.cl_from = p.page_id
              WHERE cat.page_namespace = "
.NS_CATEGORY."
              AND cat.page_is_redirect = 0
              AND c.cl_from IS NULL
              AND p.page_namespace = "
.NS_CATEGORY."
              GROUP BY cat.page_id
              ORDER BY cat.page_title"
;
      }
      else {
        $nsmatch= $articles ? "page_namespace in (".NS_MAIN.", ".NS_CATEGORY.")" : "page_namespace = " . NS_CATEGORY;
     
        $sql= "SELECT page_namespace, page_title
              FROM page
              JOIN categorylinks ON cl_from = page_id
              WHERE cl_to = "
. $this->db->addQuotes($cat) . "
              AND $nsmatch
              AND page_is_redirect = 0
              ORDER BY page_namespace DESC, page_title"
;
      }         
           
      #print "*** $sql ***";
      $res= $this->db->query($sql, 'getSubcategories');         
     
      $cats= array();
      while ($row= $this->db->fetchRow($res)) {
        $cats[]= wsfStripIntKeys($row);
      }
     
      $this->db->freeResult($res);
     
      return $cats;
    }
   
    /*
    function getCategories( $page, $ns = NS_CATEGORY ) {
      global $db;
   
      $sql= "SELECT cl_to as cat
            FROM page
            JOIN categorylinks ON cl_from = page_id
            WHERE page_title = " . $this->db->addQuotes($page) . "
            AND page_namespace = " . NS_CATEGORY . "
            ORDER BY cat";
           
      $res= $this->db->query($sql, 'getCategories');         
     
      $cats= array();
      while ($row= $this->db->fetchRow($res)) {
        $cats[]= $row['cat'];
      }
     
      $this->db->freeResult($res);
     
      return $cats;
    }
    */

}

#-----------------------------------------------------------------------------

if (!defined('CTL_STANDALONE')) return;

if (defined('CTL_MEDIAWIKI')) {
    $db=& wfGetDB( DB_SLAVE );
}
else if (defined('CTL_WIKISENSE')) {
    $db=& openConnection($ctlDB);
}
else {
    extract($ctlDB);

    # Get class for this database type
    $class = 'Database' . ucfirst( $type );
    if ( !class_exists( $class ) ) {
            require_once( "includes/$class.php" );
    }
   
    # Create object
    $db= new $class( $host, $user, $password, $dbname, 'dbFailFunction', 0 );
}

if ( !$db || !$db->mConn ) {
    die("failed to connect to $type://$user@$host/$dbname");
}

#-----------------------------------------------------------------------------

/*
$cat= $wgRequest->getVal('cat');
$node= $wgRequest->getVal('node');
$terse= $wgRequest->getVal('terse');
$conf= $wgRequest->getVal('conf');
$art= $wgRequest->getVal('art');

$filterCats= $wgRequest->getVal('fc');
$viewMode= $wgRequest->getVal('m','c');

if ($art) $viewMode= 'a';

$filterMode= false;
*/


$paramURL= $_SERVER["PHP_SELF"].'?';

/*
$paramURL= $wikiSelector->appendUrlParameters($paramURL);
addURLParam($paramURL,'m',$viewMode);
addURLParam($paramURL,'fc',$filterCats);
addURLParam($paramURL,'art',$art);

$sectionLoadURL= $paramURL;
addURLParam($sectionLoadURL,'terse',$terse);

$db= NULL;

if ($cat) $cat= trim($cat);

if ( $cat && $wikiSelector->domain ) {
  $wikiInfo= getWikiInfoFromDomain($wikiSelector->domain);
  if ($wikiInfo) $db= openConnection($wikiInfo->dbURL);
}
*/

$terseTarget= NULL;

if ($terse) {
    if ($wsgBrowser['msie']) $terseTarget= '_main';
    else if ($wsgBrowser['opera']) $terseTarget= '_content';
    else if ($wsgBrowser['mozilla']) $terseTarget= '_content';
    else if ($wsgBrowser['khtml']) $terseTarget= '_content';
   
    if ($terseTarget) $terseTarget= " target='$terseTarget'";
}

header("Content-Type: text/html; charset=utf-8");

if ($cat && $node) {
  $n= printSectionChildren($cat,$node,$art);
 
  if (!$n) {
    if ($art) {
      if ($filterMode=='w' || $filterMode=='o' ) print "<i class='empty'>no matching articles or subcategories.</i>";
      else print "<i class='empty'>".$wsgCatTreeText->msg('no_articles_or_subcat')."</i>";
    }
    else print "<i class='empty'>".$wsgCatTreeText->msg('no_subcat')."</i>";
  }
 
  $this->db->close();
  exit;
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Category Tree</title>

  <? 
  if ($db || $cat || $conf || $terse) print '<meta name="robots" content="noindex, nofollow"/>';
  else print '<meta name="robots" content="nofollow"/>';
  ?>
 
  <style type='text/css'>
  <? if ($terse): ?>
    body { font-family: sans-serif; font-size:80%; background-color:#f9f9f9; padding:0.5ex; margin:0; }
    .p { margin:0; padding-top:0; padding-bottom:0.3ex; }
    .h3 { margin:0; padding-top:0.3ex; padding-bottom:0.6ex; }
    .sectionhead { font-weight:normal; white-space:nowrap; padding-top: 0.5em; }
    .parent { font-weight:normal; font-style:italic; }
    .leaf { font-weight:normal; white-space:nowrap; margin-left:3ex; padding-top: 0.5em; }
    .settings { font-size:80%; }
    .settings input[type=text] { width:24ex; font-size:inherit; }
    .settings select { font-size:inherit; }
    .links { font-weight:normal; font-size:80%; font-weight:bold; }
  <? else: ?>
     body { font-family: sans-serif; font-size:14px; }
    .sectionhead { font-weight:bold; white-space:nowrap; }
    .parent { font-weight:bold; font-style:italic; }
    .leaf { font-weight:normal; white-space:nowrap; margin-left:3ex; }
    .settings input[type=text] { }
    .links { font-weight:normal; font-size:80%; }
  <? endif ?>
 
    .error { font-weight:bold; color:red; }
 
    .parents { font-size:95%; }
    .tree { font-size:95%; }
   
    .loaded { color:black; text-decoration: none; }
    .content { margin-left:2ex; }
    .tags { font-weight:normal; font-style:italic; font-size:80%; background-color:yellow; }
    .highlite { background-color:yellow; }
   
   
    .settings {
        border:1px solid #AAAAAA;
        background-color: #EEEEEE;
        padding:0 1ex 1ex 1ex;
        margin:0;
        margin-bottom:1ex;
    }
  </style>
 
  <script type="text/javascript" src="CategoryTree.js"></script>
 
  <script type="text/javascript">
    var sectionLoadURL= "<?=str_replace('&amp;','&',$sectionLoadURL)?>";
  </script>
 
  <script type="text/javascript">
      function install_sidebar(lnk, name, url) {
        if (typeof window.external == "object") {
            window.external.AddFavorite('javascript:void(_search=open(\''+url+'\',\'_search\'))', name);
        }
        else if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) {
            window.sidebar.addPanel (name,url,"");   
        }
        else if ( window.opera ) {
            lnk.href= url;
            lnk.rel= "sidebar";
            lnk.title= name;
            //document.write("<a href=\"" + url + "\" title=\"" + name + "\" rel=\"sidebar\">" + name + "</a>");
        }
        else {
            alert ("Your browser is not supported. Please try to create the sidebar manually.");
        }
      }
  </script>

</head>

<body>
  <? if (!$terse): ?>
  <div style='text-align:center'>
      <div style='width:700px; text-align:left; margin:0 auto;'>
  <? endif; ?>   
     
        <div style='margin:0; padding:0;'>
        <form action="CategoryTree.php">
       
        <?
        $scanURL= 'CategoryIntersect.php?';
        $scanURL= $wikiSelector->appendUrlParameters($scanURL);
        addURLParam($scanURL,'basecat',$cat);
        ?>
       
        <? if (!$terse || $conf): ?>
          <? if (!$terse): ?>
          <h2>Category Tree</h2>
          <? #wsfHackingInProgress(); ?>
           
          <p><?= $wsgCatTreeText->msg('top_note') ?>
          </p>
          <? endif; ?>
           
          <br style='clear:both;'/>
          <div style='position:relative; top:0; left:0; float:left; margin-left:auto; margin-right:auto; margin-top:2.5ex;'>
          <table class='settings'>
            <tr><td>
                <?= $wsgCatTreeText->msg('wiki') ?>:
            </td><td>
                <? $wikiSelector->printSelector(false); ?>
            </td></tr>
           
            <tr><td>
                <?= $wsgCatTreeText->msg('category') ?>:
            </td><td>
                <input type="text" name="cat" size="48" value="<?=escapeHtml($cat)?>"/>
            </td></tr>
           
            <tr><td><?= $wsgCatTreeText->msg('filter') ?>:
            </td><td>
              <select name='m'>
                  <? printOption($wsgCatTreeText->msg('filter_categories'), 'c', $viewMode); ?>
                  <? printOption($wsgCatTreeText->msg('filter_articles'), 'a', $viewMode); ?>
              <!--    <? #printOption('highlite tagged articles', 'h', $viewMode); ?>
                  <? #printOption('show tagged articles', 'w', $viewMode); ?>
                  <? #printOption('show untagged articles', 'o', $viewMode); ?> -->
              </select>
            </td></tr>

            <!--           
            <tr><td>
              Tags:
            </td><td>
              <input type="text" name="fc" value="<?=escapeHtml($filterCats)?>"/>
            </td></tr>
            -->
            <tr><td colspan="2" align="center">
                <input type="submit" name="<?= $conf?'configure':'go' ?>" value="<?= $wsgCatTreeText->msg('go_load') ?>"/>
               
                <div style='top:-6ex; right:0; position:absolute;'>
                    <? $wsgCatTreeText->printLanguageSelector($knownLanguages); ?>
                    <input type="submit" name="set-userlang" value="<?= $wsgCatTreeText->msg('set_language') ?>"/>
                    <br/><? $wsgCatTreeText->printTranslationLink('CategoryTree') ?>
                </div>
            </td></tr>
          </table>
          </div>
          <br style='clear:both;'/>
           
          <input type="hidden" name="terse" value="<?= escapeHtml($terse) ?>"/>
         
          <p><a href='<?=$scanURL?>' <?= $terseTarget ?>><?= $wsgCatTreeText->msg('scan_category_1',escapeHtml($cat))?></i></a></p>

           
        <? else: ?>
            <?
            $fullURL= $paramURL;
            addURLParam($fullURL,'cat',$cat);
           
            $confURL= $paramURL;
            addURLParam($confURL,'cat',$cat);
            addURLParam($confURL,'conf','on');
            addURLParam($confURL,'terse',$terse);
           
            ?>
            <table style='width:100%; margin:0; padding:0;'>
            <tr>
              <td style='width:50%; font-size:90%; text-align:left;  vertical-align:top;'>
                <b><?= $wikiInfo ? escapeHtml($wikiInfo->domain) : ''; ?></b>
                <!-- <br/>
                <i><a href='<?=$confURL?>' target='_self'>configure</a></i> -->
              </td>
             
              <td style='width:50%; font-size:90%; text-align:right; vertical-align:top;'>
              &nbsp;<a href='<?=$fullURL?>' <?= $terseTarget ?>><?= $wsgCatTreeText->msg('full_link')?></a>&nbsp;&gt;&gt;
              </td>
            </tr>
            </table>
           
              <p style='margin:0; padding:1ex 0 0 0; font-size:80%;'>
                <input type="text" size="16" name="cat" style='font-size:100%;' value="<?=escapeHtml($cat)?>"/>&nbsp;<input type="submit" style='font-size:100%;' value="<?= $wsgCatTreeText->msg('go_load')?>"/>
                <br/>
                <?
                $artURL= $_SERVER["PHP_SELF"].'?';
               
                $artURL= $wikiSelector->appendUrlParameters($artURL);
                addURLParam($artURL,'cat',$cat);
                addURLParam($artURL,'art',$art?'':'on');
                addURLParam($artURL,'terse',$terse);
               
                if ($art) print "<a href='$artURL' target='_self'>".$wsgCatTreeText->msg('hide_articles_link')."</a>";
                else print "<a href='$artURL' target='_self'>".$wsgCatTreeText->msg('show_articles_link')."</a>";
                ?>
                |
                <a href='<?=$scanURL?>' <?= $terseTarget ?>><?= $wsgCatTreeText->msg('scan_category_link') ?></i></a>
              </p>
             
              <input type="hidden" name="terse" value="on"/>
             
              <? $wikiSelector->printHiddenFields(false); ?>
             
              <input type="hidden" name="fc" value="<?= escapeHtml($filterCats) ?>"/>
              <input type="hidden" name="m" value="<?= escapeHtml($viewMode) ?>"/>
        <? endif; ?>
        </form>
        </div>
         
        <?
        $n= 0;
       
        if ($cat && $db && !$conf) {
          $barURL= $sectionLoadURL;
          addURLParam($barURL,'cat',$cat);
          addURLParam($barURL,'terse','on');
          $barURL= "http://".$_SERVER["SERVER_NAME"].$barURL;
         
          $ttl= "$cat ({$wikiSelector->domain})";
          ?>
         
          <div>
          <? if (!$terse): ?>
            <p style='font-size:90%; font-style:italic;'><?= $wsgCatTreeText->msg('sidebar') ?>:
            [<a href="<?= $barURL?>"><?= $wsgCatTreeText->msg('view_link') ?></a>],
            [<a href="<?= $barURL ?>" title='<?= $ttl?>' rel="sidebar"><?= $wsgCatTreeText->msg('install_link') ?> (Opera, Firefox)</a>]
            [<a href="javascript:install_sidebar(this,'<?= $ttl?>','<?= $barURL?>')"><?= $wsgCatTreeText->msg('install_link') ?> (IE, Mozilla, etc)</a>]
            </p>
           
            <h3><?= $wsgCatTreeText->msg('category') ?>: <?=escapeHtml(str_replace('_',' ',$cat))?></h3>
           
            <p class='parents'>
            <?= $wsgCatTreeText->msg('parent_categories') ?>: <? printParents($cat); ?>
            </p>
          <? else: ?> 
            <p class='parents'  style='margin:0; padding:0; padding-bottom:0.5ex;'>
            <? printParents($cat,true); ?>
            </p>
          <? endif; ?> 
          </div>

          <div class='tree'>
          <?
         
          $n= printSection($cat,'r',false,$art);
         
          if (!$n) {
            print "<i>".$wsgCatTreeText->msg('error_nothing_found')."</i>";
          }
         
          ?>
          </div>
          <?
        }
       
        if ($db) {
          $this->db->close();
        }
       
        if (!$terse) wsfFooter(false);
        ?>

  <? if (!$terse): ?>
    </div>
  </div>
  <? endif; ?>   
</body>

</html>