Aller au contenu

Utilisateur:Dr Brains/Test2.php

Une page de Wikipédia, l'encyclopédie libre.


PHP[modifier | modifier le code]

  • SelectCategoryFunctions.php
<?php

/**
 * Implementation of the SelectCategory extension, an extension of the
 * edit box of MediaWiki to provide an easy way to add category links
 * to a specific page.
 *
 * @file
 * @ingroup Extensions
 * @author Leon Weber <leon@leonweber.de> & Manuel Schneider <manuel.schneider@wikimedia.ch>
 * @copyright © 2006 by Leon Weber & Manuel Schneider
 * @licence GNU General Public Licence 2.0 or later
 */

if( !defined( 'MEDIAWIKI' ) ) {
  echo( "This file is an extension to the MediaWiki software and cannot be used standalone.\n" );
  die();
}

$wgSelectCategoryIndex = -1;

function fnSelectCategoryGetIndex(){
  global $wgSelectCategoryIndex;
  $wgSelectCategoryIndex = $wgSelectCategoryIndex+1;
  return $wgSelectCategoryIndex;
}

## Entry point for the hook and main worker function for editing the page:
function fnSelectCategoryShowHook( $m_isUpload = false, $m_pageObj ) {

  # check if we should do anything or sleep
  if ( fnSelectCategoryCheckConditions( $m_isUpload, $m_pageObj ) ) {
    # Register CSS file for our select box:
    global $wgOut, $wgScriptPath, $wgUser, $wgTitle;
    global $wgSelectCategoryMaxLevel;
    
/*     $wgOut->addLink(
      array(
        'rel'  => 'stylesheet',
        'type' => 'text/css',
        'href' => "$wgScriptPath/extensions/SelectCategory/SelectCategory.css"
      )
    ); */

    $m_skin =& $wgUser->getSkin();
              
    # Get all categories from wiki:
    $m_allCats = fnSelectCategoryGetAllCategories();
    # Load system messages:
    wfLoadExtensionMessages( 'SelectCategory' );
    # Get the right member variables, depending on if we're on an upload form or not:
    if( !$m_isUpload ) {
      # Extract all categorylinks from page:
      $m_pageCats = fnSelectCategoryGetPageCategories( $m_pageObj );

      # Never ever use editFormTextTop here as it resides outside the <form> so we will never get contents
      $m_place = 'editFormTextAfterWarn';
      # Print the localised title for the select box:
      $m_textBefore = '<b>'. wfMsg( 'selectcategory-title' ) . '</b>:';
    } else {
      # No need to get categories:
      $m_pageCats = array();

      # Place output at the right place:
      $m_place = 'uploadFormTextAfterSummary';
      # Print the part of the table including the localised title for the select box:
      $m_textBefore = "\n</td></tr><tr><td align='right'><label for='wpSelectCategory'>" . wfMsg( 'selectcategory-title' ) .":</label></td><td align='left'>";
    }
    # Introduce the output:
    $m_pageObj->$m_place .= "<!-- SelectCategory begin -->\n";
    # Print the select box:
    $m_pageObj->$m_place .= "\n$m_textBefore";
#    # First come up with the JavaScript version of the select boxes:
#    $m_pageObj->$m_place .= "<script type=\"text/javascript\" src=\"'/extensions/SelectCategory/SelectCategory.js\"></script>\n";
#    # Then the "old-style" select box for those without JavaScript:
#    $m_pageObj->$m_place .= "<noscript>\n";
#    $m_pageObj->$m_place .= "</noscript>\n";

# Catégories sélectionnées -----------------------------------------

     $List_CheckedCats = '';
     $List_CheckedCats .= '<div id="CategorySelect_CheckedCats">';
     $List_CheckedCats .= '<ul>';
     $List_CheckedCatsArray = array_keys($m_pageCats);
     foreach($List_CheckedCatsArray as $Arraykey => $Arrayvalue) {
       $category =  htmlspecialchars( $Arrayvalue);
       $category2 = str_replace("_", " ", $category);
       $category3 = urlencode($category);
       $category3 = strtr( $category3, array( '%' => '.', '+' => '_' ) );
       $category3 = str_replace( '.3A', ':', $category3 );

       $categorytitle = Title::makeTitle(NS_CATEGORY, $category );
       $categoryurl = htmlspecialchars(Title::makeTitle(NS_CATEGORY, $category )->getFullURL());
       $categoryclass = '';
       if(!$categorytitle->getArticleId()){
         $categoryclass = 'class="new"';
         $categoryurl = htmlspecialchars(Title::makeTitle(NS_CATEGORY, $category )->getFullURL('action=edit&redlink=1'));
         $categorytitle = wfMsg('red-link-title', array(Title::makeTitle(NS_CATEGORY, $category )));
       }
       $List_CheckedCats .= '<li id="CheckedCat_'.$category3.'" ><a '.$categoryclass.' href="'.$categoryurl.'" title="'.$categorytitle.'">'.$category2.'</a></li>';
    }
    $List_CheckedCats .= '</ul></div>';

# Arborescence de catégories -----------------------------------------

    $List_Content = '';
    $List_Content .= '<div id="SelectCategoryList" class="SelectCategoryMaxdepth_'.$wgSelectCategoryMaxLevel.'">';
    $List_Content .= '<ul class="SelectCategoryUlDepth0"><li style="display:none;">';
    $m_lastdepth = 0;
    foreach( $m_allCats as $m_value => $m_array ) {
      $m_cat =$m_array["title"];
      $m_depth= $m_array["depth"];

      $category =  htmlspecialchars( $m_cat );
      $category2 = str_replace("_", " ", $category);
      $category3 = urlencode($category);
      $category3 = strtr( $category3, array( '%' => '.', '+' => '_' ) );
      $category3 = str_replace( '.3A', ':', $category3 );

      $checked = '';
      if (isset($m_pageCats[$m_cat])) {
        $checked = 'checked="checked"';

      }

      $startUl = '';
      $endUl = '';
      if($m_depth>$m_lastdepth){
        while($m_depth!=$m_lastdepth){            
          $startUl .= '<ul class="SelectCategoryUlDepth'.($m_lastdepth+1).'">';
          $m_lastdepth = ($m_lastdepth+1);
        }
      }else if($m_depth<$m_lastdepth){
        $endUl .= '</li>';
        while($m_depth!=$m_lastdepth){
          $endUl .= '</ul>';
          $m_lastdepth = ($m_lastdepth -1);
        }
      }else{
        $endUl .= '</li>';
      }
      $startUl .= '<li id="'.$category3.'">';


      $List_Content .= $endUl.$startUl;
      $List_Content .= '<input type="checkbox" name="SelectCategoryList[]" value="'.$category.'" class="checkbox" '.$checked.' />';
      $List_Content .= $category2;
    }
    $endUl = '';
    if($m_lastdepth>0){
      $endUl .= '</li>';
      while($m_lastdepth!=0){
        $endUl .= '</ul>';
        $m_lastdepth = ($m_lastdepth -1);
      }
        $endUl .= '</li>';
    }
    $List_Content .= $endUl.'</li></ul></div>';

# Affichage résultat -----------------------------------------

    $Result = wfMsg( 'selectcategory-template', array($List_CheckedCats, $List_Content) );
    $m_pageObj->$m_place .= $Result;

    # Print localised help string:
    $m_pageObj->$m_place .= "<!-- SelectCategory end -->\n";
  }

  # Return true to let the rest work:
  return true;
}

## Entry point for the hook and main worker function for saving the page:
function fnSelectCategorySaveHook( $m_isUpload, $m_pageObj ) {
  global $wgContLang;
  global $wgTitle;

  # check if we should do anything or sleep
  if ( fnSelectCategoryCheckConditions( $m_isUpload, $m_pageObj ) ) {

    # Get localised namespace string:
    $m_catString = $wgContLang->getNsText( NS_CATEGORY );

    # default sort key is page name with stripped namespace name,
    # otherwise sorting is ugly.
    if( $wgTitle->getNamespace() == NS_MAIN ) {
      $default_sortkey = "";
    } else {
      $default_sortkey = "|{{PAGENAME}}";
    }

    # Get some distance from the rest of the content:
    $m_text = "\n";

    # Iterate through all selected category entries:
    if (array_key_exists('SelectCategoryList', $_POST)) {
      foreach( $_POST['SelectCategoryList'] as $m_cat ) {
        $m_text .= "\n[[$m_catString:$m_cat$default_sortkey]]";
      }
    }
    # If it is an upload we have to call a different method:
    if ( $m_isUpload ) {
      $m_pageObj->mUploadDescription .= $m_text;
    } else{
      $m_pageObj->textbox1 .= $m_text;
    }
  }

  # Return to the let MediaWiki do the rest of the work:
  return true;
}

## Get all categories from the wiki - starting with a given root or otherwise detect root automagically (expensive)
## Returns an array like this:
## array (
##   'Name' => (int) Depth,
##   ...
## )
function fnSelectCategoryGetAllCategories() {
  global $wgTitle;
  global $wgSelectCategoryRoot;

  # Get current namespace (save duplicate call of method):
  $m_namespace = $wgTitle->getNamespace();
  if( $m_namespace >= 0 && $wgSelectCategoryRoot[$m_namespace] ) {
    # Include root and step into the recursion:
    $m_allCats = array();
    $m_allCats +=   array(fnSelectCategoryGetIndex() => array("title" => $wgSelectCategoryRoot[$m_namespace], "depth" => 0) );
    $m_allCats += fnSelectCategoryGetChildren($wgSelectCategoryRoot[$m_namespace]);

#    $m_allCats = array_merge( array( $wgSelectCategoryRoot[$m_namespace] => 0 ), fnSelectCategoryGetChildren( $wgSelectCategoryRoot[$m_namespace] ) );
  } else {
    # Initialize return value:
    $m_allCats = array();

    # Get a database object:
    $m_dbObj = wfGetDB( DB_SLAVE );
    # Get table names to access them in SQL query:
    $m_tblCatLink = $m_dbObj->tableName( 'categorylinks' );
    $m_tblPage = $m_dbObj->tableName( 'page' );

    # Automagically detect root categories:
    $m_sql = "  SELECT tmpSelectCat1.cl_to AS title
        FROM $m_tblCatLink AS tmpSelectCat1
        LEFT JOIN $m_tblPage AS tmpSelectCatPage ON (tmpSelectCat1.cl_to = tmpSelectCatPage.page_title AND tmpSelectCatPage.page_namespace = 14)
        LEFT JOIN $m_tblCatLink AS tmpSelectCat2 ON tmpSelectCatPage.page_id = tmpSelectCat2.cl_from
        WHERE tmpSelectCat2.cl_from IS NULL GROUP BY tmpSelectCat1.cl_to";
    # Run the query:
    $m_res = $m_dbObj->query( $m_sql, __METHOD__ );
    # Process the resulting rows:
    while ( $m_row = $m_dbObj->fetchRow( $m_res ) ) {
      $m_allCats += array(fnSelectCategoryGetIndex() => array("title" => $m_row['title'], "depth" => 0) );
      $m_allCats += fnSelectCategoryGetChildren($m_row['title'] );
    }
    # Free result:
    $m_dbObj->freeResult( $m_res );
  }

  # Afterwards return the array to the caller:
  return $m_allCats;
}

function fnSelectCategoryGetChildren($m_root, $m_depth = 1 ) {
  # Initialize return value:
  $m_allCats = array();

  # Get a database object:
  $m_dbObj = wfGetDB( DB_SLAVE );
  # Get table names to access them in SQL query:
  $m_tblCatLink = $m_dbObj->tableName( 'categorylinks' );
  $m_tblPage = $m_dbObj->tableName( 'page' );

  # The normal query to get all children of a given root category:
  $m_sql = '
    SELECT tmpSelectCatPage.page_title AS title
    FROM '.$m_tblCatLink.' AS tmpSelectCat
    LEFT JOIN '.$m_tblPage.' AS tmpSelectCatPage 
      ON tmpSelectCat.cl_from = tmpSelectCatPage.page_id
    WHERE tmpSelectCat.cl_to LIKE '.$m_dbObj->addQuotes( $m_root ).' 
      AND tmpSelectCatPage.page_namespace = 14
    ORDER BY tmpSelectCatPage.page_id ASC;';
  # Run the query:
  $m_res = $m_dbObj->query( $m_sql, __METHOD__ );
  # Process the resulting rows:
  while ( $m_row = $m_dbObj->fetchRow( $m_res ) ) {
    # Survive category link loops:
    if( $m_root == $m_row['title'] ) {
      continue;
    }
    # Add current entry to array:
    $m_allCats += array(fnSelectCategoryGetIndex() => array("title" => $m_row['title'], "depth" => $m_depth) );
    $m_allCats += fnSelectCategoryGetChildren($m_row['title'], $m_depth + 1 );
  }
  # Free result:
  $m_dbObj->freeResult( $m_res );

  # Afterwards return the array to the upper recursion level:
  return $m_allCats;
}

## Returns an array with the categories the articles is in.
## Also removes them from the text the user views in the editbox.
function fnSelectCategoryGetPageCategories( $m_pageObj ) {

  if (array_key_exists('SelectCategoryList', $_POST)) {
    # We have already extracted the categories, return them instead
    # of extracting zero categories from the page text.
    $m_catLinks = array();
    foreach( $_POST['SelectCategoryList'] as $m_cat ) {
      $m_catLinks[ $m_cat ] = true;
    }
    return $m_catLinks;
  }

  global $wgContLang;

  # Get page contents:
  $m_pageText = $m_pageObj->textbox1;
  # Get localised namespace string:
  $m_catString = strtolower( $wgContLang->getNsText( NS_CATEGORY ) );
  # The regular expression to find the category links:
  $m_pattern = "\[\[({$m_catString}|category):([^\|\]]*)(\|{{PAGENAME}}|)\]\]";
  $m_replace = "$2";
  # The container to store all found category links:
  $m_catLinks = array ();
  # The container to store the processed text:
  $m_cleanText = '';

  # Check linewise for category links:
  foreach( explode( "\n", $m_pageText ) as $m_textLine ) {
    # Filter line through pattern and store the result:
    $m_cleanText .= preg_replace( "/{$m_pattern}/i", "", $m_textLine ) . "\n";
    # Check if we have found a category, else proceed with next line:
                if( !preg_match( "/{$m_pattern}/i", $m_textLine) ) continue;
    # Get the category link from the original text and store it in our list:
    $m_catLinks[ str_replace( ' ', '_', preg_replace( "/.*{$m_pattern}/i", $m_replace, $m_textLine ) ) ] = true;
  }
  # Place the cleaned text into the text box:
  $m_pageObj->textbox1 = trim( $m_cleanText );

  # Return the list of categories as an array:
  return $m_catLinks;
}

# Function that checks if we meet the run conditions of the extension
function fnSelectCategoryCheckConditions ($m_isUpload, $m_pageObj ) {
  global $wgSelectCategoryNamespaces;
  global $wgSelectCategoryEnableSubpages;
  global $wgTitle;


  # Run only if we are in an upload, an activated namespace or if page is
  # a subpage and subpages are enabled (unfortunately we can't use
  # implication in PHP) but not if we do a sectionedit:

  if ($m_isUpload == true) {
    return true;
  }

  $ns = $wgTitle->getNamespace();
  if( array_key_exists( $ns, $wgSelectCategoryNamespaces ) ) {
    $enabledForNamespace = $wgSelectCategoryNamespaces[$ns];
  } else {
    $enabledForNamespace = false;
  }

  # Check if page is subpage once to save method calls below:
  $m_isSubpage = $wgTitle->isSubpage();

  if ($enabledForNamespace
    && (!$m_isSubpage
      || $m_isSubpage && $wgSelectCategoryEnableSubpage)
    && $m_pageObj->section == false) {
    return true;
  }
}

JavaScript[modifier | modifier le code]

  • SelectCategory.js
//<syntaxhighlight lang="javascript">//<pre><nowiki>

// **********************************************************
// TEXTES ; 

var SelectCategory_Text = new Array();

SelectCategory_Text["ShowTitle"] = "Ouvrir";
SelectCategory_Text["HideTitle"] = "Fermer";
SelectCategory_Text["ShowText"] = '<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/Pictogram_voting_support.svg/12px-Pictogram_voting_support.svg.png" width="12" heigth="12" alt="' + SelectCategory_Text["ShowTitle"] + '" />';
SelectCategory_Text["HideText"] = '<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/e/e9/Pictogram_voting_oppose.svg/12px-Pictogram_voting_oppose.svg.png" width="12" heigth="12" alt="' + SelectCategory_Text["HideTitle"] + '" />';
 

// **********************************************************
// LANCEMENT

addOnloadHook(SelectCategory_Init);
 

// **********************************************************
// INITIALISATION

function SelectCategory_Init(){
    var Tree = document.getElementById('SelectCategoryList');
    if(!Tree) return;
    var Deepth = parseInt(Tree.className.replace(/SelectCategoryMaxdepth_/g, ""));
    if(Deepth == "NaN" || Deepth == NaN) Deepth == -1;
    var WithChildLis = new Array();
    var WithoutChildLis = new Array();
    var branche = Tree.getElementsByTagName('li');
    for(var b=2,m=branche.length;b<m;b++){
        var ThisLi = branche[b];
        ThisLi.id = "SelectCategory_" + b;
        addClass(ThisLi, "SelectCategory_level" + SelectCategory_GetLevel(ThisLi, Tree));
        var HasChild = ThisLi.getElementsByTagName('ul')[0];
        if(HasChild){
            WithChildLis.push(ThisLi);
        }else{
            WithoutChildLis.push(ThisLi);
        }
        if(!ThisLi.nextSibling){
            addClass(ThisLi, "lastline");
        }else{
            addClass(ThisLi, "notlastline");
        }
    }
    SelectCategory_AddToggleLinks(WithChildLis, true);
    SelectCategory_AddToggleLinks(WithoutChildLis, false);
    if(Deepth!=-1){
        for(var c=0,n=WithChildLis.length;c<n;c++){
            var ID = WithChildLis[c].id.split("SelectCategory_").join("");
            var LiDeepth = parseInt(WithChildLis[c].className.replace(/.*SelectCategory_level/g, "").replace(/ .*/g, ""));
            if(LiDeepth>Deepth) SelectCategory_ToggleThisLi(ID);
        }
    }
    SelectCategory_ToggleCheckedLinks();
}


// **********************************************************
// DETERMINATION PROFONDEUR D'UN LI

function SelectCategory_GetLevel(Li, Parent){
     var Deepth = 1;
     var Node = Li.parentNode;
     while(Node != Parent){
          if(Node.tagName){
               if(Node.tagName.toLowerCase() == "li"){
                    Deepth++
               }
          }
          Node = Node.parentNode;
     }
     return Deepth;
}


// **********************************************************
// AJOUT DES LIENS
 
function SelectCategory_AddToggleLinks(Lis, NotEmpty){
     for(var d=0,r=Lis.length;d<r;d++){
          var Li = Lis[d];
          var ID = Li.id.split("SelectCategory_").join("");
          var Link;
          if(NotEmpty){
               addClass(Li, "Collapsible");
               Link = document.createElement('a');
               Link.id = "SelectCategoryLink_"+ID;
               Link.href = "javascript:SelectCategory_ToggleThisLi('"+ID+"');";
               Link.title = SelectCategory_Text["HideTitle"];
               Link.innerHTML = SelectCategory_Text["HideText"];
               Li.insertBefore(document.createTextNode(" "), Li.firstChild);
               Li.insertBefore(Link, Li.firstChild);
          }else{
               Link = document.createElement('span');
               Link.innerHTML = "&nbsp;&nbsp;&nbsp; "
               Li.insertBefore(Link, Li.firstChild);
          }
          Link.style.position = "relative";
          Link.style.top = "-3px";
          Link.style.marginLeft = "-19px";
     }
}


// **********************************************************
// ENROULAGE OU DÉROULAGE D'UNE BRANCHE

function SelectCategory_ToggleThisLi(Index, state){
     var Link = document.getElementById("SelectCategoryLink_"+Index);
     var Li = document.getElementById("SelectCategory_"+Index);
     var Ul = Li.getElementsByTagName('ul')[0];
     if(!Li || !Link || !Ul) return;
 
     if(Link.title == SelectCategory_Text["HideTitle"] || (state!="undefined" && state === true) ){
          Link.innerHTML = SelectCategory_Text["ShowText"]
          Link.title = SelectCategory_Text["ShowTitle"]
          Ul.style.display = "none"
     }else if(Link.title == SelectCategory_Text["ShowTitle"] || (state!="undefined" && state === false) ){
          Link.innerHTML = SelectCategory_Text["HideText"]
          Link.title = SelectCategory_Text["HideTitle"];
          Ul.style.display = "block";
     }
}

 
// **********************************************************
// DÉROULAGE D'UNE BRANCHE SÉLECTIONNÉE

function SelectCategory_ToggleCheckedLinks(){
    var Tree = document.getElementById('SelectCategoryList');
    if(!Tree) return;
    var Inputs = Tree.getElementsByTagName('input');
    for(var a=0,l=Inputs.length;a<l;a++){
        if(Inputs[a].checked) continue;
        SelectCategory_ToggleAllParents(Inputs[a]);
    }
}

function SelectCategory_ToggleAllParents(Element){
    var Tree = document.getElementById('SelectCategoryList');
    if(!Tree) return;
    var Node = Element.parentNode;
    while(Node != Tree){        
        if(Node.tagName){
            if(Node.tagName.toLowerCase() == "li"){
                var NodeID = Node.id.split("SelectCategory_").join("");
                if($(Node).hasClass("Collapsible")) SelectCategory_ToggleThisLi(NodeID, false);
            }
        }
        Node = Node.parentNode;
    }
}

//</nowiki></pre>

CSS[modifier | modifier le code]

  • SelectCategory.css
#SelectCategoryList ul {
  padding : 0;
  margin : 0;
  list-style-type: none;
  list-style-image: none;
}

.SelectCategoryUlDepth1 {
  padding-left : 3px !important;
}

#SelectCategoryList {
  padding : 1em;
}

#SelectCategoryList li {
  margin-bottom: 0;
  zoom: 1; /* BE KIND TO IE6 */
}

#SelectCategoryList li li.notlastline {
  background: url("http://upload.wikimedia.org/wikipedia/commons/8/85/Treeview-gray-line.png") no-repeat left top;
  padding: 0 0 0 20px;
}

#SelectCategoryList li.lastline {
  background: url("http://upload.wikimedia.org/wikipedia/commons/8/85/Treeview-gray-line.png") no-repeat left top;
  padding: 0 0 0 20px;
  background-position: 0 -2988px;
}