Merge branch 'master' into Wikidata
[lhc/web/wiklou.git] / resources / mediawiki.api / mediawiki.api.category.js
1 /**
2 * Additional mw.Api methods to assist with API calls related to categories.
3 */
4
5 ( function( $, mw, undefined ) {
6
7 $.extend( mw.Api.prototype, {
8 /**
9 * Determine if a category exists.
10 * @param title {mw.Title}
11 * @param success {Function} callback to pass boolean of category's existence
12 * @param err {Function} optional callback to run if api error
13 * @return ajax call object
14 */
15 isCategory: function( title, success, err ) {
16 var params = {
17 prop: 'categoryinfo',
18 titles: title.toString()
19 },
20 ok = function( data ) {
21 var exists = false;
22 if ( data.query && data.query.pages ) {
23 $.each( data.query.pages, function( id, page ) {
24 if ( page.categoryinfo ) {
25 exists = true;
26 }
27 } );
28 }
29 success( exists );
30 };
31
32 return this.get( params, { ok: ok, err: err } );
33 },
34
35 /**
36 * Get a list of categories that match a certain prefix.
37 * e.g. given "Foo", return "Food", "Foolish people", "Foosball tables" ...
38 * @param prefix {String} prefix to match
39 * @param success {Function} callback to pass matched categories to
40 * @param err {Function} optional callback to run if api error
41 * @return {jqXHR}
42 */
43 getCategoriesByPrefix: function( prefix, success, err ) {
44
45 // fetch with allpages to only get categories that have a corresponding description page.
46 var params = {
47 'list': 'allpages',
48 'apprefix': prefix,
49 'apnamespace': mw.config.get('wgNamespaceIds').category
50 };
51
52 var ok = function( data ) {
53 var texts = [];
54 if ( data.query && data.query.allpages ) {
55 $.each( data.query.allpages, function( i, category ) {
56 texts.push( new mw.Title( category.title ).getNameText() );
57 } );
58 }
59 success( texts );
60 };
61
62 return this.get( params, { ok: ok, err: err } );
63 },
64
65
66 /**
67 * Get the categories that a particular page on the wiki belongs to
68 * @param title {mw.Title}
69 * @param success {Function} callback to pass categories to (or false, if title not found)
70 * @param err {Function} optional callback to run if api error
71 * @param async {Boolean} optional asynchronousness (default = true = async)
72 * @return {jqXHR}
73 */
74 getCategories: function( title, success, err, async ) {
75 var params, ok;
76 params = {
77 prop: 'categories',
78 titles: title.toString()
79 };
80 if ( async === undefined ) {
81 async = true;
82 }
83 ok = function( data ) {
84 var ret = false;
85 if ( data.query && data.query.pages ) {
86 $.each( data.query.pages, function( id, page ) {
87 if ( page.categories ) {
88 if ( typeof ret !== 'object' ) {
89 ret = [];
90 }
91 $.each( page.categories, function( i, cat ) {
92 ret.push( new mw.Title( cat.title ) );
93 } );
94 }
95 } );
96 }
97 success( ret );
98 };
99
100 return this.get( params, { ok: ok, err: err, async: async } );
101 }
102
103 } );
104
105 } )( jQuery, mediaWiki );