Syntax error unexpected token public

Ошибка Parse error: syntax error, unexpected ‘public’ (T_PUBLIC), expecting end of file in D:localhtdocsaddlibsDatabase.php on line 31? host . ‘;dbname=’ . $this->dbname; // Set options $options = array( PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); // Create a new PDO instanace try dbh = new PDO($dsn, $this->user, $this->pass, $options); > // Catch any errors […]

Содержание

  1. Ошибка Parse error: syntax error, unexpected ‘public’ (T_PUBLIC), expecting end of file in D:localhtdocsaddlibsDatabase.php on line 31?
  2. Syntax error unexpected token public
  3. Uncaught SyntaxError: Unexpected token — что это означает?
  4. Что делать с ошибкой Uncaught SyntaxError: Unexpected token
  5. Ошибка: Syntax error: unexpected token 17 февраля 2016 · HTML & CSS, JavaScript и Блог · 2 мин чтения
  6. Чаще всего
  7. Простой пример
  8. Возможное решение (первое)
  9. Возможное решение (второе)
  10. Так же ошибка возникает бывает…
  11. Личный опыт
  12. Послесловие
  13. Uncaught SyntaxError: Unexpected token
  14. How do I fix it?

Ошибка Parse error: syntax error, unexpected ‘public’ (T_PUBLIC), expecting end of file in D:localhtdocsaddlibsDatabase.php on line 31?

host . ‘;dbname=’ . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try <
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
>
// Catch any errors
catch(PDOException $e) <
$this->error = $e->getMessage();
>
>
>

public function query($query) <
$this->stmt = $this->dbh->prepare($query);
>

public function bind($param, $value, $type = null) <
if (is_null($type)) <
switch (true) <
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
>
>
$this->stmt->bindValue($param, $value, $type);
>

public function execute() <
return $this->stmt->execute();
>
public function resultset() <
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
>
public function single() <
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
>
public function rowCount() <
return $this->stmt->rowCount();
>

public function beginTransaction() <
return $this->dbh->beginTransaction();
>

public function endTransaction() <
return $this->dbh->commit();
>

public function cancelTransaction() <
return $this->dbh->rollBack();
>
public function debugDumpParams() <
return $this->stmt->debugDumpParams();
>

Источник

Syntax error unexpected token public

paginate(5);n return view(‘home’, compact(‘posts’));n >nnn public function create()n <nn $tags=Tag::all();n $categories=Category::all();n return view(‘posts.create’,compact(‘tags’,’categories’));n >nnn public function store(Request $request)n <n n $this->validate($request, array(n ‘title’=>’required|max:255’,n ‘slug’=>’required|min:3|max:255|unique:posts’,n ‘body’=>’required’n ));nn $post=new Post;n $post->title=$request->title;n $post->slug=$request->slug;n $post->body=$request->body;n $post->save();n $post->tags()->sync($request->tags, false);n $post->categories()->sync($request->categories, false);n return redirect()->route(‘posts.show’, $post->id);n >nn public function show($id)n <nn $post=Post::find($id);n return view(‘posts.show’, compact(‘post’));n >nnn public function edit($id)n <nn $tags=Tag::all();n $categories=Category::all();n $post=Post::find($id);n return view(‘posts.edit’, compact(‘post’, ‘tags’,’categories’));n >nnn public function update(Request $request, $id)n <nn $post=Post::find($id);n $this->validate($request, array(n ‘title’=>’required|max:255’,n ‘slug’=>»required|min:3|max:255|unique:posts,slug, $id»,n ‘body’=>’required’n ));n $post->title=$request->title;n $post->slug=$request->slug;n $post->body=$request->body;n $post->save();n if(isset($request->tags)|| isset($request->categories))<n if(isset($request->tags))<n $post->tags()->sync($request->tags);>n if(isset($request->categories))<n $post->categories()->sync($request->categories);n >nn else<n $post->tags()->sync(array());n $post->categories()->sync(array());n >n return redirect()->route(‘posts.show’, $post->id);n >nn public function destroy($id)n <n $post=Post::find($id);n $post->tags()->detach();n $post->categories()->detach();n Post::destroy($id);n return redirect(‘/’);n >n>n n

in PostController.php line 93n n

In this series, you’ll learn how to drastically improve the performance of your Laravel applications by pushing more work to the database, all while still using the Eloquent ORM.

Источник

Uncaught SyntaxError: Unexpected token — что это означает?

Самая популярная ошибка у новичков.

Когда встречается. Допустим, вы пишете цикл for на JavaScript и вспоминаете, что там нужна переменная цикла, условие и шаг цикла:

for var i = 1; i // какой-то код
>

После запуска в браузере цикл падает с ошибкой:

❌ Uncaught SyntaxError: Unexpected token ‘var’

Что значит. Unexpected token означает, что интерпретатор вашего языка встретил в коде что-то неожиданное. В нашем случае это интерпретатор JavaScript, который не ожидал увидеть в этом месте слово var, поэтому остановил работу.

Причина — скорее всего, вы пропустили что-то из синтаксиса: скобку, кавычку, точку с запятой, запятую, что-то подобное. Может быть, у вас была опечатка в служебном слове и язык его не распознал.

Что делать с ошибкой Uncaught SyntaxError: Unexpected token

Когда интерпретатор не может обработать скрипт и выдаёт ошибку, он обязательно показывает номер строки, где эта ошибка произошла (в нашем случае — в первой же строке):

Если мы нажмём на надпись VM21412:1, то браузер нам сразу покажет строку с ошибкой и подчеркнёт непонятное для себя место:

По этому фрагменту сразу видно, что браузеру не нравится слово var. Что делать теперь:

    Проверьте, так ли пишется эта конструкция на вашем языке. В случае JavaScript тут не хватает скобок. Должно быть for (var i=1; i ВКонтактеTelegramТвиттер

Источник

Ошибка: Syntax error: unexpected token 17 февраля 2016 · HTML & CSS, JavaScript и Блог · 2 мин чтения

В этой записи я хочу рассказать про данную ошибку и из-за чего она может проявляться.

Чаще всего

Давайте представим обычный AJAX запрос. В целом, я думаю, что всем понятно что это из-за себя представляет. Вы указываете путь к файлу обработчика данный и пишите в каком формате вы хотите получить данные обратно. Для более точного разъяснения проблемы, я написал небольшой пример AJAX запроса, который указан ниже.

Простой пример

В примере ниже, я использую POST запрос, к файлу по пути ajax/ajax-form.php . Ответ я ожидаю в формате JSON. Я отправляю данные в виде, , при удачном получении данных, сработает success , а при ошибке error . При success или error ответ будет показан в консоли браузера.

Сама частая причина возникновения ошибки Syntax error: unexpected token — это когда вы делаете AJAX запрос к обработчику (например — ajax/ajax-form.php из примера выше), а его нет по указанному пути ( ajax/имя-файла.php ) и в итоге возвращается 404 ошибка (не найдено).

404 ошибка, вернет вам (HTML формат), а скриптом ожидается JSON dataType: ‘json’ и поэтому возникает такая ошибка.

Возможное решение (первое)

Проверьте правильно ли прописан путь и/или имя файла обработчика.

Возможное решение (второе)

Возможно вы не правильно возвращаете ответ со стороны обработчика, например вы прописали JSON, а возвращается в HTML или наоборот.

Так же ошибка возникает бывает…

Если вы 100% уверены в том, что ошибка не происходит из-за того, что вы неправильно прописали путь для обработчика — то второй причиной возникновения ошибки может быть синтаксическая ошибка.

Например если вы пропустили «;» или вместо type: «POST» указали type «POST» . Постарайтесь внимательно пройтись по коду и если ошибок все равно нет, то оставьте его на некоторое время и чуть позже вернитесь к нему.

Личный опыт

Я сам очень часто при первоначальном взгляде на код не вижу в нем никаких ошибок — он мне кажется идеальным. Через некоторое время когда я возвращаюсь к нему, чтобы снова просмотреть все на свежую голову.

И да, после вторичного просмотра кода я вношу массу поправок и исправляю ошибки (если они были).

Послесловие

На этом все. Если у вас есть какой-либо вопрос по данной теме, то пожалуйста напишите его ниже под этой записью.

Источник

Uncaught SyntaxError: Unexpected token

This is a common error in JavaScript, and it is hard to understand at first why it happens. But if you bear with me and remember that Bugs are a good thing you will be on your way in no time.

The JavaScript file you are linking to is returning 404 page. In other words, the browser is expecting JavaScript but it is returning HTML results.

Here is a simple example that may cause this error.

In the example above, when the user clicks on a link an ajax request is triggered to return json data. If the json data is returned correctly, everyone is happy and move on. But if it doesn’t, well we have to fix it. In situations like this, it’s often common to see the error:

Uncaught SyntaxError: Unexpected token or HTML. If you check the response on your network developer tab, you will see that the response is HTML.

Another way you can get this error is if you add a script tag and have the src return HTML:

All it means is that the interpreter is expecting JavaScript or JSON and you are feeding it HTML/XML. If you don’t think you are returning HTML, check if you are not getting a 404.

How do I fix it?

Check the src path to your JavaScript to make sure it is correct. If you are making an Ajax request also check the path. Either the path is incorrect, or the file doesn’t exist.

Did you like this article? You can subscribe to read more awesome ones. RSS

Источник

<?php
class Database{
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;

private $dbh;
private $error;
private $stmt;

public function __construct(){
// Set DSN
$dsn = ‘mysql:host=’ . $this->host . ‘;dbname=’ . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
}
}
}

public function query($query){
$this->stmt = $this->dbh->prepare($query);
}

public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}

public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function rowCount(){
return $this->stmt->rowCount();
}

public function beginTransaction(){
return $this->dbh->beginTransaction();
}

public function endTransaction(){
return $this->dbh->commit();
}

public function cancelTransaction(){
return $this->dbh->rollBack();
}
public function debugDumpParams(){
return $this->stmt->debugDumpParams();
}

?>

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>rn";
        $headers .= "Reply-To: [email]info@site.com[/email]rn";
        $headers .= "MIME-Version: 1.0rn";
        $headers .= "Content-Type: text/html; charset=UTF-8rn";
 
        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();

За последние 24 часа нас посетили 11584 программиста и 1164 робота. Сейчас ищут 309 программистов …


  1. VaneS

    VaneS
    Активный пользователь

    С нами с:
    16 ноя 2011
    Сообщения:
    631
    Симпатии:
    3
    Адрес:
    Россия

    Здравствуйте, при создании сайта использовал hostcms, на локальном сервере все хорошо работало, но как только выгрузил его на хостинг появилась вот такая ошибка:

    1. Parse error: syntax error, unexpected T_PUBLIC in /var/www/u0063337/public_html/domen.ru/modules/tag/model.php on line 53

    Вот полностью исходник того скрипта:

    1.  * @copyright © 2005-2014 ООО «Хостмэйк» (Hostmake LLC), http://www.hostcms.ru
    2. class Tag_Model extends Core_Entity
    3.     public $_site_count = NULL;
    4.     public $_all_count = NULL;
    5.      * One-to-many or many-to-many relations
    6.     protected $_hasMany = array(
    7.         ‘informationsystem_item’ => array(‘through’ => ‘tag_informationsystem_item’),
    8.         ‘shop_item’ => array(‘through’ => ‘tag_shop_item’),
    9.         ‘tag_informationsystem_item’ => array(),
    10.         ‘tag_shop_item’ => array()
    11.     protected $_belongsTo = array(
    12.      * @param int $id entity ID
    13.     public function __construct($id = NULL)
    14.         parent::__construct($id);
    15.             $oUserCurrent = Core_Entity::factory(‘User’, 0)->getCurrent();
    16.             $this->_preloadValues[‘user_id’] = is_null($oUserCurrent) ? 0 : $oUserCurrent->id;
    17.         //$this->_calculateCounts();
    18.      * Utilized for reading data from inaccessible properties
    19.      * @param string $property property name
    20.     public function __get($property)
    21.             $this->_calculateCounts();
    22.         return parent::__get($property);
    23.      * Triggered by calling isset() or empty() on inaccessible properties
    24.      * @param string $property property name
    25.     public function __isset($property)
    26.         return parent::__isset($property);
    27.     protected function _calculateCounts()
    28.             $queryBuilder = Core_QueryBuilder::select(
    29.                 array(‘COUNT(*)’, ‘count’))
    30.                 ->leftJoin(‘tag_shop_items’, ‘tags.id’, ‘=’, ‘tag_shop_items.tag_id’/*,
    31.                         array(‘AND’ => array(‘tag_shop_items.tag_id’, ‘=’, $this->id))
    32.                 ->leftJoin(‘tag_informationsystem_items’, ‘tags.id’, ‘=’, ‘tag_informationsystem_items.tag_id’/*,
    33.                         array(‘AND’ => array(‘tag_informationsystem_items.tag_id’, ‘=’, $this->id))
    34.                 ->where(‘tag_informationsystem_items.tag_id’, ‘=’, $this->id)
    35.                 ->where(‘tag_shop_items.tag_id’, ‘=’, $this->id)
    36.                 //->where(‘tags.id’, ‘=’, $this->id)
    37.                 ->where(‘tags.deleted’, ‘=’, 0);
    38.             $row = $queryBuilder->execute()->asAssoc()->current();
    39.             $this->_all_count = $row[‘count’];
    40.                 ->where(‘tag_informationsystem_items.site_id’, ‘=’, CURRENT_SITE)
    41.                 ->where(‘tag_shop_items.site_id’, ‘=’, CURRENT_SITE)
    42.             $row = $queryBuilder->execute()->asAssoc()->current();
    43.             $this->_site_count = $row[‘count’];
    44.     protected function _setPath()
    45.                 $this->path = $this->name;
    46.      * Check if there another tag with this name is
    47.     protected function _checkDuplicate()
    48.         $oTagDublicate = Core_Entity::factory(‘Tag’)->getByName($this->name);
    49.         // Дубликат по имени найден
    50.         if (!is_null($oTagDublicate) && $oTagDublicate->id != $this->id)
    51.             $this->id = $oTagDublicate->id;
    52.         // Дубликат по имени не найден
    53.             // Проверяем наличие дубликата по пути
    54.             $oTagDublicate = Core_Entity::factory(‘Tag’)->getByPath($this->path);
    55.             // Дубликат по пути найден
    56.             if (!is_null($oTagDublicate) && $oTagDublicate->id != $this->id)
    57.                 $this->id = $oTagDublicate->id;
    58.      * Check if there another tag with this name is
    59.         !$this->deleted && $this->_setPath()
    60.      * Save object. Use self::update() or self::create()
    61.         !$this->deleted && $this->_setPath()
    62.      * @param Tag_Model $oObject
    63.     public function merge(Tag_Model $oObject)
    64.         $aTag_Informationsystem_Item = $oObject->Tag_Informationsystem_Items->findAll(FALSE);
    65.         foreach ($aTag_Informationsystem_Item as $oTag_Informationsystem_Item)
    66.             $oTmp = $this->Tag_Informationsystem_Items->getByInformationsystem_item_id($oTag_Informationsystem_Item->informationsystem_item_id, FALSE);
    67.                 ? $this->add($oTag_Informationsystem_Item)
    68.                 : $oTag_Informationsystem_Item->delete();
    69.         $aTag_Shop_Item = $oObject->Tag_Shop_Items->findAll(FALSE);
    70.         foreach ($aTag_Shop_Item as $oTag_Shop_Item)
    71.             $oTmp = $this->Tag_Shop_Items->getByShop_item_id($oTag_Shop_Item->shop_item_id, FALSE);
    72.                 ? $this->add($oTag_Shop_Item)
    73.                 : $oTag_Shop_Item->delete();
    74.      * Move tag to another dir
    75.      * @param int $tag_dir_id dir id
    76.     public function move($tag_dir_id)
    77.         $this->tag_dir_id = $tag_dir_id;
    78.      * Delete object from database
    79.      * @param mixed $primaryKey primary key for deleting object
    80.     public function delete($primaryKey = NULL)
    81.             $primaryKey = $this->getPrimaryKey();
    82.         $this->Tag_Informationsystem_Items->deleteAll(FALSE);
    83.         $this->Tag_Shop_Items->deleteAll(FALSE);
    84.         return parent::delete($primaryKey);
    85.      * Get XML for entity and children entities
    86.      * @hostcms-event tag.onBeforeRedeclaredGetXml
    87.         Core_Event::notify($this->_modelName . ‘.onBeforeRedeclaredGetXml’, $this);
    88.             $this->addXmlTag(‘count’, $this->count);
    89.      * Convert object to string
    90.     public function __toString()

    В чем может быть проблема!?


  2. Ganzal

    Команда форума
    Модератор

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    /**
    * Belongs to relations
    * @var array
    */
    protected $_belongsTo = array(
    ‘tag_dir’ => array()
    );

    я красным выделил 53 строку. как ты можешь заметить твой листинг бесполезен. не хочешь чтоб тебе помогали — не обращайся. хочешь — не модифицируй код или будь внимателен при копипасте.


  3. VaneS

    VaneS
    Активный пользователь

    С нами с:
    16 ноя 2011
    Сообщения:
    631
    Симпатии:
    3
    Адрес:
    Россия

    Это не копипаст, я же говорю, я установил на локальный сервер себе hostcms, она там номально работала, при переносе на хостинг стала выдавать вот такую ошибку

    Добавлено спустя 3 минуты 45 секунд:
    Версия php на хостинге


  4. Ganzal

    Команда форума
    Модератор

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    помоги мне

    Parse error: syntax error, unexpected T_PUBLIC in /var/www/u0063337/public_html/domen.ru/modules/tag/model.php on line 53
    Ошибка разбора: ошибка синтаксиса, неожиданный ТОКЕН_ОБЛАСТИ_ВИДИМОСТИ_ПУБЛИЧНОЙ в /путь/к/файлу/модэл.пхп в линии 53

    линия 53 отмечена красным в прошлом сообщении.
    лично я в ней вижу ТОКЕН_КОММЕНТАРИЙ
    а следующая за ней 54 (простая математика пятьдесят три плюс один) строка начинается с protected $_belo то есть с ТОКЕН_ОБЛАСТИ_ВИДИМОСТИ_ЗАЩИЩЕННОЙ. аааааааах, не то, не то, не то… жжджжж

    помоги мне в твоем листинге увидеть правильную 53 строку. где будет заветное паблик.
    помоги моему анализатору синтаксиса увидеть ошибку синтаксиса в данном файле и не дай ему завершить разбор данного листинга неожиданным успехом.


  5. VaneS

    VaneS
    Активный пользователь

    С нами с:
    16 ноя 2011
    Сообщения:
    631
    Симпатии:
    3
    Адрес:
    Россия

    Ганзал, я не сомневаюсь в твоих знаниях, но не все такие умные как ты… Ты можешь нормально ответить, без эронии?
    А почему на локальном сервере все нормально работало?


  6. mkramer

    Команда форума
    Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.493
    Симпатии:
    1.732

    VaneS, Ganzal вам втолковать пытается, что вы либо файл неверно привели, либо сообщение об ошибке


  7. Ganzal

    Команда форума
    Модератор

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    чувак, выключи иронию и включи мозги — приведенный листинг не соответствует приведенной ошибке. проверь внимательно что ты правильный файл публикуешь. проверь внимательно что ты не проёбываешь кусок текста при копипасте. хватит иронию искать в моих сообщениях. научись уже в них видеть неприкрытый смысл.


  8. VaneS

    VaneS
    Активный пользователь

    С нами с:
    16 ноя 2011
    Сообщения:
    631
    Симпатии:
    3
    Адрес:
    Россия

    Конечно правильный, выходит вот такая ошибка:

    1. Parse error: syntax error, unexpected T_PUBLIC in /var/www/u0063337/public_html/domen.ru/modules/tag/model.php on line 53

    Я перехожу по указанному адресу, а там этот файл, содержимое которого я выслал выше…


  9. Ganzal

    Команда форума
    Модератор

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    ну ты сам-то понимаешь что такого быть не может? скачай с хостинга файл.


  10. VaneS

    VaneS
    Активный пользователь

    С нами с:
    16 ноя 2011
    Сообщения:
    631
    Симпатии:
    3
    Адрес:
    Россия

    Он был таким же…
    В общем не знаю как я это сделал, но в общем сжал сайт в архив, закачал через веб интерфейс и распакавал прямо там, о чудо заработало….
    Не знаю что с ним было…


  11. Ganzal

    Команда форума
    Модератор

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    а до этого заливал по фтп?


  12. VaneS

    VaneS
    Активный пользователь

    С нами с:
    16 ноя 2011
    Сообщения:
    631
    Симпатии:
    3
    Адрес:
    Россия

    Да! Но ошибок не было никаких вообще, все файлы успешно перекопировались


  13. Ganzal

    Команда форума
    Модератор

    С нами с:
    15 мар 2007
    Сообщения:
    9.901
    Симпатии:
    968

    на всякий случай — включи бинарный режим обмена. есть предположение что в текстовом убились переводы строк и исходник сварился в кашу которую анализатор не смог переварить.

Various parts of the PHP language are represented internally by tokens.
A code snippet that contains an invalid sequence of tokens may lead to errors like
Parse error: syntax error, unexpected token "==", expecting "(" in script.php on line 10."
where token == is internally represented by T_IS_EQUAL.

The following table lists all tokens. They are also available as PHP constants.

Note:
Usage of T_* constants

T_* constants values are automatically generated based on PHP’s underlying parser infrastructure.
This means that the concrete value of a token may change between two PHP
versions.
This means that your code should never rely directly
on the original T_* values taken from PHP version X.Y.Z, to provide some compatibility
across multiple PHP versions.

To make use of T_* constants across multiple PHP versions, undefined constants
may be defined by the user (using big numbers like 10000) with an
appropriate strategy that will work with both PHP versions and T_* values.


<?php
// Prior to PHP 7.4.0, T_FN is not defined.
defined('T_FN') || define('T_FN', 10001);

Tokens

Token Syntax Reference
T_ABSTRACT abstract Class Abstraction
T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG & Type declarations (available as of PHP 8.1.0)
T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG & Type declarations (available as of PHP 8.1.0)
T_AND_EQUAL &= assignment
operators
T_ARRAY array() array(), array syntax
T_ARRAY_CAST (array) type-casting
T_AS as foreach
T_ATTRIBUTE #[ attributes (available as of PHP 8.0.0)
T_BAD_CHARACTER   anything below ASCII 32 except t (0x09), n (0x0a) and r (0x0d)
(available as of PHP 7.4.0)
T_BOOLEAN_AND && logical operators
T_BOOLEAN_OR || logical operators
T_BOOL_CAST (bool) or (boolean) type-casting
T_BREAK break break
T_CALLABLE callable callable
T_CASE case switch
T_CATCH catch Exceptions
T_CLASS class classes and objects
T_CLASS_C __CLASS__ magic constants
T_CLONE clone classes and objects
T_CLOSE_TAG ?> or %> escaping
from HTML
T_COALESCE ?? comparison operators
T_COALESCE_EQUAL ??= assignment operators
(available as of PHP 7.4.0)
T_COMMENT // or #, and /* */ comments
T_CONCAT_EQUAL .= assignment
operators
T_CONST const class constants
T_CONSTANT_ENCAPSED_STRING «foo» or ‘bar’ string syntax
T_CONTINUE continue continue
T_CURLY_OPEN {$ complex
variable parsed syntax
T_DEC incrementing/decrementing
operators
T_DECLARE declare declare
T_DEFAULT default switch
T_DIR __DIR__ magic constants
T_DIV_EQUAL /= assignment
operators
T_DNUMBER 0.12, etc. floating point numbers
T_DO do do..while
T_DOC_COMMENT /** */ PHPDoc style comments
T_DOLLAR_OPEN_CURLY_BRACES ${ complex
variable parsed syntax
T_DOUBLE_ARROW => array syntax
T_DOUBLE_CAST (real), (double) or (float) type-casting
T_DOUBLE_COLON :: see T_PAAMAYIM_NEKUDOTAYIM below
T_ECHO echo echo
T_ELLIPSIS function arguments
T_ELSE else else
T_ELSEIF elseif elseif
T_EMPTY empty empty()
T_ENCAPSED_AND_WHITESPACE » $a» constant part of
string with variables
T_ENDDECLARE enddeclare declare, alternative syntax
T_ENDFOR endfor for, alternative syntax
T_ENDFOREACH endforeach foreach, alternative syntax
T_ENDIF endif if, alternative syntax
T_ENDSWITCH endswitch switch, alternative syntax
T_ENDWHILE endwhile while, alternative syntax
T_ENUM enum Enumerations (available as of PHP 8.1.0)
T_END_HEREDOC   heredoc
syntax
T_EVAL eval() eval()
T_EXIT exit or die exit(), die()
T_EXTENDS extends extends, classes and objects
T_FILE __FILE__ magic constants
T_FINAL final Final Keyword
T_FINALLY finally Exceptions
T_FN fn arrow functions
(available as of PHP 7.4.0)
T_FOR for for
T_FOREACH foreach foreach
T_FUNCTION function functions
T_FUNC_C __FUNCTION__ magic constants
T_GLOBAL global variable scope
T_GOTO goto goto
T_HALT_COMPILER __halt_compiler() __halt_compiler
T_IF if if
T_IMPLEMENTS implements Object Interfaces
T_INC ++ incrementing/decrementing
operators
T_INCLUDE include() include
T_INCLUDE_ONCE include_once() include_once
T_INLINE_HTML   text outside PHP
T_INSTANCEOF instanceof type operators
T_INSTEADOF insteadof Traits
T_INTERFACE interface Object Interfaces
T_INT_CAST (int) or (integer) type-casting
T_ISSET isset() isset()
T_IS_EQUAL == comparison operators
T_IS_GREATER_OR_EQUAL >= comparison operators
T_IS_IDENTICAL === comparison operators
T_IS_NOT_EQUAL != or <> comparison operators
T_IS_NOT_IDENTICAL !== comparison operators
T_IS_SMALLER_OR_EQUAL <= comparison operators
T_LINE __LINE__ magic constants
T_LIST list() list()
T_LNUMBER 123, 012, 0x1ac, etc. integers
T_LOGICAL_AND and logical operators
T_LOGICAL_OR or logical operators
T_LOGICAL_XOR xor logical operators
T_MATCH match match (available as of PHP 8.0.0)
T_METHOD_C __METHOD__ magic constants
T_MINUS_EQUAL -= assignment
operators
T_MOD_EQUAL %= assignment
operators
T_MUL_EQUAL *= assignment
operators
T_NAMESPACE namespace namespaces
T_NAME_FULLY_QUALIFIED AppNamespace namespaces (available as of PHP 8.0.0)
T_NAME_QUALIFIED AppNamespace namespaces (available as of PHP 8.0.0)
T_NAME_RELATIVE namespaceNamespace namespaces (available as of PHP 8.0.0)
T_NEW new classes and objects
T_NS_C __NAMESPACE__ namespaces
T_NS_SEPARATOR namespaces
T_NUM_STRING «$a[0]» numeric array index
inside string
T_OBJECT_CAST (object) type-casting
T_OBJECT_OPERATOR -> classes and objects
T_NULLSAFE_OBJECT_OPERATOR ?-> classes and objects
T_OPEN_TAG <?php, <? or <% escaping
from HTML
T_OPEN_TAG_WITH_ECHO <?= or <%= escaping
from HTML
T_OR_EQUAL |= assignment
operators
T_PAAMAYIM_NEKUDOTAYIM :: ::. Also defined as
T_DOUBLE_COLON.
T_PLUS_EQUAL += assignment
operators
T_POW ** arithmetic operators
T_POW_EQUAL **= assignment operators
T_PRINT print() print
T_PRIVATE private classes and objects
T_PROTECTED protected classes and objects
T_PUBLIC public classes and objects
T_READONLY readonly classes and objects (available as of PHP 8.1.0)
T_REQUIRE require() require
T_REQUIRE_ONCE require_once() require_once
T_RETURN return returning values
T_SL << bitwise
operators
T_SL_EQUAL <<= assignment
operators
T_SPACESHIP <=> comparison operators
T_SR >> bitwise
operators
T_SR_EQUAL >>= assignment
operators
T_START_HEREDOC <<< heredoc
syntax
T_STATIC static variable scope
T_STRING parent, self, etc. identifiers, e.g. keywords like parent and self,
function names, class names and more are matched.
See also T_CONSTANT_ENCAPSED_STRING.
T_STRING_CAST (string) type-casting
T_STRING_VARNAME «${a complex
variable parsed syntax
T_SWITCH switch switch
T_THROW throw Exceptions
T_TRAIT trait Traits
T_TRAIT_C __TRAIT__ __TRAIT__
T_TRY try Exceptions
T_UNSET unset() unset()
T_UNSET_CAST (unset) type-casting
T_USE use namespaces
T_VAR var classes and objects
T_VARIABLE $foo variables
T_WHILE while while, do..while
T_WHITESPACE t rn  
T_XOR_EQUAL ^= assignment
operators
T_YIELD yield generators
T_YIELD_FROM yield from generators

See also token_name().

nathan at unfinitydesign dot com

14 years ago


T_ENCAPSED_AND_WHITESPACE is whitespace which intersects a group of tokens. For example, an "unexpected T_ENCAPSED_AND_WHITESPACE" error is produced by the following code:

<?php

$main_output_world
= 'snakes!';

echo(
'There are' 10 $main_output_world);

?>



Note the missing concatenation operator between the two strings leads to the whitespace error that is so named above. The concatenation operator instructs PHP to ignore the whitespace between the two code tokens (the so named "encapsed" data"), rather than parse it as a token itself.

The correct code would be:

<?php

$main_output_world
= 'snakes!';

echo(
'There are' . 10 . $main_output_world);

?>



Note the addition of the concatenation operator between each token.


fgm at osinet dot fr

14 years ago


T_ENCAPSED_AND_WHITESPACED is returned when parsing strings with evaluated content, like "some $value" or this example from the Strings reference page:

<?php
echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some
{$foo->bar[1]}.
This should print a capital 'A': x41
EOT;
?>

This last example is tokenized as:
T_ECHO
  echo
T_WHITESPACE
  %20 (a space character)
T_START_HEREDOC
  <<
T_ENCAPSED_AND_WHITESPACE
  My name is "
T_VARIABLE
  $name
T_ENCAPSED_AND_WHITESPACE   
  ". I am printing some
T_VARIABLE   
  $foo
T_OBJECT_OPERATOR   
  ->
T_STRING   
  foo
T_ENCAPSED_AND_WHITESPACE   
  . Now, I am printing some
T_CURLY_OPEN   
  {
T_VARIABLE   
  $foo
T_OBJECT_OPERATOR   
  ->
T_STRING   
  bar
(terminal)
  [
T_LNUMBER   
  1
(terminal)
  ]
(terminal)
  }
T_ENCAPSED_AND_WHITESPACE   
  . This should print a capital 'A': x41
T_END_HEREDOC
  EOT
(terminal)
  ;


Hi all,
I am in the middle of changing my opencart shop (1.5.5.1) from one host to another.
All files transferred & database uploaded to new server, but I get this error.

Parse error: syntax error, unexpected T_PUBLIC in /home/xxx/public_html/vqmod/vqcache/vq2-catalog_controller_common_seo_url.php on line 158

I guess there is an extra } somewhere in the code of vq2-catalog_controller_common_seo_url.php, but I cannot work out where .

Any help gratefully received !

Here is the code from that page

Code: Select all

<?php

class ControllerCommonSeoUrl extends Controller {

	public function index() {

		// Add rewrite to url class

		if ($this->config->get('config_seo_url')) {

			$this->url->addRewrite($this);

		}

		

		// Decode URL

		if (isset($this->request->get['_route_'])) {

			$parts = explode('/', $this->request->get['_route_']);

                        $this_route = $parts;
                        $this_route_multistore = $parts;
                        array_shift($this_route_multistore);
                        

			

			foreach ($parts as $part) {

				$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE keyword = '" . $this->db->escape($part) . "'");

				

				if ($query->num_rows) {

					$url = explode('=', $query->row['query']);

					

					if ($url[0] == 'product_id') {

						$this->request->get['product_id'] = $url[1];

					}

					

					if ($url[0] == 'category_id') {

						if (!isset($this->request->get['path'])) {

							$this->request->get['path'] = $url[1];

						} else {

							$this->request->get['path'] .= '_' . $url[1];

						}

					}	

					

					if ($url[0] == 'manufacturer_id') {

						$this->request->get['manufacturer_id'] = $url[1];

					}

					

					if ($url[0] == 'information_id') {

						$this->request->get['information_id'] = $url[1];

					}	

				} else {

					
                        if (is_file(DIR_APPLICATION . 'controller/' . implode("/", $this_route) . '.php'))  {
                        $this->request->get['route'] = implode("/", $this_route);
                        break;
                        } elseif (is_file(DIR_APPLICATION . 'controller/' . implode("/", $this_route_multistore) . '.php'))  {
                        $this->request->get['route'] = implode("/", $this_route_multistore);
                        break;
                        } else {
                        $this->request->get['route'] = 'error/not_found';
                        array_pop($this_route);
                        array_pop($this_route_multistore);
                        }
                        	

				}

			}

			

			
                        if (preg_match("/information//", $this->request->get['_route_'])) {
				$this->request->get['route'] = $this->request->get['_route_'];
			} elseif (isset($this->request->get['information_id'])) {
				$this->request->get['route'] = 'information/information';
			} elseif (preg_match("/checkout//", $this->request->get['_route_'])) {
				$this->request->get['route'] = $this->request->get['_route_'];
			} elseif (preg_match("/payment//", $this->request->get['_route_'])) {
				$this->request->get['route'] = $this->request->get['_route_'];
			} elseif (preg_match("/feed//", $this->request->get['_route_'])) {
				$this->request->get['route'] = $this->request->get['_route_'];
			} elseif (preg_match("/affiliate//", $this->request->get['_route_'])) {
				$this->request->get['route'] = $this->request->get['_route_'];
			} elseif (preg_match("/account//", $this->request->get['_route_'])) {
				$this->request->get['route'] = $this->request->get['_route_'];
			} elseif (preg_match("/total//", $this->request->get['_route_'])) {
				$this->request->get['route'] = $this->request->get['_route_'];
			} elseif (isset($this->request->get['product_id'])) {
				$this->request->get['route'] = 'product/product';
			} elseif (isset($this->request->get['path'])) {
				$this->request->get['route'] = 'product/category';
			} elseif (isset($this->request->get['manufacturer_id'])) {
				$this->request->get['route'] = 'product/manufacturer/product';
			}
			









				$this->request->get['route'] = 'product/manufacturer/info';

			} elseif (isset($this->request->get['information_id'])) {

				$this->request->get['route'] = 'information/information';

			}

			

			if (isset($this->request->get['route'])) {

				return $this->forward($this->request->get['route']);

			}

		}

	}

	

	public function rewrite($link) {

		$url_info = parse_url(str_replace('&', '&', $link));

	

		$url = ''; 

		

		$data = array();

		

		parse_str($url_info['query'], $data);

		

		foreach ($data as $key => $value) {

			if (isset($data['route'])) {

				if (($data['route'] == 'product/product' && $key == 'product_id') || (($data['route'] == 'product/manufacturer/info' || $data['route'] == 'product/product') && $key == 'manufacturer_id') || ($data['route'] == 'information/information' && $key == 'information_id')) {

					$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'");

				

					if ($query->num_rows) {

						$url .= '/' . $query->row['keyword'];

						

						unset($data[$key]);

					}					

				} elseif ($key == 'path') {

					$categories = explode('_', $value);

					

					foreach ($categories as $category) {

						$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = 'category_id=" . (int)$category . "'");

				

						if ($query->num_rows) {

							$url .= '/' . $query->row['keyword'];

						}							

					}

					

					unset($data[$key]);

				}

			}

		}

	

		if ($url) {

			unset($data['route']);

		

			$query = '';

		

			if ($data) {

				foreach ($data as $key => $value) {

					$query .= '&' . $key . '=' . $value;

				}

				

				if ($query) {

					$query = '?' . trim($query, '&');

				}

			}



			return $url_info['scheme'] . '://' . $url_info['host'] . (isset($url_info['port']) ? ':' . $url_info['port'] : '') . str_replace('/index.php', '', $url_info['path']) . $url . $query;

		} else {

			
                        return preg_replace("/(index.php?route=|common/home)/", "", $link);
                        

		}

	}	

}

?>

Понравилась статья? Поделить с друзьями:
  • Sysprep error 0x80073cf2
  • Sysprep error 0x0f0070
  • Syslinux edd load error boot error
  • Sysfader iexplore exe ошибка приложения как исправить
  • Sysclk error orange 5