Connect Woltlab with Symfony - symfony

Hello I would like to link my forum (forum software: Woltlab) with symfony 6....
I am currently trying to do so like this:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
class DashboardController extends AbstractController
{
#[Route('/', name: 'app_dashboard')]
public function index(): Response
{
require_once('/home/maybemc-main/htdocs/maybemc.net/global.php');
$username = wcf\system\WCF::getUser()->mcName;
$id = wcf\system\WCF::getUser()->userID;
$avatar = wcf\system\WCF::getUserProfileHandler()->getAvatar()->getUrl(35);
if (!wcf\system\WCF::getSession()->getPermission('levi.perms.canSeePanel')){
header('HTTP/1.0 403 Forbidden');
die('Du hast darauf keine Berechtigung!');
}
$client = new Client();
$response = $client->get('http://**.***.***.***:8080/teamchat/messages');
$TCList = json_decode($response->getBody(), true);
return $this->render('dashboard/index.html.twig', [
'username' => $username,
'id' => $id,
'avatar' => $avatar,
'controller_name' => 'DashboardController',
'TCList' => $TCList
]);
}
}
unfortunately I get the error "Class "App\Controller\wcf\system\WCF" not found"
Do any of you have any idea why this is not working?
I also tried to add also the global.php to the service.yaml like this:
App\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'
- '/home/maybemc-main/htdocs/maybemc.net/global.php'

Related

VichUploader : MediaObject is not uploadable

I try to upload file throught a REST API with API Plateform
I followed the doc, but I got :
"The class \"App\\Entity\\MediaObject\" is not uploadable. If you use attributes to configure VichUploaderBundle, you probably just forgot to add `#[Vich\\Uploadable]` on top of your entity. If you don't use attributes, check that the configuration files are in the right place. In both cases, clearing the cache can also solve the issue.",
I'am using :
"api-platform/core": "^3.0",
"vich/uploader-bundle": "^2.0"
My config :
# api/config/packages/vich_uploader.yaml
vich_uploader:
db_driver: orm
metadata:
type: attribute
mappings:
media_object:
uri_prefix: /media
upload_destination: '%kernel.project_dir%/public/media'
namer: Vich\UploaderBundle\Naming\OrignameNamer
My entity :
<?php
// api/src/Entity/MediaObject.php
namespace App\Entity;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Post;
use App\Controller\CreateMediaObjectAction;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
#[Vich\Uploadable]
#[ORM\Entity]
#[ApiResource(
normalizationContext: ['groups' => ['media_object:read']],
types: ['https://schema.org/MediaObject'],
operations: [
new Get(),
new GetCollection(),
new Post(
controller: CreateMediaObjectAction::class,
deserialize: false,
validationContext: ['groups' => ['Default', 'media_object_create']],
openapiContext: [
'requestBody' => [
'content' => [
'multipart/form-data' => [
'schema' => [
'type' => 'object',
'properties' => [
'file' => [
'type' => 'string',
'format' => 'binary'
]
]
]
]
]
]
]
)
]
)]
class MediaObject
{
#[ORM\Id, ORM\Column, ORM\GeneratedValue]
private ?int $id = null;
#[ApiProperty(types: ['https://schema.org/contentUrl'])]
#[Groups(['media_object:read'])]
public ?string $contentUrl = null;
#[Vich\UploadableField(mapping: "media_object", fileNameProperty: "filePath")]
#[Assert\NotNull(groups: ['media_object_create'])]
public ?File $file = null;
#[ORM\Column(nullable: true)]
public ?string $filePath = null;
public function getId(): ?int
{
return $this->id;
}
}
In my case this resolved the problem:
composer require doctrine/annotations

symfony4 use .env config variables in a service

I am using a package that is not especially made for symfony (TNTsearch), and have put all the functions I want to use in a service I called TNTsearchHelper.php. This service requires some variables, including some that could be found in the .env file. I currently define and construct these in my class:
class TntSearchHelper
{
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
$config = [
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'databasename',
'username' => 'user',
'password' => 'pw',
'storage' => 'my/path/to/file',
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
];
$this->config = $config;
}
What I would really like is to simply use the variables for my database that are set in the .env file. Is there any way to do this? This service is not registered in services.yaml because this is not neccesary with the autowire: true option, so I don't have any config options/file for my service in the config and wonder if I can keep it that way.
Yes. It's possible. If you want to use env variables for configuration, you have two options:
1.Use getenv:
$config = [
'driver' => 'mysql',
'host' => getenv('MYSQL_HOST'),
'database' => getenv('MYSQL_DB'),
'username' => getenv('MYSQL_LOGIN'),
'password' => getenv('MYSQL_PASSWORD'),
'storage' => 'my/path/to/file',
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
];
2.Configure your service in services.yaml:
services:
App\TntSearchHelper:
arguments:
- '%env(MYSQL_HOST)%'
- '%env(MYSQL_DB)%'
- '%env(MYSQL_LOGIN)%'
- '%env(MYSQL_PASSWORD)%'
And change your __construct function to this:
public function __construct(string $host, string $db, string $login, string $password, EntityManagerInterface $em)
{
$this->em = $em;
$config = [
'driver' => 'mysql',
'host' => $host,
'database' => $db,
'username' => $login,
'password' => $password,
'storage' => 'my/path/to/file',
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
];
$this->config = $config;
}
Also make sure that all this env variables are set because there's only DATABASE_URL variable in .env file by default
I know three possibilities. Each case has 03 steps configuration : 1 - declare yours variables in env. 2 - config service file 3 - and call your parameter
_ In controllers extending from the AbstractController, and use the getParameter() helper :
YAML file config
# config/services.yaml
parameters:
kernel.project_dir: "%env(variable_name)%"
app.admin_email: "%env(variable_name)%"
In your service,
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class UserController extends AbstractController
{
// ...
public function index(): Response
{
$projectDir = $this->getParameter('kernel.project_dir');
$adminEmail = $this->getParameter('app.admin_email');
// ...
}
}
_ In services and controllers not extending from AbstractController, inject the parameters as arguments of their constructors.
YAML file config
# config/services.yaml
parameters:
app.contents_dir: "%env(variable_name)%"
services:
App\Service\MessageGenerator:
arguments:
$contentsDir: '%app.contents_dir%'
In your service,
class MessageGenerator
{
private $params;
public function __construct(string $contentsDir)
{
$this->params = $contentsDir;
}
public function someMethod()
{
$parameterValue = $this->params;
// ...
}
}
_ Finally, if some service needs access to lots of parameters, instead of injecting each of them individually, you can inject all the application parameters at once by type-hinting any of its constructor arguments with the ContainerBagInterface:
YAML file config
# config/services.yaml
parameters:
app.parameter_name: "%env(variable_name)%"
In your service,
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
class MessageGenerator
{
private $params;
public function __construct(ContainerBagInterface $params)
{
$this->params = $params;
}
public function someMethod()
{
$parameterValue = $this->params->get('app.parameter_name');
// ...
}
}
source Accessing Configuration Parameters

Using Subscribing Handler Interface when Serialize te modify parameters in symfony

I have a REST API and have an Entity Userwith field called Avatar, in DB I save name XXXX.jpg but when I return I want to add a url in this field Avatar, for example www.mylink.com/XXXX.jpg.
I'm trying with a service implements SubscribingHandlerInterfacebut I don't know how I can use it.
I have this method in this service:
class UrlManager implements SubscribingHandlerInterface
{
public static function getSubscribingMethods()
{
return array(
array(
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'json',
'type' => 'AppBundle/Entity/User',
'method' => 'serializeUrlAvatar',
),
);
}
public function serializeUrlAvatar(User $user)
{
$url = 'www.mylink.com';
return array(
"avatar" => $url . $user->getAvatar()
);
}
}
but how can I call this service to modify url when I serialize.
Now I do this:
$_format = 'json';
$json = $this->get('jms_serializer')->serialize($user, $_format);
return new Response($json, 200, ['Content-Type' => 'application/' . $_format]);
In service.yml:
app.url_converter_service:
class: AppBundle\Service\UrlManager
tags:
- { name: jms_serializer.subscribing_handler }
Update
In my controller I call this function like this:
$result = $this->get('app.url_converter_service')->serializeUrlAvatar($user);
$json = $this->get('jms_serializer')->serialize($result, $_format);
return new Response($json, 200, ['Content-Type' => 'application/' . $_format]);
So my question is, exists a way to remove the first line and serialize correctly (add the url) when I serialize?
Have you registered your service like this?
# app/config/services.yml
avatar_url_handler:
class: YourBundle\Serializer\Handler\AvatarUrlHandler
tags:
- { name: jms_serializer.subscribing_handler }
I found a solution. I create a service which implements EventSubscriberInterface like this:
class UserSerializeHandler implements EventSubscriberInterface
{
private $user_uploads;
public function __construct($user_uploads){
$this->user_uploads = $user_uploads;
}
public static function getSubscribedEvents()
{
return array(
array(
'event' => 'serializer.pre_serialize',
'class' => User::class,
'method' => 'onPreSerializeUser'
));
}
public function onPreSerializeUser(PreSerializeEvent $event)
{
/** #var User $user */
$user = $event->getObject();
$avatar = $user->getAvatar();
$user->setAvatar($this->user_uploads . "/" . $avatar);
}
}
In service.yml:
app.serializer_user_service:
class: AppBundle\Service\UserSerializeHandler
arguments: ['%user_uploads%']
tags:
- { name: jms_serializer.event_subscriber }
I have user_uploads in parameters.yml like this:
user_uploads: 'https://myUrl.com'
And in any Controller that I serialize a User, I add the url in the Avatar paramter.
$json = $this->get('jms_serializer')->serialize($user, $_format);
return new Response($json, 200, ['Content-Type' => 'application/' . $_format]);

What HWIOAuthBundle is expecting from the infos_url?

I am trying to config my oauth2 server with HWIOAuthBundle and I would like to have some clarifications on what HWIOAuthBundle is expecting as response to config correctly infos_url?
I guess it is expecting a json file. So, what are its fields?
If you have links, I will be happy.
hwi_oauth:
firewall_name: main
resource_owners:
battlenet:
type: oauth2
client_id: "%client_id%"
client_secret: "%client_secret%"
access_token_url: %path%/oauth/token
authorization_url: %path%/oauth/authorize
infos_url: %path%/user/me
scope: "read"
user_response_class: HWI\Bundle\OAuthBundle\OAuth\Response\PathUserResponse
paths:
identifier: id
nickname: id
realname: id
Thanks ;)
I found how it can be done! You have to create a simple API for the users as follows:
The routing:
# app/routing.yml
api_users:
pattern: /api/users.json
defaults: { _controller: AppOAuthServerBundle:User:getUser }
options:
i18n: false
The controller:
<?php
namespace App\OAuthServerBundle\Controller;
use App\GeneralBundle\Entity\User;
use FOS\RestBundle\Controller\FOSRestController;
class UserController extends FOSRestController
{
public function getUserAction()
{
$user = $this->get('security.context')->getToken()->getUser();
if ( $user instanceof User ) {
$data = array(
'id' => $user->getId(),
'username' => $user->getUsername(),
'realname' => $user->getFirstname().' '.$user->getLastname(),
'email' => $user->getEmail(),
);
} else {
$data = array();
}
$view = $this->view($data, 200)
->setTemplate('AppOAuthServerBundle:Default:index.html.twig')
->setFormat('json')
->setTemplateVar('user');
return $this->handleView($view);
}
}

Custom Handler on JMSSerializerBundle is ignored

I am attempting to use a custom handler for JMS Serializer Bundle
class CustomHandler implements SubscribingHandlerInterface
{
public static function getSubscribingMethods()
{
return array(
array(
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'json',
'type' => 'integer',
'method' => 'serializeIntToJson',
),
);
}
public function serializeIntToJson(JsonSerializationVisitor $visitor, $int, array $type, Context $context)
{
die("GIVE ME SOMETHING");
}
}
This does nothing, and does not die. This is how I am registering the handler
$serializer = SerializerBuilder::create()
->configureHandlers(function(HandlerRegistry $registry) {
$registry->registerSubscribingHandler(new MyHandler());
})
->addDefaultHandlers()
->build();
$json = $serializer->serialize($obj, 'json');
My handler is never called and I cannot manipulate the data on serialisation.
You need to create a service for this handler:
custom_jms_handler:
class: MyBundle\Serializer\CustomHandler
tags:
- { name: jms_serializer.subscribing_handler }
Then make sure you use the registered JMS serializer service
$json = $this->get('jms_serializer')->serialize($obj, 'json');
I have this which works
$serializer = SerializerBuilder::create()
->configureListeners(function(EventDispatcher $dispatcher) {
$dispatcher->addSubscriber(new ProjectSubscriber($this->container));
$dispatcher->addSubscriber(new UserSubscriber($this->container));
})
->addDefaultListeners()
->addMetadataDir(realpath($this->get('kernel')->getRootDir()."/../") . '/src/Jake/NameOfBundle/Resources/config/serializer')
->build();
return $serializer->serialize($project, 'json');
$project is my entity.
You can omit this line if you don't have serializer configs
->addMetadataDir(realpath($this->get('kernel')->getRootDir()."/../") . '/src/Jake/NameOfBundle/Resources/config/serializer')
I think my main issue was this ->addDefaultListeners().
In config.yml I have
jms_serializer:
metadata:
auto_detection: true
directories:
NameOfBundle:
namespace_prefix: ""
path: "#JakeNameOfBundle/Resources/config/serializer"
I don't have anthing set up to make JMS a service.

Resources