Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
componentbase.php
1<?php
2
3namespace Bitrix\Translate;
4
10
11
12abstract class ComponentBase
13 extends \CBitrixComponent
14 implements Translate\IErrorable
15{
18
19 const STATUS_SUCCESS = 'success';
20 const STATUS_DENIED = 'denied';
21 const STATUS_ERROR = 'error';
22
23 const TEMPLATE_ERROR = 'error';
24
26 protected $path = '';
27
29 protected $tabId = 0;
30
31
35 protected function checkModuleAvailability()
36 {
37 if (!Main\Loader::includeModule('translate'))
38 {
39 if ($this->isAjaxRequest())
40 {
41 $this->sendJsonResponse(new Error('Module "translate" is not installed.', self::STATUS_ERROR));
42 }
43 else
44 {
45 $this->addError(new Error('Module "translate" is not installed.', self::STATUS_ERROR));
46 $this->includeComponentTemplate(self::TEMPLATE_ERROR);
47 }
48
49 return false;
50 }
51
52 return true;
53 }
54
60 protected function hasUserPermissionView($user)
61 {
62 return Translate\Permission::canView($user);
63 }
64
70 protected function hasUserPermissionEdit($user)
71 {
72 return Translate\Permission::canEdit($user);
73 }
79 protected function hasUserPermissionEditSource($user)
80 {
81 return Translate\Permission::canEditSource($user);
82 }
83
88 protected function checkPermissionView()
89 {
90 if (!$this->hasUserPermissionView($this->getUser()))
91 {
92 if ($this->isAjaxRequest())
93 {
94 $this->sendJsonResponse(new Error(Loc::getMessage('TRANSLATE_FILTER_ERROR_ACCESS_DENIED'), self::STATUS_DENIED));
95 }
96 else
97 {
98 $this->addError(new Error(Loc::getMessage('TRANSLATE_FILTER_ERROR_ACCESS_DENIED'), self::STATUS_DENIED));
99 $this->includeComponentTemplate(self::TEMPLATE_ERROR);
100 }
101
102 return false;
103 }
104
105 return true;
106 }
107
112 protected function checkPermissionEdit()
113 {
114 if (!$this->hasUserPermissionEdit($this->getUser()))
115 {
116 if ($this->isAjaxRequest())
117 {
118 $this->sendJsonResponse(new Error(Loc::getMessage('TRANSLATE_FILTER_ERROR_WRITING_RIGHTS'), self::STATUS_DENIED));
119 }
120 else
121 {
122 $this->addError(new Error(Loc::getMessage('TRANSLATE_FILTER_ERROR_WRITING_RIGHTS'), self::STATUS_DENIED));
123 $this->includeComponentTemplate(self::TEMPLATE_ERROR);
124 }
125
126 return false;
127 }
128
129 return true;
130 }
131
136 protected function checkPermissionEditPhp()
137 {
138 if (!$this->hasUserPermissionEditSource($this->getUser()))
139 {
140 if ($this->isAjaxRequest())
141 {
142 $this->sendJsonResponse(new Error(Loc::getMessage('TRANSLATE_FILTER_ERROR_PHP_EDIT_RIGHTS'), self::STATUS_DENIED));
143 }
144 else
145 {
146 $this->addError(new Error(Loc::getMessage('TRANSLATE_FILTER_ERROR_PHP_EDIT_RIGHTS'), self::STATUS_DENIED));
147 $this->includeComponentTemplate(self::TEMPLATE_ERROR);
148 }
149
150 return false;
151 }
152
153 return true;
154 }
155
160 protected function checkModuleStepper(): void
161 {
162 $stepper = \Bitrix\Main\Update\Stepper::getHtml('translate', Loc::getMessage('TRANSLATE_INDEX_STEPPER'));
163 if (!empty($stepper))
164 {
165 $this->arResult['STEPPER'] = $stepper;
166 }
167 }
168
173 protected function checkFtsTables(): void
174 {
175 Translate\Index\Internals\PhraseFts::checkTables();
176 }
177
182 protected function checkMysqlConfig(): void
183 {
184 $majorVersion = (int)\mb_substr(\Bitrix\Main\Application::getConnection()->getVersion()[0], 0, 1);
185
186 if ($majorVersion >= 8)
187 {
188 $conf = Main\Application::getConnection()->query("SHOW VARIABLES LIKE 'regexp_time_limit'")->fetch();
189 if ($conf['Variable_name'] == 'regexp_time_limit')
190 {
191 if ((int)$conf['Value'] <= 0)
192 {
193 $this->addWarning(new Error(Loc::getMessage('TRANSLATE_MYSQL_CONFIG_ERROR_REGEXP_TIME_LIMIT'), self::STATUS_ERROR));
194 }
195 }
196 }
197 }
198
202 protected function prepareParams()
203 {
204 $params =& $this->getParams();
205 if (empty($params['CURRENT_LANG']))
206 {
207 $params['CURRENT_LANG'] = Loc::getCurrentLang();
208 }
209 if (empty($params['LIST_PATH']))
210 {
211 $params['LIST_PATH'] = '/bitrix/admin/translate_list.php';
212 }
213 if (empty($params['EDIT_PATH']))
214 {
215 $params['EDIT_PATH'] = '/bitrix/admin/translate_edit.php';
216 }
217 if (empty($params['SHOW_SOURCE_PATH']))
218 {
219 $params['SHOW_SOURCE_PATH'] = '/bitrix/admin/translate_show_php.php';
220 }
221 if (empty($params['EDIT_SOURCE_PATH']))
222 {
223 $params['EDIT_SOURCE_PATH'] = '/bitrix/admin/translate_edit_php.php';
224 }
225
226 $params['SET_TITLE'] = isset($params['SET_TITLE']) ? $params['SET_TITLE'] === 'Y' : true;
227
228 $this->arResult['IS_AJAX_REQUEST'] = $this->isAjaxRequest();
229
230 $this->arResult['ALLOW_VIEW'] = $this->hasUserPermissionView($this->getUser());
231 $this->arResult['ALLOW_EDIT'] = $this->hasUserPermissionEdit($this->getUser());
232 $this->arResult['ALLOW_EDIT_SOURCE'] = $this->hasUserPermissionEditSource($this->getUser());
233 }
234
243 protected function rearrangeLanguages($languageList, $currentLangId)
244 {
245 $inx = \array_search($currentLangId, $languageList, true);
246 if ($inx !== false)
247 {
248 unset($languageList[$inx]);
249 }
250
251 \array_unshift($languageList, $currentLangId);
252
253 return $languageList;
254 }
255
259 protected function getLanguages()
260 {
261 static $languagesList;
262
263 if (empty($languagesList))
264 {
265 $languagesList = Translate\Config::getEnabledLanguages();
266 }
267
268 return $languagesList;
269 }
270
278 protected function getLanguagesTitle($languageIds)
279 {
280 $titles = Translate\Config::getLanguagesTitle($languageIds);
281 array_walk($titles, function(&$title, $langId) { $title = "{$title} ({$langId})"; });
282
283 return $titles;
284 }
285
291 protected function getCompatibleLanguages()
292 {
293 static $languages = array();
294 if (empty($languages))
295 {
296 $currentEncoding = Localization\Translation::getCurrentEncoding();
297 $currentLang = Loc::getCurrentLang();
298 $limitEncoding = !($currentEncoding == 'utf-8' || Localization\Translation::useTranslationRepository());
299
300 $isEncodingCompatible = function ($langId) use ($limitEncoding, $currentEncoding, $currentLang)
301 {
302 $compatible = true;
303 if ($limitEncoding)
304 {
305 $compatible = (
306 $langId == $currentLang ||
307 Translate\Config::getCultureEncoding($langId) == $currentEncoding ||
308 $langId == 'en'
309 );
310 }
311
312 return $compatible;
313 };
314
315 $enabledLanguages = $this->getLanguages();
316 foreach ($enabledLanguages as $langId)
317 {
318 if ($limitEncoding && !$isEncodingCompatible($langId))
319 {
320 continue;
321 }
322 $languages[] = $langId;
323 }
324 }
325
326 return $languages;
327 }
328
332 protected function detectTabId()
333 {
334 $tabId = $this->request->get('tabId');
335 if (!empty($tabId) && (int)$tabId > 0)
336 {
337 $this->tabId = (int)$tabId;
338 }
339 elseif ($this->isAjaxRequest())
340 {
341 $this->tabId = Translate\Filter::getTabId(false);
342 }
343 else
344 {
345 $this->tabId = Translate\Filter::getTabId();
346 }
347
348 return $this->tabId;
349 }
350
354 protected function detectStartingPath(?string $path = ''): string
355 {
356 $home = Translate\Config::getDefaultPath();
357
358 $initPaths = Translate\Config::getInitPath();
359 if (count($initPaths) > 0)
360 {
361 $home = $initPaths[0];
362 if (!empty($path))
363 {
364 foreach ($initPaths as $initPath)
365 {
366 if (\mb_strpos($path, $initPath) === 0)
367 {
368 $home = $initPath;
369 break;
370 }
371 }
372 }
373 }
374
375 return $home;
376 }
377
378
383 public function &getParams()
384 {
385 return $this->arParams;
386 }
387
392 public function &getResult()
393 {
394 return $this->arResult;
395 }
396
397
401 protected function getUser()
402 {
404 global $USER;
405 return $USER;
406 }
407
411 protected function getApplication()
412 {
414 global $APPLICATION;
415 return $APPLICATION;
416 }
417
422 protected function isAjaxRequest()
423 {
424 return
425 ($this->request->isAjaxRequest() || $this->request->get('AJAX_CALL') !== null) &&
426 $this->request->getRequestMethod() == 'POST';
427 }
428
437 protected function sendJsonResponse($response)
438 {
439 $this->getApplication()->restartBuffer();
440
441 $answer = Main\Application::getInstance()->getContext()->getResponse();
442
443 if ($response instanceof Main\Error)
444 {
445 $this->addError($response);
446 $response = array();
447 }
448
449 $response['result'] = true;
450 if ($this->hasErrors())
451 {
452 $answer->setStatus('500 Internal Server Error');
453
454 $response['status'] = self::STATUS_ERROR;
455 $errors = array();
456 foreach ($this->getErrors() as $error)
457 {
459 $errors[] = array(
460 'message' => $error->getMessage(),
461 'code' => $error->getCode(),
462 );
463 }
464 $response['result'] = false;
465 $response['errors'] = $errors;
466 }
467 elseif (!isset($response['status']))
468 {
469 $response['status'] = self::STATUS_SUCCESS;
470 }
471
472 $answer->addHeader('Content-Type', 'application/x-javascript; charset=UTF-8');
473 echo Main\Web\Json::encode($response);
474
475 \CMain::finalActions();
476 }
477
484 protected function clearSavedOptions($category, $nameMask)
485 {
486 $res = \CUserOptions::getList(false,['CATEGORY' => $category, 'USER_ID' => $this->getUser()->getId(), 'NAME_MASK' => $nameMask]);
487 while ($opt = $res->fetch())
488 {
489 \CUserOptions::deleteOption($category, $opt['NAME']);
490 }
491 }
492
500 protected function detectPathBack($path)
501 {
502 static $pathBackCache = array();;
503 if (!isset($pathBackCache[$path]))
504 {
505 $pathBack = \dirname($path);
506 $slash = \explode('/', $pathBack);
507 if (\is_array($slash))
508 {
509 $slashTmp = $slash;
510 $langKey = \array_search('lang', $slash) + 1;
511 unset($slashTmp[$langKey]);
512 if ($langKey == \count($slash) - 1)
513 {
514 unset($slash[$langKey]);
515 $pathBack = \implode('/', $slash);
516 }
517 }
518 $pathBackCache[$path] = $pathBack;
519 }
520
521 return $pathBackCache[$path];
522 }
523
531 protected function generateChainLinks($path)
532 {
533 static $chainCache = [];
534 if (!isset($chainCache[$path]))
535 {
536 $params =& $this->getParams();
537 $chain = array();
538 $slash = \explode('/', \dirname($path));
539 if (\is_array($slash))
540 {
541 $langKey = \array_search('lang', $slash) + 1;
542 $slash[$langKey] = $params['CURRENT_LANG'];
543 if ($langKey == \count($slash) - 1)
544 {
545 unset($slash[$langKey]);
546 }
547 $i = 0;
548 $pathList = array();
549 foreach ($slash as $dir)
550 {
551 $i++;
552 if ($i == 1)
553 {
554 $chain[] = array(
555 'link' => $params['LIST_PATH'].
556 '?lang='.$params['CURRENT_LANG'].
557 '&tabId='.$this->tabId.
558 '&path=/',
559 'title' => '..'
560 );
561 }
562 else
563 {
564 $pathList[] = \htmlspecialcharsbx($dir);
565 $chain[] = array(
566 'link' => $params['LIST_PATH'].
567 '?lang='.$params['CURRENT_LANG'].
568 '&tabId='.$this->tabId.
569 '&path=/'.\implode('/', $pathList).'/',
570 'title' => \htmlspecialcharsbx($dir)
571 );
572 }
573 }
574 }
575 $chainCache[$path] = $chain;
576 }
577
578 return $chainCache[$path];
579 }
580
581 public function getTopIndexedFolders(int $depth = 2): array
582 {
583 static $list;
584 if ($list === null)
585 {
586 $list = [0 => ''];
587 $res = Index\Internals\PathIndexTable::getList([
588 'select' => ['ID', 'PATH'],
589 'filter' => [
590 '=INDEXED' => 'Y',
591 '=IS_DIR' => 'Y',
592 '<=DEPTH_LEVEL' => $depth,
593 ],
594 'order' => [
595 'DEPTH_LEVEL' => 'ASC',
596 'PATH' => 'ASC',
597 ]
598 ]);
599 while ($row = $res->fetch())
600 {
601 $list[$row['ID']] = $row['PATH'];
602 }
603 }
604
605 return $list;
606 }
607}
static getConnection($name="")
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
rearrangeLanguages($languageList, $currentLangId)
detectStartingPath(?string $path='')
clearSavedOptions($category, $nameMask)
addError(Main\Error $error)
addWarning(Main\Error $error)
Definition warning.php:22