Форум программистов, компьютерный форум, киберфорум
PHP для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.86/21: Рейтинг темы: голосов - 21, средняя оценка - 4.86
2 / 2 / 1
Регистрация: 18.11.2012
Сообщений: 94
1

Интересный syntax error, unexpected 'public' (T_PUBLIC)

19.03.2020, 09:53. Показов 3915. Ответов 3

Author24 — интернет-сервис помощи студентам
Всем привет!
Есть проблемка, над которой уже долгий час сижу.
Предистория
Дело в том, что есть плагин для вордпреса, который обробатывет форму и создает док. документ.
На сайте он работает с багами, то есть при создании страници часть php кода (условий) не выполняются, поэтому на выходе получаю не то что ожидаю.

Решил побороться локально и узнать суть проблемы.
Я создал локально сервер, поставил чистый вордпрес и загрузил всего один плагин.
В конструкторе плагина подключаются все необходимые php.
И вот к чему мы подходим. Плагин работает с шорткодами. Когда он видит на странице сайта шорткод типа [litigation_application form_id="Claim_For_Test"] - он выполняет свою работу (показывает форму и обробатывает данные для отправки).

Так вот, сейчас все упирается в скрипт shortcode.php, код прикрепляю.

PHP/HTML
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
<?php
/**
 * Shortcode
 */
 
defined( 'ABSPATH' ) || die();
 
/**
 * Class LitigationApplication.
 */
class LitigationApplication {
 
    private $forms = [];
    private $shortcode = 'litigation_application';
    private $is_litigation_application = false;
 
    /**
     * Constructor
     * */
    function __construct() {
 
        add_shortcode( $this->shortcode, [ &$this, 'viewLitigationApplicationMaster' ] );
        add_action( 'wp_enqueue_scripts', [ &$this, 'checkLitigationApplication' ], 1 );
        add_action( 'wp_enqueue_scripts', [ &$this, 'registerPluginScrips' ], 10 );
 
        // Fetch meta Ajax action
        add_action( 'wp_ajax_data_fetchmeta', [ &$this, 'fetchMeta' ] );
        add_action( 'wp_ajax_nopriv_data_fetchmeta', [ &$this, 'fetchMeta' ] );
 
        // Save Claims Ajax action
        add_action( 'wp_ajax_save_claims', [ &$this, 'saveClaims' ] );
        add_action( 'wp_ajax_nopriv_save_claims', [ &$this, 'saveClaims' ] );
    }
 
    public static function getPath() {
 
        $upload_dir = wp_get_upload_dir();
 
        $documents_dir = [ 'path' => $upload_dir['basedir'] . '/documents/', 'url' => $upload_dir['baseurl'] . '/documents/' ];
 
        if ( ! file_exists( $documents_dir['path'] ) ) {
 
            mkdir( $documents_dir['path'], 0755 );
 
            $fp = fopen( $documents_dir['path'] . 'index.php', 'wb' );
            fwrite( $fp, 'O_o' );
            fclose( $fp );
        }
 
        return $documents_dir;
    }
 
    public function saveClaims() {
 
        if ( ! wp_verify_nonce( sanitize_text_field( $_REQUEST['nonce_field'] ) , 'LitigationApplication' ) ) {
 
            // Security nonce field error.
            wp_die();
        }
 
        $data = self::sanitizeArray( $_REQUEST['data'] );
 
        $form_id = sanitize_text_field( $_REQUEST['form_id'] );
 
        $claim_title = wp_strip_all_tags( '[' . $_REQUEST['form_id'] . '] ' . $data['full_name'] );
 
        $claim_id = wp_insert_post(
            [
                'post_title'    => $claim_title,
                'post_status'   => 'publish',
                'post_type'     => 'wbl_claims',
            ]
        );
 
        if( is_wp_error( $claim_id ) ) {
 
            wp_die();
        } else {
 
            foreach ( $data as $key => $value ) {
 
                update_post_meta( $claim_id, $key, $value );
            }
 
            // Set all data
            update_post_meta( $claim_id, 'all_data', $data );
 
            // Set key
            $claim_key = crc32( $claim_id . $claim_title );
            update_post_meta( $claim_id, 'claim_key', $claim_key );
        }
 
        $claim_key = crc32( $claim_id . $claim_title );
 
        // Create document
        $document = $form_id::createDocument( $claim_id, $claim_key, $data );
 
        // Get payments form
        if ( $document ) {
 
            self::getPaymentsForm( $claim_id, $data['_wp_http_referer'] );
        }
 
        wp_die();
    }
 
    /**
     * Get Payments Form
     *
     * @param int $claim_id claim id.
     *
     * @return html
     */
    public static function getPaymentsForm( $claim_id, $page ) {
 
        // Get claim meta
        $meta = get_post_meta( $claim_id );
 
        // Set form id
        $form_id = $meta['form_id'][0];
        $claim_key = $meta['claim_key'][0];
 
        // Get form meta
        $form = $form_id::getFormMeta();
 
        // Get settings
        $settings = get_option( 'CFD_settings' );
 
        if ( isset( $settings['liqpay']['public_key'] ) && ! empty( $settings['liqpay']['public_key'] ) && isset( $settings['liqpay']['private_key'] ) && ! empty( $settings['liqpay']['private_key'] ) ) {
 
            $liqpay = new LiqPay( $settings['liqpay']['public_key'], $settings['liqpay']['private_key'] );
 
            $html = $liqpay->cnb_form(
                [
                    'action'        => 'pay',
                    'amount'        => $form['cost'],
                    'currency'      => 'UAH',
                    'language'      => 'uk', //ru, uk, en
                    'description'   => 'Сайт',
                    'order_id'      => $claim_id,
                    'version'       => '3',
                    'sandbox'       => $settings['liqpay']['sandbox'],
                    'result_url'    => $_SERVER['HTTP_REFERER'] . '?liqpay_action=1&order_id=' . $claim_id,
                    'server_url'    => $_SERVER['HTTP_REFERER'] . '?liqpay_action=1&order_id=' . $claim_id,
                ]
            );
 
            echo $html;
        }
    }
 
    /**
     * Get Payments Form
     *
     * @param int $claim_id claim id.
     *
     * @return void.
     */
    public static function getPaymentsStatus( $order_id , $action = 'status' ) {
 
        $settings = get_option( 'CFD_settings' );
 
        $liqpay = new LiqPay( $settings['liqpay']['public_key'], $settings['liqpay']['private_key'] );
 
        $res = $liqpay->api(
            'request',
                array(
                'action'        => $action,
                'version'       => '3',
                'order_id'      => $order_id,
            )
        );
 
        if( $res ) {
            $res = (array) $res;
 
            $data = array(
                    'date_check'        => date( 'd-m-Y H:i:s', current_time( 'timestamp', 0 ) ),
                    'action'            => $res['action'],
                    'status'            => $res['status'],
                    'amount'            => isset( $res['amount'] ) ? $res['amount'] : null,
                    'payment_id'        => isset( $res['payment_id'] ) ? $res['payment_id'] : null,
                    'create_date'       => isset( $res['create_date'] ) ? $res['create_date'] : null,
                    'end_date'          => isset( $res['end_date'] ) ? $res['end_date'] : null,
                    'err_code'          => isset( $res['err_code'] ) ? $res['err_code'] : null,
                    'err_description'   => isset( $res['err_description'] ) ? $res['err_description'] : null,
            );
 
            if ( add_post_meta( $order_id, 'liqpay_payment_status', $data ) ) {
 
                return $data;
            }
        }
 
        return false;
    }
 
    public function fetchMeta() {
 
        if ( ! wp_verify_nonce( sanitize_text_field( $_REQUEST['nonce_field'] ) , 'LitigationApplication' ) ) {
 
            // Security nonce field error.
            wp_die();
        }
 
        $id = absint( $_REQUEST['ID'] );
 
        if ( 0 === $id ) {
 
            echo 'Invalid Input';
            die();
        }
 
        $meta = get_post_meta( $id, 'address', true );
 
        if ( is_array( $meta ) && ! empty( $meta ) ) {
 
            foreach ( $meta as $value ) {
 
                if ( ! empty( $value ) ) {
 
                    echo $value . '</br>';
                }
            }
        }
 
        die();
    }
 
    public function registerPluginScrips() {
 
        if ( false === $this->is_litigation_application ) {
 
            return false;
        }
 
        wp_register_style( 'select2_style', plugins_url( '', __FILE__ ) . '/../dist/css/select2.min.css' );
        wp_enqueue_style( 'select2_style' );
 
        wp_register_script( 'select2_js', plugins_url( '', __FILE__ ) . '/../dist/js/select2.min.js', array( 'jquery' ) );
        wp_enqueue_script( 'select2_js' );
 
        wp_register_script( 'jquery_steps', plugins_url( '', __FILE__ ) . '/../dist/js/jquery.steps.min.js', array( 'jquery' ) );
        wp_enqueue_script( 'jquery_steps' );
 
        wp_register_script( 'jquery_validate', plugins_url( '', __FILE__ ) . '/../dist/js/jquery.validate.min.js', array( 'jquery' ) );
        wp_enqueue_script( 'jquery_validate' );
 
        wp_register_script( 'jquery_validate_additional', plugins_url( '', __FILE__ ) . '/../dist/js/additional-methods.min.js', array( 'jquery_validate' ) );
        wp_enqueue_script( 'jquery_validate_additional' );
 
        wp_register_script( 'intl_input', plugins_url( '', __FILE__ ) . '/../dist/js/intlTelInput-jquery.min.js', array( 'jquery' ) );
        wp_enqueue_script( 'intl_input' );
 
        wp_register_style( 'intl_input_style', plugins_url( '', __FILE__ ) . '/../dist/css/intlTelInput.min.css' );
        wp_enqueue_style( 'intl_input_style' );
 
        wp_register_style( 'wbl_litigation_style', plugins_url( '', __FILE__ ) . '/../dist/css/style.css' );
        wp_enqueue_style( 'wbl_litigation_style' );
 
    }
 
    /**
     * Litigation Application Master
     *
     * @param array $atts shortcode parameters.
     *
     * @return html.
     */
    public function viewLitigationApplicationMaster( $atts ) {
 
        $html = '';
 
        if( isset( $_REQUEST['liqpay_action'] ) && isset( $_REQUEST['order_id'] ) && ! empty( $_REQUEST['order_id'] ) ) {
 
            $claim_id = absint( $_REQUEST['order_id'] );
            $status = self::getPaymentsStatus( $claim_id , $action = 'status' );
 
            if ( in_array( $status['status'], [ 'wait_accept', 'success', 'sandbox' ], true ) ) {
 
                // View document
                ob_start();
 
                $url = get_post_meta( $claim_id, 'download_link', true );
 
                if ( in_array( $status['status'], [ 'success', 'sandbox' ], true ) ) {
 
                    $this->sendMail( $claim_id, $url );
                }
 
                ?>
                    <p style="margin-bottom: 2em;">
                        Дякуємо! Вашу позовну заяву успішно створено.<br/>
                        Завантажте готовий документ за посиланням нижче.<br/>
                        Також скористайтеся детальними інструкціями щодо порядку подання заяви до суду.<br/>
                        Копія цього повідомлення надіслана на вашу електронну пошту (якщо не бачите листа, перевірте папку "Спам")
                    </p>
                    <div class="download_links">
                        <a href="<?php echo plugins_url( 'templates/instructions.docx', dirname(__FILE__) ) ?>" class="wbl-litigation-manual"><?php esc_html_e( 'Download manual', 'wbl-litigation' );?></a>
                        <a href="<?php echo esc_url( $url ); ?>" class="wbl-litigation-document"><?php esc_html_e( 'Download claim', 'wbl-litigation' );?></a>
                    </div>
                <?
 
                $html = ob_get_contents();
 
                ob_end_clean();
            }
 
            return $html;
        }
 
        // Merge atts
        $atts = array_merge(
            [
                'form_id'   => '',
            ],
            $atts
        );
 
        $forms = $this->getForms();
 
        if ( ! isset( $forms[ $atts['form_id'] ] ) ) {
 
            return;
        }
        ob_start();
 
        $form = new $atts['form_id']();
        $form->showForm();
        ?>
 
        <style media="screen">
            li.select2-results__option:empty {
                display: none;
            }
        </style>
 
 
        <?php
 
        $html = ob_get_contents();
 
        ob_end_clean();
 
        return $html;
    }
 
    public function sendMail( $claim_id ) {
 
        $to             = get_post_meta( $claim_id, 'email', true );
        $subject        = esc_html__( 'Ваше замовлення #', 'wbl-litigation' ) . $claim_id . ' ' . esc_html__( 'створено', 'wbl-litigation' ).' ✅';
        $download_link  = get_post_meta( $claim_id, 'download_link', true );
 
        ob_start();
 
        ?>
            <html>
                <body>
                <p style="margin-bottom: 2em;">
                    Дякуємо! Вашу позовну заяву успішно створено.<br/>
                    Завнтажте готовий документ за посиланням нижче.<br/>
                    Також скористайтеся детальними інструкціями щодо порядку подання заяви до суду.
                </p>
                <div class="download_links">
                    <a href="<?php echo plugins_url( 'templates/instructions.docx', dirname( __FILE__ ) ) ?>" class="wbl-litigation-manual"><?php esc_html_e( 'Download manual', 'wbl-litigation' );?></a>
                    </br>
                    <a href="<?php echo esc_url( $download_link ); ?>" class="wbl-litigation-document"><?php esc_html_e( 'Download claim', 'wbl-litigation' );?></a>
                </div>
                </body>
            </html>
        <?php
 
        $body = ob_get_contents();
 
        ob_end_clean();
 
        // Send mail
        $headers =  "From: Сайт <info@site.com>\r\n";
        $headers .= "Reply-To: [email]info@site.com[/email]\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
 
        wp_mail( $to, $subject, $body, $headers );
    }
 
    public function getForms() {
 
        return $this->forms = apply_filters( 'LitigationApplicationForms', $this->forms );
    }
 
    public function checkLitigationApplication() {
 
        global $post;
 
        if ( has_shortcode( $post->post_content, $this->shortcode ) ) {
 
            $this->is_litigation_application = true;
        }
    }
 
    /**
     * Sanitize array
     *
     * @param field $data in data.
     * @return int the integer
     */
    public static function sanitizeArray( $data ) {
 
        $out_data = array();
 
        if ( is_array( $data ) ) {
 
            foreach ( $data as $key => $value ) {
 
                if ( ! is_array( $value ) && ! is_object( $value ) ) {
 
                    $out_data[ $key ] = sanitize_text_field( $value );
                }
 
                if ( is_array( $value ) ) {
 
                    $out_data[ $key ] = self::sanitizeArray( $value );
                }
            }
        } else {
 
            $out_data = sanitize_text_field( $data );
        }
 
        return $out_data;
    }
}
 
new LitigationApplication();
Именно через него крашится сайт. Выбивет синтакс ошибку типа: syntax error, unexpected 'public' (T_PUBLIC).
Я просмотрел код несколько раз на закрытые скобки. Потом позабирал все паблики у функций и тогда мы приходим к ошибке syntax error, unexpected end of file, что тоже очень похоже на не закрытую скобку.

Если закоментить, не дать подключить конструктору shortcode.php, сайт работает но не видит шорктода для выполнения.

Подскажите, дайте совет, буду рад любой помощи. Взгляните на код может быть я чего то не увидел. Но по синтаксису - проблем быть не должно. В блокнотах все скобки закрыты.
Миниатюры
Интересный syntax error, unexpected 'public' (T_PUBLIC)   Интересный syntax error, unexpected 'public' (T_PUBLIC)  
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
19.03.2020, 09:53
Ответы с готовыми решениями:

Parse error: syntax error, unexpected 'public' (T_PUBLIC), expecting end of file in W:\domains\localhost\form4.php on li
&lt;?php public static function getMacAlgoBlockSize($algorithm = 'sha1') { ...

Ошибка - Parse error: syntax error, unexpected T_VARIABLE как исправить?
$table = 'tp-20' $result = mysql_query('SELECT * FROM `$table` '); синтаксический ошибка как...

Исправить ошибку Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';'
Ошибка:Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' in...

Parse error: syntax error, unexpected T_STRING in W:\home\.php on line 82
&lt;?php class index { private function indexjs() { ?&gt; &lt;script type=&quot;text/javascript&quot;...

3
162 / 150 / 97
Регистрация: 24.12.2013
Сообщений: 744
Записей в блоге: 12
19.03.2020, 14:49 2
WATTman, а это весь скрипта shortcode.php ? как то написано через одно место ну не суть) у тебя в конце нет закрывающего ?>
0
2 / 2 / 1
Регистрация: 18.11.2012
Сообщений: 94
19.03.2020, 14:57  [ТС] 3
brain-4-me, все скрипты данного плагина не имеют закрытой
PHP
1
?>
, поэтому погоды это не делает
0
2 / 2 / 1
Регистрация: 18.11.2012
Сообщений: 94
20.03.2020, 23:48  [ТС] 4
Корень ошибки нашел. Дело было в html-коде. Перенес его полностью в php.
0
20.03.2020, 23:48
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
20.03.2020, 23:48
Помогаю со студенческими работами здесь

Parse error: syntax error, unexpected T_STRING in index.php on line 15
Помогите пожалуйста! Вот такая ошибка: Вот HTML: &lt;html&gt; &lt;meta http-equiv=&quot;Content-Language&quot;...

В чем ошибка (Parse error: syntax error, unexpected '$i' (T_VARIABLE), expecting ';') ?
private function select($table_name,$fields,$where=&quot;&quot;,$order=&quot;&quot;,$up=true,$limit=&quot;&quot;) {...

Parse error: syntax error, unexpected T_SL in /homell.php on line 48
$_POST = &lt;&lt;&lt; HTML &lt;a href=&quot;{$config }uploads/posts/{$poster_data}{$poster_name}&quot; onclick=&quot;return...

Ошибка как исправить PHP Parse error: syntax error, unexpected '['
Всем привет. Ребята помогите решить проблему. сайт пишет вот такую ошибку PHP Parse error:...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru