src/AdmBundle/Helper/Adm.php line 475

Open in your IDE?
  1. <?php
  2. namespace AdmBundle\Helper;
  3. use Exception;
  4. use Symfony\Component\Filesystem\Filesystem;
  5. use Symfony\Component\Finder\Finder;
  6. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  7. use Symfony\Component\Yaml\Dumper;
  8. use Symfony\Component\Yaml\Exception\ParseException;
  9. use Symfony\Component\Yaml\Yaml;
  10. use WebBundle\Entity\ListEmail;
  11. use WebBundle\Entity\StaticPageEntity;
  12. use WebBundle\Entity\TransEntity;
  13. use WebBundle\Entity\User;
  14. use WebBundle\Helper\App;
  15. use WebBundle\Helper\LocaleHelper;
  16. use WebBundle\Helper\PathHelper;
  17. use WebBundle\Helper\RequestHelper;
  18. use WebBundle\Helper\StrHelper;
  19. /**
  20.  * class: Adm
  21.  * -----------------------------------------------------
  22.  * Created by MihailShirnin on 18.10.2016.
  23.  * @package AdmBundle\Helper
  24.  */
  25. class Adm
  26. {
  27.     /**
  28.      * Типы поиска при фильтрации
  29.      * @param string $type
  30.      * @return mixed
  31.      */
  32.     public static function getCompareTypes($type 'full')
  33.     {
  34.         $arr = [
  35.             'full' => [
  36.                 'like' => '~',
  37.                 'not-like' => '!~',
  38.                 'equals' => '=',
  39.                 'not-equals' => '!=',
  40.                 'more' => '>',
  41.                 'less' => '<',
  42.                 'bool' => '',
  43.             ],
  44.             'int' => [
  45.                 'equals' => '=',
  46.                 'not-equals' => '!=',
  47.                 'more' => '>',
  48.                 'less' => '<',
  49.             ],
  50.             'str' => [
  51.                 'like' => '~',
  52.                 'equals' => '=',
  53.                 'not-equals' => '!=',
  54.             ],
  55.             'bool' => [
  56.                 'true' => '1',
  57.                 'false' => '0',
  58.             ],
  59.         ];
  60.         $arr['locale'] = array_merge(['all' => 'all'], LocaleHelper::getListAll());
  61.         return $arr[$type];
  62.     }
  63.     /**
  64.      * @param          $route
  65.      * @param array $parameters
  66.      * @param bool|int $referenceType
  67.      * @return string
  68.      */
  69.     public static function generateUrl($route$parameters = [], $referenceType UrlGeneratorInterface::ABSOLUTE_PATH)
  70.     {
  71.         $url App::getRouter()->generate($route$parameters$referenceType);
  72.         return urldecode($url);
  73.     }
  74.     /**
  75.      * Получаем список локалей для редактирования. Проверяем сразу по доступности
  76.      * @param object|null $object
  77.      * @param bool $isConsole
  78.      * @return array
  79.      */
  80.     public static function getLocalesAdminPanel($object null$isConsole false)
  81.     {
  82.         $locales = [];
  83.         $list = [];
  84.         $uId App::getCurUser() ? App::getCurUser()->getId() : null;
  85.         foreach (LocaleHelper::getListAll() as $locale) {
  86.             $localeName strtoupper($locale);
  87.             $list[$locale] = $localeName;
  88.         }
  89.         foreach ($list as $locale => $name) {
  90.             $localeUP strtoupper($locale);
  91.             if ($isConsole) {
  92.                 $locales[$locale] = $name;
  93.             } elseif ($locale == 'ru' or $locale == 'en' and static::isGranted('ROLE_ADMIN'$object)) {
  94.                 $locales[$locale] = $name;
  95.             } elseif ($locale != 'ua' and static::isGranted('ROLE_PREVIEW_LC'$object)) {
  96.                 $locales[$locale] = $name;
  97.             } elseif ($locale == 'ru' and static::isGranted('ROLE_BM'$object)) {
  98.                 $locales[$locale] = $name;
  99.             } else {
  100.                 $access false;
  101.                 // доступ на чтение для Оли Горшковой
  102.                 if ($uId == 561560 and $locale == 'sv') {
  103.                     $access true;
  104.                 }
  105.                 if (!$access) {
  106.                     $access = static::isGranted('ROLE_TR_' $localeUP$object);
  107.                 }
  108.                 // доступ на чтение для Круглова Валеры
  109.                 if (!$access and $uId == 523776 and $object instanceof StaticPageEntity) {
  110.                     $access true;
  111.                 }
  112.                 if ($access) {
  113.                     $locales[$locale] = $name;
  114.                 }
  115.             }
  116.         }
  117.         return $locales;
  118.     }
  119.     /**
  120.      * Проверяем на возможность редактирования
  121.      * @param string $locale
  122.      * @param null $object
  123.      * @return bool
  124.      */
  125.     public static function isEditor(string $locale$object null)
  126.     {
  127.         if ($locale == 'usa') {
  128.             $locale 'en';
  129.         }
  130.         $role strtoupper("ROLE_TR_{$locale}");
  131.         try {
  132.             $curUser App::getCurUser();
  133.         } catch (Exception $e) {
  134.             $curUser null;
  135.         }
  136.         // Доценко Жене разврешаем редактировать все.
  137.         try {
  138.             if ($curUser and $curUser->getId() == 442) {
  139.                 return true;
  140.             }
  141.         } catch (Exception $e) {
  142.         }
  143.         try {
  144.             $secAuthChecker App::getContainer()->get('security.authorization_checker');
  145.             if ($secAuthChecker->isGranted('ROLE_SUPER_ADMIN'$object)) {
  146.                 return true;
  147.             }
  148.             if ($secAuthChecker->isGranted('ROLE_REDACTOR'$object)) {
  149.                 return true;
  150.             }
  151.             if ($secAuthChecker->isGranted($role$object)) {
  152.                 return true;
  153.             }
  154.         } catch (Exception $e) {
  155.         }
  156.         // доступ Омурбеку по просьбе Игоря
  157.         if ($object instanceof ListEmail) {
  158.             if ($curUser and $curUser->getId() == 600182) {
  159.                 return true;
  160.             }
  161.         }
  162.         if ($object instanceof ListEmail or $object instanceof TransEntity) {
  163.             if (in_array($locale, ['en''ru'])) {
  164.                 if ($curUser and in_array('ROLE_EDITOR_EMAIL'$curUser->getRoles())) {
  165.                     return true;
  166.                 }
  167.             }
  168.         }
  169.         return false;
  170.     }
  171.     /**
  172.      * Проверка уровня доступа
  173.      * @param      $role
  174.      * @param null $object
  175.      * @return bool
  176.      */
  177.     public static function isGranted($role$object null)
  178.     {
  179.         $role StrHelper::toUpper($role);
  180.         $secAuthChecker App::getContainer()->get('security.authorization_checker');
  181.         if ($secAuthChecker->isGranted('ROLE_SUPER_ADMIN'$object)) {
  182.             return true;
  183.         }
  184.         // проверяем сначала роли уровнем выше для переводчиков
  185.         if (strripos($role'ROLE_TR_') !== false) {
  186.             if ($secAuthChecker->isGranted('ROLE_TR_ALL'$object)) {
  187.                 return true;
  188.             }
  189.         }
  190.         return $secAuthChecker->isGranted($role$object);
  191.     }
  192.     /**
  193.      * @return mixed | User
  194.      */
  195.     public static function getCurUser()
  196.     {
  197.         return App::getCurUser();
  198.     }
  199.     /**
  200.      * Получение сокращенного имени текущего роута из запроса
  201.      * @return array|mixed|null|string
  202.      */
  203.     public static function getCurRouteName()
  204.     {
  205.         $routeName RequestHelper::get('_route');
  206.         $routeName explode('.'$routeName);
  207.         array_pop($routeName);
  208.         $routeName[] = 'index';
  209.         $routeName implode('.'$routeName);
  210.         return $routeName;
  211.     }
  212.     /**
  213.      * @return Filesystem
  214.      */
  215.     public static function getFileSystemNew()
  216.     {
  217.         return new Filesystem();
  218.     }
  219.     /**
  220.      * @return Dumper
  221.      */
  222.     public static function getDumperNew()
  223.     {
  224.         return new Dumper();
  225.     }
  226.     /**
  227.      * @return Finder
  228.      */
  229.     public static function getFinderNew()
  230.     {
  231.         return new Finder();
  232.     }
  233.     /**
  234.      * Parses YAML into a PHP value.
  235.      *  Usage:
  236.      *  <code>
  237.      *   $array = Yaml::parse(file_get_contents('config.yml'));
  238.      *   print_r($array);
  239.      *  </code>
  240.      * @param string $input A string containing YAML
  241.      * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise
  242.      * @param bool $objectSupport True if object support is enabled, false otherwise
  243.      * @param bool $objectForMap True if maps should return a stdClass instead of array()
  244.      * @return mixed The YAML converted to a PHP value
  245.      * @throws ParseException If the YAML is not valid
  246.      */
  247.     public static function getYamlParse($input$exceptionOnInvalidType false$objectSupport false$objectForMap false)
  248.     {
  249.         return Yaml::parse($input$exceptionOnInvalidType$objectSupport$objectForMap);
  250.     }
  251.     /**
  252.      * Формируем ссылку для получения истории изменений
  253.      * @param $entityId
  254.      * @param $entityName
  255.      * @param $fieldDot
  256.      * @return array
  257.      */
  258.     public static function getLinkHistory($entityId$entityName$fieldDot null)
  259.     {
  260.         $fieldDot $fieldDot "&entityField[]=val|{$fieldDot}::fileld|entityField::type|equals" '';
  261.         $arr = [
  262.             'title' => 'История изменений',
  263.             'link' => "/adm/history/list/?entityId[]=val|{$entityId}::fileld|entityId::type|equals{$fieldDot}&entityName[]=val|{$entityName}::fileld|entityName::type|equals",
  264.         ];
  265.         return $arr;
  266.     }
  267.     /**
  268.      * Формируем ссылку для получения оринигала перевода
  269.      * @param $route
  270.      * @param $id
  271.      * @param $fieldDot
  272.      * @param $locale
  273.      * @return array|string
  274.      */
  275.     public static function getLinkTranslater($route$id$fieldDot$localebool $useHtmlEditor false)
  276.     {
  277.         $arr = [];
  278.         if (!$locale or $locale == 'ru') {
  279.             return $arr;
  280.         }
  281.         $fieldDotRu Adm::getFieldDotSourceForTranslater($fieldDot$locale);
  282.         $arr = [
  283.             'title' => 'Перевод с оригиналом',
  284.             'link' => Adm::generateUrl($route, ['getField' => ['id' => $id'field' => $fieldDotRu]]),
  285.         ];
  286.         // включаем html в переводах только для избранных полей
  287.         if (
  288.             $useHtmlEditor or
  289.             StrHelper::isInStr($fieldDot'page.html') or
  290.             StrHelper::isInStr($fieldDot'body.') or
  291.             StrHelper::isInStr($fieldDot'text.') or
  292.             StrHelper::isInStr($fieldDot'answer.') or
  293.             $fieldDot == 'body'
  294.         ) {
  295.             $arr['html'] = true;
  296.         }
  297.         return $arr;
  298.     }
  299.     public static function getLinkTransExList($entityId$entityName$fieldDot$locale)
  300.     {
  301.         $arr = [];
  302.         if (!$locale or $locale == 'ru') {
  303.             return $arr;
  304.         }
  305.         if (!Adm::isGranted('ROLE_REDACTOR')) {
  306.             return $arr;
  307.         }
  308.         if ($entityId == null) {
  309.             return $arr;
  310.         }
  311. //        /** @var TransExRepository $repoTransEx */
  312. //        $repoTransEx = App::getRepository('WebBundle:TransExEntity');
  313. //        $cnt = $repoTransEx->getCount($entityId, $entityName, $fieldDot);
  314.         $arr = [
  315.             'title' => "Переводы выполненные в бюро",
  316.             'link' => "/adm/trans-ex/list/?entityId[]=val|{$entityId}::fileld|entityId::type|equals&entityField[]=val|{$fieldDot}::fileld|entityField::type|equals&entityName[]=val|{$entityName}::fileld|entityName::type|equals",
  317.         ];
  318.         return $arr;
  319.     }
  320.     /**
  321.      * @param $id
  322.      * @param $entityName
  323.      * @param $field
  324.      * @param $locale
  325.      * @param bool $replace
  326.      * @return array
  327.      */
  328.     public static function getLinkTransExAdd($id$entityName$field$locale$replace true)
  329.     {
  330.         $arr = [];
  331.         if (!$locale or $locale == 'source' or $locale == 'ru') {
  332.             return $arr;
  333.         }
  334.         if (!Adm::isGranted('ROLE_REDACTOR')) {
  335.             return $arr;
  336.         }
  337.         if ($id == null) {
  338.             return $arr;
  339.         }
  340.         $pattern $field;
  341.         if ($replace) {
  342.             $langsAll App::getParameter('langs_all');
  343.             $langsAllUc explode('|'$langsAll);
  344.             $langsAllUc array_map(function ($word) {
  345.                 return ucwords($word);
  346.             }, $langsAllUc);
  347.             $langsAllUc implode('|'$langsAllUc);
  348.             if (preg_match("/(.*\.)({$langsAll})$/"$field)) {
  349.                 $pattern preg_replace("/(.*\.)({$langsAll})$/""$1locale"$field);
  350.             }
  351.             if (preg_match("/(.*)({$langsAllUc})$/"$field)) {
  352.                 $pattern preg_replace("/(.*)({$langsAllUc})/""$1localeUc"$field);
  353.             }
  354.         }
  355.         $arr = [
  356.             'title' => 'Отправить заявку в бюро',
  357.             'link' => Adm::generateUrl('adm.trans_ex.create', ['entityName' => $entityName'entityId' => $id'entityFieldPattern' => $pattern'lcTarget' => $locale]),
  358.         ];
  359.         return $arr;
  360.     }
  361.     /**
  362.      * Формируем имя поля для получения оринигала перевода
  363.      * @param $fieldDot
  364.      * @param $locale
  365.      * @return array|string
  366.      */
  367.     public static function getFieldDotSourceForTranslater($fieldDot$locale)
  368.     {
  369.         $fieldDotRu explode('.'$fieldDot);
  370.         $last array_pop($fieldDotRu);
  371.         if ($last == $locale) {
  372.             $last 'ru';
  373.         } else if ($last == ucfirst($locale)) {
  374.             $last 'Ru';
  375.         } else if (StrHelper::isInStr($lastucfirst($locale))) {
  376.             $last str_replace(ucfirst($locale), 'Ru'$last);
  377.         }
  378.         array_push($fieldDotRu$last);
  379.         $fieldDotRu implode('.'$fieldDotRu);
  380.         return $fieldDotRu;
  381.     }
  382.     /**
  383.      * Проверяем валидность ссылки, на существоание и ответ сервера
  384.      * @param $url
  385.      * @return bool
  386.      */
  387.     public static function checkOpenUrl($url)
  388.     {
  389.         $url_c parse_url($url);
  390.         if (!empty($url_c['host'])) {
  391.             $ip gethostbyname($url_c['host']);
  392.             if ($url_c['host'] != $ip) {
  393.                 return true;
  394.             }
  395.         }
  396. //        App::dumpExit( $url_c['host'], gethostbyname ($url_c['host']), checkdnsrr($url_c['host']) );
  397.         // пока убрал проверку на headers, не корректная
  398. //        if (!empty($url_c['host']) and checkdnsrr($url_c['host'])) {
  399. //            if ($headers=@get_headers($url)){
  400. //                $cod = substr($headers[0], 9, 3);
  401. //                if ($cod == 200) {
  402. //                    return true;
  403. //                }
  404. //            }
  405. //        }
  406.         return false;
  407.     }
  408.     public static function linkEdit($route$id)
  409.     {
  410.         if (!Adm::isGranted('ROLE_ADMIN')) {
  411.             return null;
  412.         }
  413.         $link App::isDev() ? '' 'https://adm.tile.expert';
  414.         switch ($route) {
  415.             case 'bi_collection_show_check':
  416.                 $link .= "/import/collection/show/{$id}";
  417.                 break;
  418.             case 'adm.collection.edit':
  419.                 $link .= "/adm/coll/{$id}/edit/";
  420.                 break;
  421.             case 'adm.static.page.edit':
  422.                 $link .= "/adm/static-page/{$id}/edit/";
  423.                 break;
  424.             case 'adm.brand.edit':
  425.                 $link .= "/adm/brand/{$id}/edit/";
  426.                 break;
  427.             case 'adm.filter.edit':
  428.                 $link .= "/adm/filter/{$id}/edit/";
  429.                 break;
  430.             case 'adm.blog.edit':
  431.                 $link .= "/adm/blog/{$id}/edit/";
  432.                 break;
  433.             case 'bi.factory.edit':
  434.                 $link .= "/import/factory/output/show/{$id}";
  435.                 break;
  436.         }
  437.         return $link;
  438.     }
  439.     /**
  440.      * Генерация рендомной строки
  441.      * @param int $length
  442.      * @return string
  443.      */
  444.     public static function genUnId($length 10)
  445.     {
  446.         $chars '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  447.         $cLength strlen($chars);
  448.         $str '';
  449.         for ($i 0$i $length$i++) {
  450.             $str .= $chars[rand(0$cLength 1)];
  451.         }
  452.         return $str;
  453.     }
  454.     /**
  455.      * Чуть правленный путь для картинок в админке
  456.      * @param string $type
  457.      * @param $attr
  458.      * @return string|null
  459.      */
  460.     public static function pathImageIcon(string $type$attr)
  461.     {
  462.         $src PathHelper::pathGenerate($type$attr);
  463.         if ($src) {
  464.             $src str_replace('img.tile.expert''img-adm.tile.expert'$src);
  465.             $src preg_replace('/\?(.*)/'''$src);
  466.             if (!preg_match('/.svg$/'$src)) {
  467.                 $src "{$src}?r=100x100";
  468.             }
  469.         }
  470.         return $src;
  471.     }
  472. }