/var/www/html_it/wp-content/plugins/loco-translate/src/mvc/AjaxRouter.php


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
<?php
/**
 * Handles execution of Ajax actions and rendering of JSON
 */
class Loco_mvc_AjaxRouter extends Loco_hooks_Hookable {
    
    
/**
     * Current ajax controller
     * @var Loco_mvc_AjaxController
     */
    
private $ctrl;

    
/**
     * @var Loco_output_Buffer
     */
    
private $buffer;

    
/**
     * Generate a GET request URL containing required routing parameters
     * @param string $route
     * @param array $args
     * @return string
     */
    
public static function generate$route, array $args = [] ){
        
// validate route autoload if debugging
        
if( loco_debugging() ){
            
class_existsself::routeToClass($route) );
        }
        
$args +=  [
            
'route' => $route,
            
'action' => 'loco_ajax',
            
'loco-nonce' => wp_create_nonce($route),
        ];
        return 
admin_url('admin-ajax.php','relative').'?'.http_build_query($args);
    }


    
/**
     * Create a new ajax router and starts buffering output immediately
     */
    
public function __construct(){
        
$this->buffer Loco_output_Buffer::start();
        
parent::__construct();
    }


    
/**
     * "init" action callback.
     * early-ish hook that ensures controllers can initialize
     */
    
public function on_init(){
        try {
            
$class self::routeToClass$_REQUEST['route'] );
            
// autoloader will throw error if controller class doesn't exist
            
$this->ctrl = new $class;
            
$this->ctrl->_init$_REQUEST );
            
// hook name compatible with AdminRouter, plus additional action for ajax hooks to set up
            
do_action('loco_admin_init'$this->ctrl );
            
do_action('loco_ajax_init'$this->ctrl );
        }
        catch( 
Loco_error_Exception $e ){
            
$this->ctrl null;
            
// throw $e; // <- debug
        
}
    }

    
    
/**
     * @param string $route
     * @return string
     */
    
private static function routeToClass$route ){
        
$route explode'-'$route );
        
// convert route to class name, e.g. "foo-bar" => "Loco_ajax_foo_BarController"
        
$key count($route) - 1;
        
$route[$key] = ucfirst$route[$key] );
        return 
'Loco_ajax_'.implode('_',$route).'Controller';
    }


    
/**
     * Common ajax hook for all Loco admin JSON requests
     * Note that tests call renderAjax directly.
     * @codeCoverageIgnore
     */
    
public function on_wp_ajax_loco_json(){
        
$json $this->renderAjax();
        
$this->exitScript$json,  [
            
'Content-Type' => 'application/json; charset=UTF-8',
        ] );
    }


    
/**
     * Additional ajax hook for download actions that won't be JSON
     * Note that tests call renderDownload directly.
     * @codeCoverageIgnore
     */
    
public function on_wp_ajax_loco_download(){
        
$file null;
        
$ext null;
        
$data $this->renderDownload();
        if( 
is_string($data) ){
            
$path = ( $this->ctrl $this->ctrl->get('path') : '' ) or $path 'error.json';
            
$file = new Loco_fs_File$path );
            
$ext $file->extension();
        }
        else if( 
$data instanceof Exception ){
            
$data sprintf('%s in %s:%u'$data->getMessage(), basename($data->getFile()), $data->getLine() );
        }
        else {
            
$data = (string) $data;
        }
        
$mimes =  [
            
'po'   => 'application/x-gettext',
            
'pot'  => 'application/x-gettext',
            
'mo'   => 'application/x-gettext-translation',
            
'php'  => 'application/x-httpd-php-source',
            
'json' => 'application/json',
            
'zip'  => 'application/zip',
            
'xml'  => 'text/xml',
        ];
        
$headers = [];
        if( 
$file instanceof Loco_fs_File && isset($mimes[$ext]) ){
            
$headers['Content-Type'] = $mimes[$ext].'; charset=UTF-8';
            
$headers['Content-Disposition'] = 'attachment; filename='.$file->basename();
        }
        else {
            
$headers['Content-Type'] = 'text/plain; charset=UTF-8';
        }
        
$this->exitScript$data$headers );
    }


    
/**
     * Exit script before WordPress shutdown, avoids hijacking of exit via wp_die_ajax_handler.
     * Also gives us a final chance to check for output buffering problems.
     * @codeCoverageIgnore
     */
    
private function exitScript$str, array $headers ){
        try {
            
do_action('loco_admin_shutdown');
            
Loco_output_Buffer::clear();
            
$this->buffer null;
            
Loco_output_Buffer::check();
            
$headers['Content-Length'] = strlen($str);
            foreach( 
$headers as $name => $value ){
                
header$name.': '.$value );
            }
        }
        catch( 
Exception $e ){
            
Loco_error_AdminNotices::addLoco_error_Exception::convert($e) );
            
$str $e->getMessage();
        }
        echo 
$str;
        exit(
0);
    }


    
/**
     * Execute Ajax controller to render JSON response body
     * @return string
     */
    
public function renderAjax(){
        try {
            
// respond with deferred failure from initAjax
            
if( ! $this->ctrl ){
                
$route = isset($_REQUEST['route']) ? $_REQUEST['route'] : '';
                
// translators: Fatal error where %s represents an unexpected value
                
throw new Loco_error_Exceptionsprintf__('Ajax route not found: "%s"','loco-translate'), $route ) );
            }
            
// else execute controller to get json output
            
$json $this->ctrl->render();
            if( 
is_null($json) || '' === $json ){
                throw new 
Loco_error_Exception__('Ajax controller returned empty JSON','loco-translate') );
            }
        }
        catch( 
Loco_error_Exception $e ){
            
$json json_encode( [ 'error' => $e->jsonSerialize(), 'notices' => Loco_error_AdminNotices::destroy() ] );
        }
        catch( 
Exception $e ){
            
$e Loco_error_Exception::convert($e);
            
$json json_encode( [ 'error' => $e->jsonSerialize(), 'notices' => Loco_error_AdminNotices::destroy() ] );
        }
        
$this->buffer->discard();
        return 
$json;
    }


    
/**
     * Execute ajax controller to render something other than JSON
     * @return string|Exception
     */
    
public function renderDownload(){
        try {
            
// respond with deferred failure from initAjax
            
if( ! $this->ctrl ){
                throw new 
Loco_error_Exception__('Download action not found','loco-translate') );
            }
            
// else execute controller to get raw output
            
$data $this->ctrl->render();
            if( 
is_null($data) || '' === $data ){
                throw new 
Loco_error_Exception__('Download controller returned empty output','loco-translate') );
            }
        }
        catch( 
Exception $e ){
            
$data $e;
        }
        
$this->buffer->discard();
        return 
$data;
    }

}