r87707 MediaWiki - Code Review archive

Repository:MediaWiki
Revision:r87706‎ | r87707 | r87708 >
Date:11:06, 9 May 2011
Author:faurethomas
Status:deferred (Comments)
Tags:
Comment:
Categorize: use wgAPIListModules for AJAX call, use wgAutoloadClasses to load files, separate hooks,
Modified paths:
  • /trunk/extensions/Categorize/Categorize.api.php (added) (history)
  • /trunk/extensions/Categorize/Categorize.body.php (modified) (history)
  • /trunk/extensions/Categorize/Categorize.hooks.php (added) (history)
  • /trunk/extensions/Categorize/Categorize.i18n.php (modified) (history)
  • /trunk/extensions/Categorize/Categorize.js (modified) (history)
  • /trunk/extensions/Categorize/Categorize.php (modified) (history)

Diff [purge]

Index: trunk/extensions/Categorize/Categorize.i18n.php
@@ -4,12 +4,15 @@
55 /* Categorize Mediawiki Extension
66 *
77 * @author Andreas Rindler (mediawiki at jenandi dot com) and Thomas Fauré (faure dot thomas at gmail dot com)
8 - * @licence GNU General Public Licence 2.0 or later
 8+ * @licence GNU General Public Licence 3.0
99 * @description
1010 *
1111 */
1212 $messages = array();
1313
 14+/** English
 15+ * @author Thomas Fauré
 16+ */
1417 $messages['en'] = array(
1518 'categorize-title' => 'Knowledge qualification',
1619 'categorize-subtitle' => '',
@@ -18,12 +21,15 @@
1922 'categorize-taglabel' => 'Catégories populaires',
2023 'categorize-advice' => 'Click on the labels you want to attribute to this article:'
2124 );
 25+/** French (Français)
 26+ * @author Thomas Fauré
 27+ */
2228 $messages['fr'] = array(
2329 'categorize-title' => 'Qualification des savoirs',
2430 'categorize-subtitle' => '',
2531 'categorize-footer' => 'Si vous souhaitez ajouter un label, contactez ...',
26 - 'categorize-boxlabel' => 'Catégories',
27 - 'categorize-taglabel' => 'Catégories populaires',
28 - 'categorize-advice' => 'Cliquez sur les labels que vous souhaitez attribuer à cet article :'
 32+ 'categorize-boxlabel' => 'Catégories',
 33+ 'categorize-taglabel' => 'Catégories populaires',
 34+ 'categorize-advice' => 'Cliquez sur les labels que vous souhaitez attribuer à cet article :'
2935 );
3036 ?>
Index: trunk/extensions/Categorize/Categorize.php
@@ -1,10 +1,10 @@
22 <?php
33 /* Categorize Mediawiki Extension
44 *
5 - * @author Andreas Rindler (mediawiki at jenandi dot com) for initial Extension:CategorySuggest and Thomas Faur� for Categorize improvments
 5+ * @author Andreas Rindler (mediawiki at jenandi dot com) for initial Extension:CategorySuggest and Thomas Faur� (faure dot thomas at gmail dot com) for Categorize improvments
66 * @credits Jared Milbank, Leon Weber <leon.weber@leonweber.de> & Manuel Schneider <manuel.schneider@wikimedia.ch>, Daniel Friesen http://wiki-tools.com
7 - * @licence GNU General Public Licence 2.0 or later
8 - * @description Adds input box to edit and upload page which allows users to assign categories to the article. When a user starts typing the name of a category, the extension queries the database to find categories that match the user input. Furthermore, a best categories labels cloud is displayed."
 7+ * @licence GNU General Public Licence 3.0
 8+ * @description Adds input box to edit and upload page which allows users to assign categories to the article. When a user starts typing the name of a category, the extension queries the database to find categories that match the user input. Furthermore, a best categories labels cloud is displayed.
99 *
1010 */
1111
@@ -28,86 +28,37 @@
2929 # $wgCategorizeUnaddedWarning - not implemented
3030 # $wgCategorizeCloud : cloud - use cloud ; anything else - list
3131 #
 32+
 33+$dir = dirname( __FILE__ );
 34+
 35+
3236 $wgCategorizejs = $wgScriptPath . '/extensions/Categorize/Categorize.js' ;
3337 $wgCategorizecss = $wgScriptPath . '/extensions/Categorize/Categorize.css';
3438 $wgCategorizeNumToSend = '50';
3539 $wgCategorizeUnaddedWarning = 'True';
3640 $wgCategorizeCloud = 'list';
3741
38 -## Register extension setup hook and credits:
39 -$wgExtensionFunctions[] = 'fnCategorize';
40 -$wgExtensionCredits['parserhook'][] = array(
 42+$wgExtensionCredits['other'][] = array(
4143 'name' => 'Categorize',
42 - 'author' => 'Thomas Faur&eacute;',
 44+ 'author' => 'Thomas Faur�',
4345 'url' => 'http://www.mediawiki.org/wiki/Extension:Categorize',
4446 'description' => 'Adds input box to edit and upload page which allows users to assign categories to the article. When a user starts typing the name of a category, the extension queries the database to find categories that match the user input. Furthermore, a best categories labels cloud is displayed.',
45 - 'version' => '0.1.0'
 47+ 'version' => '0.1.1'
4648 );
4749
48 -## register Ajax function to be called from Javascript file
49 -$wgAjaxExportList[] = 'fnCategorizeAjax';
 50+$wgExtensionMessagesFiles['Categorize'] = "$dir/Categorize.i18n.php";
 51+$wgAutoloadClasses['CategorizeHooks'] = "$dir/Categorize.hooks.php";
 52+$wgAutoloadClasses['CategorizeBody'] = "$dir/Categorize.body.php";
5053
51 -## Entry point for Ajax, registered in $wgAjaxExportList; returns all cats starting with $query
52 -function fnCategorizeAjax( $query ) {
53 - if(isset($query) && $query != NULL) {
54 - $searchString = mysql_real_escape_string($query);
55 - # % and _ are not escaped so do it here
56 - $searchString = str_replace( '%' , '\%' , $searchString );
57 - $searchString = str_replace( '_' , '\_' , $searchString );
58 - $searchString = str_replace( '|' , '%' , $searchString );
59 - $dbr =& wfGetDB( DB_SLAVE );
60 - $categorylinks = $dbr->tableName('categorylinks');
61 - $page = $dbr->tableName('page');
62 - $sql =
63 - "SELECT DISTINCT\n".
64 - " cl_to AS cats\n".
65 - " FROM $categorylinks\n".
66 - " WHERE\n".
67 - " UCASE(cl_to) LIKE UCASE('".$searchString."%')\n";
68 - $res = $dbr->query( $sql );
69 - $suggestStrings = array();
70 - for ( $i=0 ; $row = $dbr->fetchObject( $res ) ; $i++ ) {
71 - array_push($suggestStrings,$row->cats);
72 -## Optional enhancement: Cutoff and rollover at max number of suggestions
73 -## implement cutoff and rollover here
74 -# if ($i > 10) {
75 -# array_push($suggestStrings,'More...');
76 -# break;
77 -# }
78 - }
79 - $text = implode("<",$suggestStrings);
80 - $dbr->freeResult( $res );
81 - }
82 - if ( !isset($text) || $text == NULL ) {
83 - $text = '<';
84 - }
85 - $response = new AjaxResponse($text);
86 - return $response;
87 -}
 54+$wgAutoloadClasses['ApiQueryCategorize'] = "$dir/Categorize.api.php";
 55+$wgAPIListModules['categorize'] = 'ApiQueryCategorize';
8856
89 -## Set Hook:
90 -function fnCategorize() {
91 - global $wgHooks;
92 -
93 - ## Showing the boxes
94 - # Hook when starting editing:
95 - $wgHooks['EditPage::showEditForm:initial'][] = array( 'fnCategorizeShowHook', false );
96 - # Hook for the upload page:
97 - $wgHooks['UploadForm:initial'][] = array( 'fnCategorizeShowHook', true );
 57+## Set Hooks:
9858
99 - ## Saving the data
100 - # Hook when saving page:
101 - $wgHooks['EditPage::attemptSave'][] = array( 'fnCategorizeSaveHook', false );
102 - # Hook when saving the upload:
103 - $wgHooks['UploadForm:BeforeProcessing'][] = array( 'fnCategorizeSaveHook', true );
104 -
105 - ## Infrastructure
106 - # Hook our own CSS:
107 - $wgHooks['OutputPageParserOutput'][] = 'fnCategorizeOutputHook';
108 - # Hook up local messages:
109 - $wgHooks['LoadAllMessages'][] = 'fnCategorizeMessageHook';
110 -}
111 -
112 -## Load the file containing the hook functions:
113 -require_once( 'Categorize.body.php' );
 59+$wgHooks['EditPage::showEditForm:initial'][] = array( 'CategorizeHooks::fnCategorizeShowHook', false );
 60+$wgHooks['UploadForm:initial'][] = array( 'CategorizeHooks::fnCategorizeShowHook', true );
 61+$wgHooks['EditPage::attemptSave'][] = array( 'CategorizeHooks::fnCategorizeSaveHook', false );
 62+$wgHooks['UploadForm:BeforeProcessing'][] = array( 'CategorizeHooks::fnCategorizeSaveHook', true );
 63+$wgHooks['OutputPageParserOutput'][] = 'CategorizeHooks::fnCategorizeOutputHook';
 64+$wgHooks['LoadAllMessages'][] = 'CategorizeHooks::fnCategorizeMessageHook';
11465 ?>
Index: trunk/extensions/Categorize/Categorize.hooks.php
@@ -0,0 +1,151 @@
 2+<?php
 3+if ( !defined( 'MEDIAWIKI' ) )
 4+ die();
 5+
 6+class CategorizeHooks {
 7+ /*************************************************************************************/
 8+ ## Entry point for the hook and main worker function for editing the page:
 9+ public static function fnCategorizeShowHook( $m_isUpload = false, &$m_pageObj ) {
 10+ global $wgOut, $wgParser, $wgTitle, $wgRequest, $wgScriptPath;
 11+ global $wgTitle, $wgScriptPath, $wgCategorizeCloud, $wgCategorizejs, $wgCategorizecss;
 12+ global $wgCategorizeLabels;
 13+
 14+ # Get ALL categories from wiki:
 15+ // $m_allCats = fnAjaxSuggestGetAllCategories();
 16+ # Get the right member variables, depending on if we're on an upload form or not:
 17+ if( !$m_isUpload ) {
 18+ # Check if page is subpage once to save method calls later:
 19+ $m_isSubpage = $wgTitle->isSubpage();
 20+
 21+ # Check if page has been submitted already to Preview or Show Changes
 22+ $strCatsFromPreview = trim($wgRequest->getVal('txtSelectedCategories2'));
 23+ if(strlen($strCatsFromPreview)==0){
 24+ # Extract all categorylinks from PAGE:
 25+ $m_pageCats = CategorizeBody::fnCategorizeGetPageCategories( $m_pageObj );
 26+ } else {
 27+ # Get cats from preview
 28+ $m_pageCats = explode(";",$strCatsFromPreview);
 29+ }
 30+ # Never ever use editFormTextTop here as it resides outside the <form> so we will never get contents
 31+ $m_place = 'editFormTextAfterWarn';
 32+ # Print the localised title for the select box:
 33+ $m_textBefore = '<b>'. wfMsg( 'categorize-title' ) . '</b>:';
 34+ } else {
 35+ # No need to get categories:
 36+ $m_pageCats = array();
 37+
 38+ # Place output at the right place:
 39+ $m_place = 'uploadFormTextAfterSummary';
 40+ }
 41+
 42+ #ADD EXISTING CATEGORIES TO INPUT BOX
 43+ $arrExistingCats = array();
 44+ $arrExistingCats = $m_pageCats;
 45+ #ADD JAVASCRIPT - use document.write so it is not presented if javascript is disabled.
 46+ $m_pageObj->$m_place .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"$wgScriptPath/extensions/Categorize/Categorize.css\" />
 47+ \n"; # provisoire
 48+ $m_pageObj->$m_place .= "<script type=\"text/javascript\" src=\"$wgScriptPath/extensions/Categorize/jquery.js\"></script>\n";
 49+ $m_pageObj->$m_place .= "<script type=\"text/javascript\">var xSelectedLabels = new Array();</script>\n";
 50+ foreach($arrExistingCats as $arrExistingCat)
 51+ {
 52+ $m_pageObj->$m_place .= "<script type=\"text/javascript\">xSelectedLabels['$arrExistingCat']=1;</script>\n";
 53+ }
 54+ $m_pageObj->$m_place .= "<script type=\"text/javascript\" src=\"" . $wgCategorizejs . "\"></script>\n";
 55+ $m_pageObj->$m_place .= "<script type=\"text/javascript\">/*<![CDATA[*/\n";
 56+ $m_pageObj->$m_place .= "document.write(\"<div id='categoryselectmaster2'><div style='border-bottom:1px solid #AAAAAA;'><b>" .wfMsg( 'categorize-title' ). "</b></div>\");\n";
 57+ $m_pageObj->$m_place .= "document.write(\"<p>" . wfMsg( 'categorize-subtitle' ). "</p>\");\n";
 58+ $m_pageObj->$m_place .= "document.write(\"\");\n";
 59+ $m_pageObj->$m_place .= "document.write(\"<input onkeyup='sendRequest(this,event);' autocomplete='off' type='text' name='txtSelectedCategories2' id='txtSelectedCategories2' maxlength='200' length='150' style='width:100%;' value='".str_replace("_"," ",implode(";", $arrExistingCats))."'/>\");\n";
 60+ $m_pageObj->$m_place .= "document.write(\"<br/><div id='searchResults'></div>\");\n";
 61+ $m_pageObj->$m_place .= "document.write(\"<input type='hidden' value='" . $wgCategorySuggestCloud . "' id='txtCSDisplayType'/>\");\n";
 62+ $m_pageObj->$m_place .= "document.write(\"<p>" . wfMsg( 'categorize-advice' ). "</p>\");\n";
 63+ $m_pageObj->$m_place .= "document.write(\"<p><table id='xtable'>\");\n";
 64+ $l__categorize_index = 0;
 65+ foreach($wgCategorizeLabels as $l__label_key=>$l__label_array)
 66+ {
 67+ $m_pageObj->$m_place .= "document.write(\"<tr>\");\n";
 68+ if (substr($l__label_key,0,9)=='separator')
 69+ {
 70+ $m_pageObj->$m_place .= "document.write(\"<td colspan=2> <hr/>\");\n";
 71+ }
 72+ else
 73+ {
 74+ $l__categorize_index += 1;
 75+ $l__key_value_to_print = utf8_encode(str_replace("_"," ",$l__label_key));
 76+ $l__xselected = (in_array($l__key_value_to_print,$arrExistingCats)) ? 'xselected' : '';
 77+ $m_pageObj->$m_place .= "document.write(\"<th style='text-align:left;'><span class='xlabel xcategorize$l__categorize_index $l__xselected'>$l__key_value_to_print</span> :</th><td> \");\n";
 78+ foreach($l__label_array as $l__label_value)
 79+ {
 80+ $l__label_value_to_print = utf8_encode(str_replace("_"," ",$l__label_value));
 81+ $l__xselected = (in_array($l__label_value_to_print,$arrExistingCats)) ? 'xselected' : '';
 82+ $m_pageObj->$m_place .= "document.write(\"<span class='xlabel xcategorize$l__categorize_index $l__xselected'>$l__label_value_to_print</span>\");\n";
 83+ }
 84+ $m_pageObj->$m_place .= "document.write(\"</td></tr>\");\n";
 85+ }
 86+ }
 87+ $m_pageObj->$m_place .= "document.write(\"</table></p>\");\n";
 88+ $m_pageObj->$m_place .= "document.write(\"<p>" . wfMsg( 'categorize-footer' ). "</p>\");\n";
 89+ $m_pageObj->$m_place .= "document.write(\"</div>\");\n";
 90+ $m_pageObj->$m_place .= "/*]]>*/</script>\n";
 91+
 92+
 93+ return true;
 94+ }
 95+
 96+ /*************************************************************************************/
 97+ ## Entry point for the hook and main worker function for saving the page:
 98+ public static function fnCategorizeSaveHook( $m_isUpload, $m_pageObj ) {
 99+ global $wgContLang;
 100+ global $wgOut;
 101+
 102+ # Get localised namespace string:
 103+ $m_catString = $wgContLang->getNsText( NS_CATEGORY );
 104+ # Get some distance from the rest of the content:
 105+ $m_text = "\n";
 106+
 107+ # Assign all selected category entries:
 108+ $strSelectedCats = $_POST['txtSelectedCategories2'];
 109+
 110+ #CHECK IF USER HAS SELECTED ANY CATEGORIES
 111+ if(strlen($strSelectedCats)>1){
 112+ $arrSelectedCats = array();
 113+ $arrSelectedCats = explode(";",$_POST['txtSelectedCategories2']);
 114+ # !!!!!!!!!!!!!!!! TODO d�doublonner les cat�gories ICI !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 115+ foreach( $arrSelectedCats as $m_cat ) {
 116+ if(strlen($m_cat)>0){
 117+ $m_text .= "\n[[$m_catString:" . mysql_escape_string(trim($m_cat)) . "]]";
 118+ }
 119+ }
 120+ # If it is an upload we have to call a different method:
 121+ if ( $m_isUpload ) {
 122+ $m_pageObj->mUploadDescription .= $m_text;
 123+ } else{
 124+ $m_pageObj->textbox1 .= $m_text;
 125+ }
 126+ }
 127+ $wgOut->addHTML($m_text);
 128+
 129+ # Return to the let MediaWiki do the rest of the work:
 130+ return true;
 131+ }
 132+
 133+ /*************************************************************************************/
 134+ ## Entry point for the CSS:
 135+ public static function fnCategorizeOutputHook( &$m_pageObj, $m_parserOutput ) {
 136+ global $wgScriptPath;
 137+
 138+ # Register CSS file for input box:
 139+ $m_pageObj->addLink(
 140+ array(
 141+ 'rel' => 'stylesheet',
 142+ 'type' => 'text/css',
 143+ 'href' => $wgScriptPath . '/extensions/Categorize/Categorize.css'
 144+ )
 145+ );
 146+
 147+ return true;
 148+ }
 149+
 150+}
 151+
 152+?>
\ No newline at end of file
Property changes on: trunk/extensions/Categorize/Categorize.hooks.php
___________________________________________________________________
Added: svn:eol-style
1153 + native
Index: trunk/extensions/Categorize/Categorize.js
@@ -48,7 +48,6 @@
4949
5050 strQueryR = strQuery.replace(/\>|\</g,"");
5151 if ( strQueryR != strQuery ) {
52 -// alert("Removing invalid characters '<', '>', or '|'." );
5352 strQuery = strQueryR;
5453 q.value = strQueryR;
5554 }
@@ -57,12 +56,50 @@
5857 if ( strQuery.toString() != csQuery.toString() ) {
5958 strQuery = strQuery.replace(/ /g,"_");
6059 csQuery = strQuery;
61 - sajax_debug_mode = false;
62 - sajax_do_call( "fnCategorizeAjax", [ strQuery ], ajaxResponse );
 60+ $.getJSON("api.php?action=query&format=json&list=categorize&catstrquery="+strQuery,
 61+ function(data) {
 62+ $.each(data.query.categorize, function(i,item){
 63+
 64+ });
 65+ // resultSet = response.responseText;
 66+ var resultDiv = document.getElementById('searchResults');
 67+ displayType = document.getElementById('txtCSDisplayType').name;
 68+ resultDiv.innerHTML = '';
 69+ resultDiv.style.display = 'block';
 70+ if (!data) {resultDiv.style.display = 'none'; } // TODO
 71+ else{
 72+ resultDiv.style.visibility = 'visible';
 73+ wideResult = false;
 74+ $.each(data.query.categorize, function(i,item){
 75+ if ( displayType != 'Cloud' ) {
 76+ var result=document.createElement("p");
 77+ }
 78+ else {
 79+ var result=document.createElement("span");
 80+ }
 81+ result.name = item.replace(/_/g," ");
 82+ csWord = result.name;
 83+
 84+ csHTML = '<span class="csSelect">' + csWord.substr(0, csQuery.length) + '</span>' + csWord.substr(csQuery.length) + " ";
 85+ result.innerHTML = csHTML;
 86+ result.onmouseover = highlight;
 87+ result.onmouseout = unHighlight;
 88+ result.onmousedown = selectEntry;
 89+ result.title = 'Click here to add category to the category list!';
 90+ result.className="cs";
 91+ resultDiv.style.lineHeight='1';
 92+ resultDiv.appendChild(result);
 93+ });
 94+ }
 95+
 96+
 97+ });
 98+
 99+
63100 }
64101 }
65102 // WAIT FOR SERVER RESPONSE AND DISPLAY SUGGESTIONS
66 -ajaxResponse = function handleResponse(response) {
 103+ajaxResponse = function handleResponse(response) {
67104 resultSet = response.responseText;
68105 var resultDiv = document.getElementById('searchResults');
69106 displayType = document.getElementById('txtCSDisplayType').name;
Index: trunk/extensions/Categorize/Categorize.api.php
@@ -0,0 +1,97 @@
 2+<?php
 3+/**
 4+ * Created on May 05, 2011
 5+ *
 6+ * Categorize extension
 7+ *
 8+ * Copyright (C) 2011 faure dot thomas at gmail dot com
 9+ *
 10+ * This program is free software; you can redistribute it and/or modify
 11+ * it under the terms of the GNU General Public License as published by
 12+ * the Free Software Foundation; either version 2 of the License, or
 13+ * (at your option) any later version.
 14+ *
 15+ * This program is distributed in the hope that it will be useful,
 16+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
 17+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 18+ * GNU General Public License for more details.
 19+ *
 20+ * You should have received a copy of the GNU General Public License along
 21+ * with this program; if not, write to the Free Software Foundation, Inc.,
 22+ * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 23+ * http://www.gnu.org/copyleft/gpl.html
 24+ */
 25+/**
 26+ * Query module to get the list of the Categories beginning by a given string.
 27+ *
 28+ * @ingroup API
 29+ * @ingroup Extensions
 30+ */
 31+class ApiQueryCategorize extends ApiQueryBase {
 32+ public function __construct( $query, $moduleName ) {
 33+ parent::__construct( $query, $moduleName, 'cat' );
 34+ }
 35+ public function execute() {
 36+ $params = $this->extractRequestParams();
 37+ $strquery = $params['strquery'];
 38+ $result = $this->getResult();
 39+
 40+ if(isset($strquery) && $strquery != NULL) {
 41+ $searchString = str_replace( '%' , '\%' , $strquery );
 42+ $searchString = str_replace( '_' , '\_' , $searchString );
 43+ $searchString = str_replace( '|' , '%' , $searchString );
 44+ $dbr = $this->getDB();;
 45+
 46+ $suggestStrings = array();
 47+
 48+ $this->addTables( 'categorylinks' );
 49+ $this->addFields( 'DISTINCT cl_to' );
 50+ $this->addWhere ( " UPPER(CONVERT(cl_to using latin1)) LIKE UPPER(CONVERT('$searchString%' using latin1)) ");
 51+ $res = $this->select( __METHOD__ );
 52+ while ( $row = $res->fetchObject() ) {
 53+ array_push($suggestStrings,$row->cl_to);
 54+ $fit = $result->addValue( array( 'query', $this->getModuleName() ), null, $row->cl_to );
 55+ if ( !$fit ) {
 56+ $this->setContinueEnumParameter( 'start', wfTimestamp( TS_ISO_8601, $row->afl_timestamp ) );
 57+ break;
 58+ }
 59+ }
 60+ $dbr->freeResult( $res );
 61+ }
 62+ $result->setIndexedTagName_internal( array( 'query', $this->getModuleName() ), 'category' );
 63+ }
 64+
 65+ public function getAllowedParams() {
 66+ return array(
 67+ 'strquery' => array(
 68+ ApiBase::PARAM_TYPE => 'string'
 69+ )
 70+ );
 71+ }
 72+
 73+ public function getParamDescription() {
 74+ return array(
 75+ 'strquery' => 'The string to search'
 76+ );
 77+ }
 78+
 79+ public function getDescription() {
 80+ return 'Show categories beginning by "strquery" string.';
 81+ }
 82+
 83+ public function getPossibleErrors() {
 84+ return array_merge( parent::getPossibleErrors(), array(
 85+ // to fill
 86+ ) );
 87+ }
 88+
 89+ protected function getExamples() {
 90+ return array(
 91+ 'api.php?action=query&list=categorize&catstrquery=helloworld'
 92+ );
 93+ }
 94+
 95+ public function getVersion() {
 96+ return __CLASS__ . ': $Id: Categorize.api.php xxxxx 2010-05-09 10:04:00Z Faure.thomas $';
 97+ }
 98+}
\ No newline at end of file
Property changes on: trunk/extensions/Categorize/Categorize.api.php
___________________________________________________________________
Added: svn:eol-style
199 + native
Index: trunk/extensions/Categorize/Categorize.body.php
@@ -1,9 +1,9 @@
22 <?php
33 /* Categorize Mediawiki Extension
44 *
5 - * @author Andreas Rindler (mediawiki at jenandi dot com) for initial Extension:CategorySuggest and Thomas Faur� for Categorize improvments
 5+ * @author Andreas Rindler (mediawiki at jenandi dot com) for initial Extension:CategorySuggest and Thomas Faur� (faure dot thomas at gmail dot com) for Categorize improvments
66 * @credits
7 - * @licence GNU General Public Licence 2.0 or later
 7+ * @licence GNU General Public Licence 3.0
88 * @description
99 *
1010 */
@@ -13,248 +13,87 @@
1414 die();
1515 }
1616
17 -/*************************************************************************************/
18 -## Entry point for the hook and main worker function for editing the page:
19 -function fnCategorizeShowHook( $m_isUpload = false, &$m_pageObj ) {
20 - global $wgOut, $wgParser, $wgTitle, $wgRequest, $wgScriptPath;
21 - global $wgTitle, $wgScriptPath, $wgCategorizeCloud, $wgCategorizejs, $wgCategorizecss;
22 - global $wgCategorizeLabels;
 17+class CategorizeBody {
 18+ /*************************************************************************************/
 19+ ## Returns an array with the categories the articles is in.
 20+ ## Also removes them from the text the user views in the editbox.
 21+ public static function fnCategorizeGetPageCategories( $m_pageObj ) {
 22+ global $wgOut;
2323
24 - # Get ALL categories from wiki:
25 -// $m_allCats = fnAjaxSuggestGetAllCategories();
26 - # Load system messages:
27 - fnCategorizeMessageHook();
28 - # Get the right member variables, depending on if we're on an upload form or not:
29 - if( !$m_isUpload ) {
30 - # Check if page is subpage once to save method calls later:
31 - $m_isSubpage = $wgTitle->isSubpage();
 24+ # Get page contents:
 25+ $m_pageText = $m_pageObj->textbox1;
3226
33 - # Check if page has been submitted already to Preview or Show Changes
34 - $strCatsFromPreview = trim($wgRequest->getVal('txtSelectedCategories2'));
35 - if(strlen($strCatsFromPreview)==0){
36 - # Extract all categorylinks from PAGE:
37 - $m_pageCats = fnCategorizeGetPageCategories( $m_pageObj );
38 - } else {
39 - # Get cats from preview
40 - $m_pageCats = explode(";",$strCatsFromPreview);
41 - }
42 - # Never ever use editFormTextTop here as it resides outside the <form> so we will never get contents
43 - $m_place = 'editFormTextAfterWarn';
44 - # Print the localised title for the select box:
45 - $m_textBefore = '<b>'. wfMsg( 'categorize-title' ) . '</b>:';
46 - } else {
47 - # No need to get categories:
48 - $m_pageCats = array();
 27+ $arrAllCats = Array();
 28+ $regulartext ='';
 29+ $nowikitext = '';
 30+ $cleanedtext ='';
 31+ $finaltext = '';
 32+ # Check linewise for category links:
 33+ # Get the first part of the text up until the first <nowiki> tag.
 34+ $arrBlocks1 = explode( "<nowiki>", $m_pageText );
 35+ $regulartext = $arrBlocks1[0];
 36+
 37+ # Get and strip categories from the first part
 38+ $cleanedtext = CategorizeBody::fnCategorizeStripCats($regulartext,$arrAllCats);
 39+ $finaltext .= $cleanedtext;
4940
50 - # Place output at the right place:
51 - $m_place = 'uploadFormTextAfterSummary';
52 - }
53 -
54 - #ADD EXISTING CATEGORIES TO INPUT BOX
55 - $arrExistingCats = array();
56 - $arrExistingCats = $m_pageCats;
57 - #ADD JAVASCRIPT - use document.write so it is not presented if javascript is disabled.
58 - $m_pageObj->$m_place .= "<link rel=\"stylesheet\" type=\"text/css\" href=\"$wgScriptPath/extensions/Categorize/Categorize.css\" />
59 -\n"; # provisoire
60 - $m_pageObj->$m_place .= "<script type=\"text/javascript\" src=\"$wgScriptPath/extensions/Categorize/jquery.js\"></script>\n";
61 - $m_pageObj->$m_place .= "<script type=\"text/javascript\">var xSelectedLabels = new Array();</script>\n";
62 - foreach($arrExistingCats as $arrExistingCat)
63 - {
64 - $m_pageObj->$m_place .= "<script type=\"text/javascript\">xSelectedLabels['$arrExistingCat']=1;</script>\n";
65 - }
66 - $m_pageObj->$m_place .= "<script type=\"text/javascript\" src=\"" . $wgCategorizejs . "\"></script>\n";
67 - $m_pageObj->$m_place .= "<script type=\"text/javascript\">/*<![CDATA[*/\n";
68 - $m_pageObj->$m_place .= "document.write(\"<div id='categoryselectmaster2'><div style='border-bottom:1px solid #AAAAAA;'><b>" .wfMsg( 'categorize-title' ). "</b></div>\");\n";
69 - $m_pageObj->$m_place .= "document.write(\"<p>" . wfMsg( 'categorize-subtitle' ). "</p>\");\n";
70 - $m_pageObj->$m_place .= "document.write(\"\");\n";
71 - $m_pageObj->$m_place .= "document.write(\"<input onkeyup='sendRequest(this,event);' autocomplete='off' type='text' name='txtSelectedCategories2' id='txtSelectedCategories2' maxlength='200' length='150' style='width:100%;' value='".str_replace("_"," ",implode(";", $arrExistingCats))."'/>\");\n";
72 - $m_pageObj->$m_place .= "document.write(\"<br/><div id='searchResults'></div>\");\n";
73 - $m_pageObj->$m_place .= "document.write(\"<input type='hidden' value='" . $wgCategorySuggestCloud . "' id='txtCSDisplayType'/>\");\n";
74 - $m_pageObj->$m_place .= "document.write(\"<p>" . wfMsg( 'categorize-advice' ). "</p>\");\n";
75 - $m_pageObj->$m_place .= "document.write(\"<p><table id='xtable'>\");\n";
76 - $l__categorize_index = 0;
77 - foreach($wgCategorizeLabels as $l__label_key=>$l__label_array)
78 - {
79 - $m_pageObj->$m_place .= "document.write(\"<tr>\");\n";
80 - if (substr($l__label_key,0,9)=='separator')
81 - {
82 - $m_pageObj->$m_place .= "document.write(\"<td colspan=2> <hr/>\");\n";
 41+ # Go through the rest of the blocks to find more categories
 42+ for($i=1; $i<count($arrBlocks1); $i++){
 43+ $arrBlocks2 = explode( "</nowiki>", $arrBlocks1[$i] );
 44+ //ignore cats here because it is part of the <nowiki> block
 45+ $nowikitext = $arrBlocks2[0];
 46+ //add to final text
 47+ $finaltext .= '<nowiki>' . $nowikitext . '</nowiki> ';
 48+
 49+ //strip cats here because it's the text after the <nowiki> block
 50+ $regulartext = $arrBlocks2[1];
 51+ $cleanedtext = CategorizeBody::fnCategorizeStripCats($regulartext,$arrAllCats);
 52+ $finaltext .= ltrim($cleanedtext);
8353 }
84 - else
85 - {
86 - $l__categorize_index += 1;
87 - $l__key_value_to_print = utf8_encode(str_replace("_"," ",$l__label_key));
88 - $l__xselected = (in_array($l__key_value_to_print,$arrExistingCats)) ? 'xselected' : '';
89 - $m_pageObj->$m_place .= "document.write(\"<th style='text-align:left;'><span class='xlabel xcategorize$l__categorize_index $l__xselected'>$l__key_value_to_print</span> :</th><td> \");\n";
90 - foreach($l__label_array as $l__label_value)
91 - {
92 - $l__label_value_to_print = utf8_encode(str_replace("_"," ",$l__label_value));
93 - $l__xselected = (in_array($l__label_value_to_print,$arrExistingCats)) ? 'xselected' : '';
94 - $m_pageObj->$m_place .= "document.write(\"<span class='xlabel xcategorize$l__categorize_index $l__xselected'>$l__label_value_to_print</span>\");\n";
95 - }
96 - $m_pageObj->$m_place .= "document.write(\"</td></tr>\");\n";
97 - }
98 - }
99 - $m_pageObj->$m_place .= "document.write(\"</table></p>\");\n";
100 - $m_pageObj->$m_place .= "document.write(\"<p>" . wfMsg( 'categorize-footer' ). "</p>\");\n";
101 - $m_pageObj->$m_place .= "document.write(\"</div>\");\n";
102 - $m_pageObj->$m_place .= "/*]]>*/</script>\n";
103 -
104 -
105 - return true;
106 -}
10754
108 -/*************************************************************************************/
109 -## Entry point for the hook and main worker function for saving the page:
110 -function fnCategorizeSaveHook( $m_isUpload, $m_pageObj ) {
111 - global $wgContLang;
112 - global $wgOut;
113 -
114 - # Get localised namespace string:
115 - $m_catString = $wgContLang->getNsText( NS_CATEGORY );
116 - # Get some distance from the rest of the content:
117 - $m_text = "\n";
118 -
119 - # Assign all selected category entries:
120 - $strSelectedCats = $_POST['txtSelectedCategories2'];
121 -
122 - #CHECK IF USER HAS SELECTED ANY CATEGORIES
123 - if(strlen($strSelectedCats)>1){
124 - $arrSelectedCats = array();
125 - $arrSelectedCats = explode(";",$_POST['txtSelectedCategories2']);
126 - # !!!!!!!!!!!!!!!! TODO d�doublonner les cat�gories ICI !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
127 - foreach( $arrSelectedCats as $m_cat ) {
128 - if(strlen($m_cat)>0){
129 - $m_text .= "\n[[$m_catString:" . mysql_escape_string(trim($m_cat)) . "]]";
130 - }
131 - }
132 - # If it is an upload we have to call a different method:
133 - if ( $m_isUpload ) {
134 - $m_pageObj->mUploadDescription .= $m_text;
135 - } else{
136 - $m_pageObj->textbox1 .= $m_text;
137 - }
138 - }
139 - $wgOut->addHTML($m_text);
140 -
141 - # Return to the let MediaWiki do the rest of the work:
142 - return true;
143 -}
144 -
145 -/*************************************************************************************/
146 -## Entry point for the CSS:
147 -function fnCategorizeOutputHook( &$m_pageObj, $m_parserOutput ) {
148 - global $wgScriptPath;
149 -
150 - # Register CSS file for input box:
151 - $m_pageObj->addLink(
152 - array(
153 - 'rel' => 'stylesheet',
154 - 'type' => 'text/css',
155 - 'href' => $wgScriptPath . '/extensions/Categorize/Categorize.css'
156 - )
157 - );
158 -
159 - return true;
160 -}
161 -
162 -
163 -/*************************************************************************************/
164 -## Entry point for localised messages:
165 -function fnCategorizeMessageHook() {
166 - global $wgLang;
167 - global $wgMessageCache;
168 -
169 - # Initialize array of all messages:
170 - $messages=array();
171 - # Load default messages (english):
172 - include( 'Categorize.i18n.php' );
173 - # Load localised messages:
174 - $wgMessageCache->addMessagesByLang($messages);
175 -
176 - return true;
177 -}
178 -
179 -/*************************************************************************************/
180 -## Returns an array with the categories the articles is in.
181 -## Also removes them from the text the user views in the editbox.
182 -function fnCategorizeGetPageCategories( $m_pageObj ) {
183 -global $wgOut;
184 -
185 - # Get page contents:
186 - $m_pageText = $m_pageObj->textbox1;
187 -
188 - $arrAllCats = Array();
189 - $regulartext ='';
190 - $nowikitext = '';
191 - $cleanedtext ='';
192 - $finaltext = '';
193 - # Check linewise for category links:
194 - # Get the first part of the text up until the first <nowiki> tag.
195 - $arrBlocks1 = explode( "<nowiki>", $m_pageText );
196 - $regulartext = $arrBlocks1[0];
197 -
198 - # Get and strip categories from the first part
199 - $cleanedtext = fnCategorizeStripCats($regulartext,$arrAllCats);
200 - $finaltext .= $cleanedtext;
201 -
202 - # Go through the rest of the blocks to find more categories
203 - for($i=1; $i<count($arrBlocks1); $i++){
204 - $arrBlocks2 = explode( "</nowiki>", $arrBlocks1[$i] );
205 - //ignore cats here because it is part of the <nowiki> block
206 - $nowikitext = $arrBlocks2[0];
207 - //add to final text
208 - $finaltext .= '<nowiki>' . $nowikitext . '</nowiki> ';
 55+ //Place cleaned text back into the text box:
 56+ $m_pageObj->textbox1 = rtrim( $finaltext );
20957
210 - //strip cats here because it's the text after the <nowiki> block
211 - $regulartext = $arrBlocks2[1];
212 - $cleanedtext = fnCategorizeStripCats($regulartext,$arrAllCats);
213 - $finaltext .= ltrim($cleanedtext);
 58+ return $arrAllCats;
 59+
21460 }
21561
216 - //Place cleaned text back into the text box:
217 - $m_pageObj->textbox1 = rtrim( $finaltext );
218 -
219 - return $arrAllCats;
220 -
221 -}
 62+ public static function fnCategorizeStripCats($texttostrip, &$catsintext){
 63+ global $wgContLang, $wgOut;
22264
223 -function fnCategorizeStripCats($texttostrip, &$catsintext){
224 - global $wgContLang, $wgOut;
 65+ # Get localised namespace string:
 66+ $m_catString = strtolower( $wgContLang->getNsText( NS_CATEGORY ) );
 67+ # The regular expression to find the category links:
 68+ $m_pattern = "\[\[({$m_catString}|category):(.*)\]\]";
 69+ $m_replace = "$2";
 70+ # The container to store all found category links:
 71+ $m_catLinks = array ();
 72+ # The container to store the processed text:
 73+ $m_cleanText = '';
22574
226 - # Get localised namespace string:
227 - $m_catString = strtolower( $wgContLang->getNsText( NS_CATEGORY ) );
228 - # The regular expression to find the category links:
229 - $m_pattern = "\[\[({$m_catString}|category):(.*)\]\]";
230 - $m_replace = "$2";
231 - # The container to store all found category links:
232 - $m_catLinks = array ();
233 - # The container to store the processed text:
234 - $m_cleanText = '';
23575
 76+ # Check linewise for category links:
 77+ foreach( explode( "\n", $texttostrip ) as $m_textLine ) {
 78+ # Filter line through pattern and store the result:
 79+ $m_cleanText .= rtrim( preg_replace( "/{$m_pattern}/i", "", $m_textLine ) ) . "\n";
23680
237 - # Check linewise for category links:
238 - foreach( explode( "\n", $texttostrip ) as $m_textLine ) {
239 - # Filter line through pattern and store the result:
240 - $m_cleanText .= rtrim( preg_replace( "/{$m_pattern}/i", "", $m_textLine ) ) . "\n";
241 -
242 - # Check if we have found a category, else proceed with next line:
243 - if( preg_match_all( "/{$m_pattern}/i", $m_textLine,$catsintext2,PREG_SET_ORDER) ){
244 - foreach( $catsintext2 as $local_cat => $m_prefix ) {
245 - //Set first letter to upper case to match MediaWiki standard
246 - $strFirstLetter = substr($m_prefix[2], 0,1);
247 - strtoupper($strFirstLetter);
248 - $newString = strtoupper($strFirstLetter) . substr($m_prefix[2], 1);
249 - array_push($catsintext,$newString);
250 -
251 - }
252 - # Get the category link from the original text and store it in our list:
253 - preg_replace( "/.*{$m_pattern}/i", $m_replace, $m_textLine,-1,$intNumber );
 81+ # Check if we have found a category, else proceed with next line:
 82+ if( preg_match_all( "/{$m_pattern}/i", $m_textLine,$catsintext2,PREG_SET_ORDER) ){
 83+ foreach( $catsintext2 as $local_cat => $m_prefix ) {
 84+ //Set first letter to upper case to match MediaWiki standard
 85+ $strFirstLetter = substr($m_prefix[2], 0,1);
 86+ strtoupper($strFirstLetter);
 87+ $newString = strtoupper($strFirstLetter) . substr($m_prefix[2], 1);
 88+ array_push($catsintext,$newString);
 89+
 90+ }
 91+ # Get the category link from the original text and store it in our list:
 92+ preg_replace( "/.*{$m_pattern}/i", $m_replace, $m_textLine,-1,$intNumber );
 93+ }
 94+
25495 }
 96+ return $m_cleanText;
25597
25698 }
257 -
258 - return $m_cleanText;
259 -
260 -}
 99+ }
261100 ?>

Comments

#Comment by Raymond (talk | contribs)   12:36, 9 May 2011

Please fix English texts too. They contain French test like:

	'categorize-taglabel'    => 'Catégories populaires',

Furthermore you use an editor with a wrong encoding:

-	'author'      => 'Thomas Fauré',
+	'author'      => 'Thomas Faur�',
#Comment by Faure.thomas (talk | contribs)   12:39, 9 May 2011

right encoding is UTF-8, isn't it ?

#Comment by Raymond (talk | contribs)   12:45, 9 May 2011

yes

#Comment by Faure.thomas (talk | contribs)   12:47, 9 May 2011

ok thanks, I will correct it, I was in ANSI...

Status & tagging log