AjaxDispatcher, now ~30 lines shorter and not using $_GET or $_POST
[lhc/web/wiklou.git] / includes / AjaxDispatcher.php
1 <?php
2 /**
3 * @defgroup Ajax Ajax
4 *
5 * @file
6 * @ingroup Ajax
7 * Handle ajax requests and send them to the proper handler.
8 */
9
10 if ( !( defined( 'MEDIAWIKI' ) && $wgUseAjax ) ) {
11 die( 1 );
12 }
13
14 require_once( 'AjaxFunctions.php' );
15
16 /**
17 * Object-Oriented Ajax functions.
18 * @ingroup Ajax
19 */
20 class AjaxDispatcher {
21 /** Name of the requested handler */
22 private $func_name = null;
23
24 /** Arguments passed */
25 private $args = array();
26
27 /** Load up our object with user supplied data */
28 public function __construct( WebRequest $req ) {
29 wfProfileIn( __METHOD__ );
30
31 $rs = $req->getVal( 'rs' );
32 if( $rs !== null ) {
33 $this->func_name = $rs;
34 }
35 $rsargs = $req->getVal( 'rsargs' );
36 if( $rsargs !== null ) {
37 $this->args = $rsargs;
38 }
39
40 wfProfileOut( __METHOD__ );
41 }
42
43 /** Pass the request to our internal function.
44 * BEWARE! Data are passed as they have been supplied by the user,
45 * they should be carefully handled in the function processing the
46 * request.
47 */
48 function performAction() {
49 global $wgAjaxExportList, $wgOut;
50
51 if ( is_null( $this->func_name ) ) {
52 return;
53 }
54
55 wfProfileIn( __METHOD__ );
56
57 if ( ! in_array( $this->func_name, $wgAjaxExportList ) ) {
58 wfDebug( __METHOD__ . ' Bad Request for unknown function ' . $this->func_name . "\n" );
59
60 wfHttpError(
61 400,
62 'Bad Request',
63 "unknown function " . (string) $this->func_name
64 );
65 } else {
66 wfDebug( __METHOD__ . ' dispatching ' . $this->func_name . "\n" );
67
68 if ( strpos( $this->func_name, '::' ) !== false ) {
69 $func = explode( '::', $this->func_name, 2 );
70 } else {
71 $func = $this->func_name;
72 }
73
74 try {
75 $result = call_user_func_array( $func, $this->args );
76
77 if ( $result === false || $result === null ) {
78 wfDebug( __METHOD__ . ' ERROR while dispatching '
79 . $this->func_name . "(" . var_export( $this->args, true ) . "): "
80 . "no data returned\n" );
81
82 wfHttpError( 500, 'Internal Error',
83 "{$this->func_name} returned no data" );
84 } else {
85 if ( is_string( $result ) ) {
86 $result = new AjaxResponse( $result );
87 }
88
89 $result->sendHeaders();
90 $result->printText();
91
92 wfDebug( __METHOD__ . ' dispatch complete for ' . $this->func_name . "\n" );
93 }
94 } catch ( Exception $e ) {
95 wfDebug( __METHOD__ . ' ERROR while dispatching '
96 . $this->func_name . "(" . var_export( $this->args, true ) . "): "
97 . get_class( $e ) . ": " . $e->getMessage() . "\n" );
98
99 if ( !headers_sent() ) {
100 wfHttpError( 500, 'Internal Error',
101 $e->getMessage() );
102 } else {
103 print $e->getMessage();
104 }
105 }
106 }
107
108 wfProfileOut( __METHOD__ );
109 $wgOut = null;
110 }
111 }