app/Plugin/Blogs42/Controller/Admin/Blogs/BlogsController.php line 58

Open in your IDE?
  1. <?php
  2. namespace Plugin\Blogs42\Controller\Admin\Blogs;
  3. use Eccube\Controller\AbstractController;
  4. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  5. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  10. use Symfony\Component\Filesystem\Filesystem;
  11. use Symfony\Component\HttpFoundation\File\File;
  12. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  13. use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
  14. use Symfony\Component\Asset\Packages;
  15. use Plugin\Blogs42\Entity\Blogs;
  16. use Plugin\Blogs42\Entity\BlogsCategory;
  17. use Plugin\Blogs42\Repository\BlogsRepository;
  18. use Plugin\Blogs42\Repository\CategoryRepository;
  19. use Plugin\Blogs42\Form\Type\Admin\BlogsType;
  20. class BlogsController extends AbstractController
  21. {
  22.     /**
  23.      * @var BlogsRepository
  24.      */
  25.     protected $BlogsRepository;
  26.     /**
  27.      * @var CategoryRepository
  28.      */
  29.     protected $categoryRepository;
  30.     /**
  31.     * @var Packages
  32.     */
  33.     protected $packages;
  34.     /**
  35.      * PageController constructor.
  36.      *
  37.      * @param BlogsRepository $BlogsRepository
  38.      * @param CategoryRepository $categoryRepository
  39.      */
  40.     public function __construct(
  41.         BlogsRepository $BlogsRepository,
  42.         CategoryRepository $categoryRepository,
  43.         Packages $packages
  44.     ) {
  45.         $this->BlogsRepository $BlogsRepository;
  46.         $this->categoryRepository $categoryRepository;
  47.         $this->packages $packages;
  48.     }
  49.     /**
  50.      * @Route("/%eccube_admin_route%/plugin/blogs_list", name="blogs_list")
  51.      * @Template("@Blogs42/admin/Blogs/blogs_list.twig")
  52.      */
  53.     public function index(Request $request)
  54.     {
  55.         log_info('ブログ一覧表示');
  56.         $blogs $this->BlogsRepository->findBy([],['id' => 'desc']);
  57.         return [
  58.             'pagination' => $blogs,
  59.             'total_item_count' => count($blogs),
  60.         ];
  61.     }
  62.     /**
  63.      * @Route("/%eccube_admin_route%/plugin/blogs_new", name="blogs_new")
  64.      * @Route("/%eccube_admin_route%/plugin/blogs/{id}/edit", name="blogs_edit",requirements={"id" = "\d+"}, methods={"GET", "POST"})
  65.      * @Template("@Blogs42/admin/Blogs/blogs_edit.twig")
  66.      */
  67.     public function edit(Request $request$id=null)
  68.     {
  69.         if(is_null($id)){
  70.             log_info('ブログ記事登録開始');
  71.             $blogs = new Blogs();
  72.             $blogs
  73.                 ->setVisible(false);
  74.         } else {
  75.             log_info('ブログ記事編集開始[ID:'$id .']');
  76.             $blogs $this->BlogsRepository->find($id);
  77.         }
  78.         $builder $this->formFactory->createBuilder(BlogsType::class, $blogs);
  79.         $form $builder->getForm();
  80.         $categories = [];
  81.         $BlogsCategories $blogs->getBlogsCategories();
  82.         foreach ($BlogsCategories as $BlogsCategory) {
  83.             /* @var $BlogsCategory \Plugin\Blogs42\Entity\BlogsCategory */
  84.             $categories[] = $BlogsCategory->getCategory();
  85.         }
  86.         $form['Category']->setData($categories);
  87.         if ('POST' === $request->getMethod()) {
  88.             $form->handleRequest($request);
  89.             if ($form->isValid()) {
  90.                 $blogs $form->getData();
  91.                 // カテゴリの登録
  92.                 // 一度クリア
  93.                 /* @var $blogs \Plugin\Blogs42\Entity\Blogs */
  94.                 foreach ($blogs->getBlogsCategories() as $BlogsCategory) {
  95.                     $blogs->removeBlogsCategory($BlogsCategory);
  96.                     $this->entityManager->remove($BlogsCategory);
  97.                 }
  98.                 $this->entityManager->persist($blogs);
  99.                 $this->entityManager->flush();
  100.                 $count 1;
  101.                 $Categories $form->get('Category')->getData();
  102.                 $categoriesIdList = [];
  103.                 foreach ($Categories as $Category) {
  104.                     foreach ($Category->getPath() as $ParentCategory) {
  105.                         if (!isset($categoriesIdList[$ParentCategory->getId()])) {
  106.                             $BlogsCategory $this->createBlogsCategory($blogs$ParentCategory$count);
  107.                             $this->entityManager->persist($BlogsCategory);
  108.                             $count++;
  109.                             /* @var $blogs \Plugin\Blogs42\Entity\Blogs */
  110.                             $blogs->addBlogsCategory($BlogsCategory);
  111.                             $categoriesIdList[$ParentCategory->getId()] = true;
  112.                         }
  113.                     }
  114.                     if (!isset($categoriesIdList[$Category->getId()])) {
  115.                         $BlogsCategory $this->createBlogsCategory($blogs$Category$count);
  116.                         $this->entityManager->persist($BlogsCategory);
  117.                         $count++;
  118.                         /* @var $blogs \Plugin\Blogs42\Entity\Blogs */
  119.                         $blogs->addBlogsCategory($BlogsCategory);
  120.                         $categoriesIdList[$Category->getId()] = true;
  121.                     }
  122.                 }
  123.                 // 画像の移動
  124.                 if ($blogs->getEyecatchImage()) {
  125.                     $file_path $this->eccubeConfig['eccube_temp_image_dir'] . '/' $blogs->getEyecatchImage();
  126.                     if (file_exists($file_path)) {
  127.                         $file = new File($file_path);
  128.                         $file->move($this->eccubeConfig['eccube_save_image_dir']);
  129.                     }
  130.                 }
  131.                 //エディターツール
  132.                     $blog_description $blogs->getBlogDescription();
  133.                     // temp_imageの画像ファイル名を取得
  134.                     $preg_string '/upload\/temp_image\/(.*?(jpg|jpeg|gif|png))/i';
  135.                     preg_match_all($preg_string$blog_description$match1PREG_PATTERN_ORDER);
  136.                     // save_imageに移動
  137.                     foreach ($match1[1] as $filename) {
  138.                         $file = new Filesystem();
  139.                         if(file_exists($this->eccubeConfig['eccube_temp_image_dir'].'/'.$filename)){
  140.                             $file->copy($this->eccubeConfig['eccube_temp_image_dir'].'/'.$filename,$this->eccubeConfig['eccube_save_image_dir'].'/'.$filename);
  141.                             $file->remove($this->eccubeConfig['eccube_temp_image_dir'].'/'.$filename);
  142.                         }
  143.                     }
  144.                     // 画像のパスを変更
  145.                     $blog_description str_replace("temp_image""save_image"$blog_description);
  146.                     $blogs->setBlogDescription($blog_description);
  147.                 $this->entityManager->persist($blogs);
  148.                 $this->entityManager->flush();
  149.                 log_info('ブログ記事登録/編集完了');
  150.                 $this->addSuccess('admin.common.save_complete''admin');
  151.                 return $this->redirectToRoute('blogs_edit', ['id' => $blogs->getId()]);
  152.             }
  153.         }
  154.         // ツリー表示のため、ルートからのカテゴリを取得
  155.         $TopCategories $this->categoryRepository->getList(null);
  156.         $ChoicedCategoryIds array_map(function ($Category) {
  157.             return $Category->getId();
  158.         }, $form->get('Category')->getData());
  159.         return [
  160.             'blogs' => $blogs,
  161.             'form' => $form->createView(),
  162.             'oldEyecatchImage' => $blogs->getEyecatchImage(),
  163.             'TopCategories' => $TopCategories,
  164.             'ChoicedCategoryIds' => $ChoicedCategoryIds,
  165.         ];
  166.     }
  167.     /**
  168.      *
  169.      * @param Request     $request
  170.      * @param blogs $blogs
  171.      *
  172.      * @throws \Exception
  173.      *
  174.      * @return \Symfony\Component\HttpFoundation\RedirectResponse
  175.      * @Route("/%eccube_admin_route%/plugin/blogs/{id}/delete", name="blogs_delete", requirements={"id" = "\d+"}, methods={"DELETE"})
  176.      */
  177.     public function delete(Request $requestBlogs $blogs)
  178.     {
  179.         log_info('ブログ削除開始[id:'$blogs->getId() .']');
  180.         // Valid token
  181.         $this->isTokenValid();
  182.         // スライダー情報を削除する
  183.         try {
  184.             $this->BlogsRepository->delete($blogs);
  185.             log_info('ブログ記事削除成功', ['id' => $blogs->getId()]);
  186.             $this->addSuccess('admin.common.delete_complete''admin');
  187.         } catch (\Exception $e) {
  188.             log_info('ブログ記事削除失敗', ['id' => $blogs->getId()]);
  189.             $this->addError('admin.common.delete_error_foreign_key''admin');
  190.         }
  191.         return $this->redirectToRoute('blogs_list');
  192.     }
  193.     /**
  194.      * @Route("/%eccube_admin_route%/blogs/image/add", name="eyecatch_image_add")
  195.      */
  196.     public function imageAdd(Request $request)
  197.     {
  198.         if (!$request->isXmlHttpRequest()) {
  199.             throw new BadRequestHttpException();
  200.         }
  201.         log_info('ブログ記事画像登録開始');
  202.         $allowExtensions = ['gif''jpg''jpeg''png''webp'];
  203.         $filename null;
  204.         $files $request->files->all();
  205.         foreach ($files as $images) {
  206.             if (isset($images['eyecatch_file'])) {
  207.                 $image $images['eyecatch_file'];
  208.                 //ファイルフォーマット検証
  209.                 $mimeType $image->getMimeType();
  210.                 if (!== strpos($mimeType'image')) {
  211.                     throw new UnsupportedMediaTypeHttpException();
  212.                 }
  213.                 // 拡張子
  214.                 $extension $image->getClientOriginalExtension();
  215.                 if (!in_array(strtolower($extension), $allowExtensions)) {
  216.                     throw new UnsupportedMediaTypeHttpException();
  217.                 }
  218.                 $filename date('mdHis') . uniqid('_') . '.' $extension;
  219.                 $image->move($this->getParameter('eccube_temp_image_dir'), $filename);
  220.             }
  221.         }
  222.         log_info('ブログ記事画像登録完了');
  223.         return $this->json(['filename' => $filename], 200);
  224.     }
  225.     /**
  226.      * BlogsCategory作成
  227.      *
  228.      * @param \Plugin\Blogs42\Entity\Blogs $blogs
  229.      * @param \Plugin\Blogs42\Entity\Category $Category
  230.      * @param integer $count
  231.      *
  232.      * @return \Plugin\Blogs42\Entity\BlogsCategory
  233.      */
  234.     private function createBlogsCategory($blogs$Category$count)
  235.     {
  236.         $BlogsCategory = new BlogsCategory();
  237.         $BlogsCategory->setBlogs($blogs);
  238.         $BlogsCategory->setBlogsId($blogs->getId());
  239.         $BlogsCategory->setCategory($Category);
  240.         $BlogsCategory->setCategoryId($Category->getId());
  241.         return $BlogsCategory;
  242.     }
  243.     /**
  244.      * @Route("/%eccube_admin_route%/plugin/wysiwyg/image/add", name="wysiwyg_image_add")
  245.      */
  246.     public function editorImageAdd(Request $request)
  247.     {
  248.         if (!$request->isXmlHttpRequest()) {
  249.             throw new BadRequestHttpException();
  250.         }
  251.         log_info('エディター内画像登録開始');
  252.         $falseCount=0;
  253.         $allowExtensions = ['gif''jpg''jpeg''png''webp''GIF''JPG''JPEG''PNG''WEBP'];
  254.         $filename null;
  255.         $files $request->files->all();
  256.         $authorization $request->headers->get('authorization');
  257.         $csrf $request->headers->get('eccube-csrf-token');
  258.         $alt $request->request->get('alt');
  259.         $width $request->request->get('width');
  260.         $imgList = [];
  261.         $imgData = [];
  262.         if($authorization == $csrf){
  263.             foreach ($files as $key => $image) {
  264.                 $originalName $image->getClientOriginalName();
  265.                 //ファイルフォーマット検証
  266.                 $mimeType $image->getMimeType();
  267.                 if (!== strpos($mimeType'image')) {
  268.                         throw new UnsupportedMediaTypeHttpException();
  269.                 }
  270.                 // 拡張子
  271.                 $extension $image->getClientOriginalExtension();
  272.                 if (!in_array(strtolower($extension), $allowExtensions)) {
  273.                         throw new UnsupportedMediaTypeHttpException();
  274.                 }
  275.                 $filename date('mdHis') . uniqid('_') . '.' $extension;
  276.                 $fileUrl '';
  277.                 $result '';
  278.                 if ($key == 'imageFile') {
  279.                     try {
  280.                         $image->move($this->getParameter('eccube_temp_image_dir'), $filename);
  281.                         $fileUrl $this->packages->getUrl($filename'temp_image');
  282.                         $result 'success';
  283.                     } catch (FileException $e) {
  284.                         $falseCount++;
  285.                         $result 'fail';
  286.                     }
  287.                     $imgData array_push($imgList,["result" => $result"oldName"=>$originalName,"filePath"=>$fileUrl]);
  288.                 }else{
  289.                     $falseCount++;
  290.                     $result 'fail';
  291.                     $imgData array_push($imgList,["result" => $result"oldName"=>$originalName,"filePath"=>$fileUrl]);
  292.                 }
  293.             }
  294.             log_info('画像登録完了');
  295.         }
  296.         log_info('エディター内画像登録終了');
  297.         if($falseCount 0) {
  298.             return $this->json(['fail_image' => $falseCount'data' => $imgList],400);
  299.         }
  300.         return $this->json(['success' => true'data' => $imgList],);
  301.     }
  302. }