some code cleaning

This commit is contained in:
Thomas 2020-05-03 11:13:49 +02:00
parent 0cf71853f3
commit 6817607955
12 changed files with 924 additions and 1002 deletions

View file

@ -20,7 +20,9 @@
"symfony/translation": "4.3.*", "symfony/translation": "4.3.*",
"symfony/twig-bundle": "4.3.*", "symfony/twig-bundle": "4.3.*",
"symfony/yaml": "4.3.*", "symfony/yaml": "4.3.*",
"twig/extensions": "^1.5" "twig/extensions": "^1.5",
"ext-curl": "*",
"ext-json": "*"
}, },
"require-dev": { "require-dev": {
"symfony/web-server-bundle": "4.3.*" "symfony/web-server-bundle": "4.3.*"

View file

@ -1,4 +1,9 @@
<?php <?php /** @noinspection PhpUndefinedClassInspection */
/** @noinspection PhpDocSignatureInspection */
/** @noinspection PhpUnused */
/** @noinspection DuplicatedCode */
/** @noinspection PhpTranslationKeyInspection */
/** /**
* Created by fediplan. * Created by fediplan.
* User: tom79 * User: tom79
@ -17,16 +22,17 @@ use App\SocialEntity\MastodonAccount;
use App\SocialEntity\PollOption; use App\SocialEntity\PollOption;
use DateTime; use DateTime;
use DateTimeZone; use DateTimeZone;
use Exception;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent; use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\Translation\TranslatorInterface; use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class FediPlanController extends AbstractController class FediPlanController extends AbstractController
@ -39,9 +45,9 @@ class FediPlanController extends AbstractController
public function indexAction(Request $request, AuthorizationCheckerInterface $authorizationChecker, ConnectMastodonAccountFlow $flow, Mastodon_api $mastodon_api, TranslatorInterface $translator, EventDispatcherInterface $eventDispatcher) public function indexAction(Request $request, AuthorizationCheckerInterface $authorizationChecker, ConnectMastodonAccountFlow $flow, Mastodon_api $mastodon_api, TranslatorInterface $translator, EventDispatcherInterface $eventDispatcher)
{ {
if ($authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')){ if ($authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
$local = $request->getSession()->get('_locale'); $local = $request->getSession()->get('_locale');
return $this->redirect($this->generateUrl('schedule',['_locale' => $local])); return $this->redirect($this->generateUrl('schedule', ['_locale' => $local]));
} }
$client = new Client(); $client = new Client();
$flow->bind($client); $flow->bind($client);
@ -50,25 +56,25 @@ class FediPlanController extends AbstractController
$client_id = null; $client_id = null;
$client_secret = null; $client_secret = null;
if ($flow->isValid($form)) { if ($flow->isValid($form)) {
if( $flow->getCurrentStep() == 1){ if ($flow->getCurrentStep() == 1) {
$host = $client->getHost(); $host = $client->getHost();
$result = $mastodon_api->getInstanceNodeInfo($host); $result = $mastodon_api->getInstanceNodeInfo($host);
//We currently only support Mastodon accounts //We currently only support Mastodon accounts
if( $result != "MASTODON" && $result != "PLEROMA"){ if ($result != "MASTODON" && $result != "PLEROMA") {
$form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_only',[],'fediplan','en'))); $form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_only', [], 'fediplan', 'en')));
}else{ } else {
$mastodon_api->set_url("https://" . $host); $mastodon_api->set_url("https://" . $host);
$mastodon_api->set_scopes([]); $mastodon_api->set_scopes([]);
$createApp = $mastodon_api->create_app("FediPlan", [], '', "https://plan.fedilab.app"); $createApp = $mastodon_api->create_app("FediPlan", [], '', "https://plan.fedilab.app");
if( isset($createApp['error']) ){ if (isset($createApp['error'])) {
$form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_client_id',[],'fediplan','en'))); $form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_client_id', [], 'fediplan', 'en')));
}else{ } else {
// form for the next step // form for the next step
$mastodon_api->set_client($createApp['response']['client_id'], $createApp['response']['client_secret']); $mastodon_api->set_client($createApp['response']['client_id'], $createApp['response']['client_secret']);
$urlToMastodon = $mastodon_api->getAuthorizationUrl(); $urlToMastodon = $mastodon_api->getAuthorizationUrl();
if( isset($createApp['error']) ){ if (isset($createApp['error'])) {
$form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_oauth_url',[],'fediplan','en'))); $form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_oauth_url', [], 'fediplan', 'en')));
}else{ } else {
$flow->saveCurrentStepData($form); $flow->saveCurrentStepData($form);
$client_id = $createApp['response']['client_id']; $client_id = $createApp['response']['client_id'];
$client_secret = $createApp['response']['client_secret']; $client_secret = $createApp['response']['client_secret'];
@ -85,48 +91,24 @@ class FediPlanController extends AbstractController
$mastodon_api->set_scopes([]); $mastodon_api->set_scopes([]);
$mastodon_api->set_client($client->getClientId(), $client->getClientSecret()); $mastodon_api->set_client($client->getClientId(), $client->getClientSecret());
$reply = $mastodon_api->loginAuthorization($code); $reply = $mastodon_api->loginAuthorization($code);
if( isset($reply['error']) ){ if (isset($reply['error'])) {
$form->get('code')->addError(new FormError($translator->trans('error.instance.mastodon_token', [], 'fediplan', 'en')));
/* $access_token = $code; } else {
$token_type = "Bearer";
$mastodon_api->set_url("https://" . $client->getHost());
$mastodon_api->set_token($access_token, $token_type);
try {
$accountReply = $mastodon_api->accounts_verify_credentials();
} catch (\ErrorException $e) {
}
if( isset($accountReply['error']) ){
$form->get('code')->addError(new FormError($translator->trans('error.instance.mastodon_account',[],'fediplan','en')));
}else{
$Account = $mastodon_api->getSingleAccount($accountReply['response']);
$Account->setInstance($host);
$Account->setToken($token_type ." ".$access_token);
$token = new UsernamePasswordToken($Account, null, 'main', array('ROLE_USER'));
$this->get('security.token_storage')->setToken($token);
$event = new InteractiveLoginEvent($request, $token);
$eventDispatcher->dispatch("security.interactive_login", $event);
return $this->redirectToRoute('schedule');
}*/
$form->get('code')->addError(new FormError($translator->trans('error.instance.mastodon_token',[],'fediplan','en')));
}else{
$access_token = $reply['response']['access_token']; $access_token = $reply['response']['access_token'];
$token_type = $reply['response']['token_type']; $token_type = $reply['response']['token_type'];
$mastodon_api->set_url("https://" . $client->getHost()); $mastodon_api->set_url("https://" . $client->getHost());
$mastodon_api->set_token($access_token, $token_type); $mastodon_api->set_token($access_token, $token_type);
try {
$accountReply = $mastodon_api->accounts_verify_credentials(); $accountReply = $mastodon_api->accounts_verify_credentials();
} catch (\ErrorException $e) { if (isset($accountReply['error'])) {
} $form->get('code')->addError(new FormError($translator->trans('error.instance.mastodon_account', [], 'fediplan', 'en')));
if( isset($accountReply['error']) ){ } else {
$form->get('code')->addError(new FormError($translator->trans('error.instance.mastodon_account',[],'fediplan','en')));
}else{
$Account = $mastodon_api->getSingleAccount($accountReply['response']); $Account = $mastodon_api->getSingleAccount($accountReply['response']);
$Account->setInstance($host); $Account->setInstance($host);
$Account->setToken($token_type ." ".$access_token); $Account->setToken($token_type . " " . $access_token);
$token = new UsernamePasswordToken($Account, null, 'main', array('ROLE_USER')); $token = new UsernamePasswordToken($Account, null, 'main', array('ROLE_USER'));
$this->get('security.token_storage')->setToken($token); $this->get('security.token_storage')->setToken($token);
$event = new InteractiveLoginEvent($request, $token); $event = new InteractiveLoginEvent($request, $token);
$eventDispatcher->dispatch("security.interactive_login", $event); $eventDispatcher->dispatch($event, "security.interactive_login");
return $this->redirectToRoute('schedule'); return $this->redirectToRoute('schedule');
} }
} }
@ -168,58 +150,55 @@ class FediPlanController extends AbstractController
/* @var $user MastodonAccount */ /* @var $user MastodonAccount */
$user = $this->getUser(); $user = $this->getUser();
$mastodon_api->set_url("https://" . $user->getInstance()); $mastodon_api->set_url("https://" . $user->getInstance());
$token = explode(" ", $user->getToken())[1];
$token = explode(" " ,$user->getToken())[1];
$type = explode(" ", $user->getToken())[0]; $type = explode(" ", $user->getToken())[0];
$mastodon_api->set_token($token, $type); $mastodon_api->set_token($token, $type);
$params = []; $params = [];
//Update media description and store their id //Update media description and store their id
foreach ($_POST as $key => $value){ foreach ($_POST as $key => $value) {
if( $key != "compose"){ if ($key != "compose") {
if (strpos($key, 'media_id_') !== false){ if (strpos($key, 'media_id_') !== false) {
$mediaId = $value; $mediaId = $value;
$description = $_POST['media_description_'.$mediaId]; $description = $_POST['media_description_' . $mediaId];
//update description if needed //update description if needed
if( $description != null && trim($description) != ""){ if ($description != null && trim($description) != "") {
try { $mastodon_api->update_media($mediaId, ['description' => $description]);
$res = $mastodon_api->update_media($mediaId, ['description' => $description]);
} catch (\ErrorException $e) {}
} }
$params['media_ids'][] = $mediaId; $params['media_ids'][] = $mediaId;
} }
} }
} }
//Schedule status //Schedule status
if( $data->getContentWarning() ){ if ($data->getContentWarning()) {
$params['spoiler_text'] = $data->getContentWarning(); $params['spoiler_text'] = $data->getContentWarning();
} }
if( $data->getContent() ){ if ($data->getContent()) {
$params['status'] = $data->getContent(); $params['status'] = $data->getContent();
} }
if( $data->getVisibility() ){ if ($data->getVisibility()) {
$params['visibility'] = $data->getVisibility(); $params['visibility'] = $data->getVisibility();
} }
$params['sensitive'] = ($data->getSensitive() == null || !$data->getSensitive())?false:true; $params['sensitive'] = ($data->getSensitive() == null || !$data->getSensitive()) ? false : true;
$pollOptions = $data->getPollOptions(); $pollOptions = $data->getPollOptions();
$pollExpiresAt = $data->getPollExpiresAt(); $pollExpiresAt = $data->getPollExpiresAt();
$isPollMultiple = $data->isPollMultiple(); $isPollMultiple = $data->isPollMultiple();
if( count($pollOptions) > 0){ if (count($pollOptions) > 0) {
$count_correct_values = 0; $count_correct_values = 0;
foreach($pollOptions as $po) { foreach ($pollOptions as $po) {
/** @var $po PollOption */ /** @var $po PollOption */
if( $po->getTitle() != null && strlen(trim($po->getTitle())) > 0){ if ($po->getTitle() != null && strlen(trim($po->getTitle())) > 0) {
$count_correct_values++; $count_correct_values++;
} }
} }
if( $count_correct_values > 1 ){ if ($count_correct_values > 1) {
$params['poll']['options'] = []; $params['poll']['options'] = [];
foreach($pollOptions as $po) { foreach ($pollOptions as $po) {
/** @var $po PollOption */ /** @var $po PollOption */
if( $po->getTitle() != null && strlen(trim($po->getTitle())) > 0){ if ($po->getTitle() != null && strlen(trim($po->getTitle())) > 0) {
$params['poll']['options'][] = trim($po->getTitle()); $params['poll']['options'][] = trim($po->getTitle());
} }
} }
@ -228,22 +207,21 @@ class FediPlanController extends AbstractController
} }
} }
try { try {
$date = new DateTime( $data->getScheduledAt()->format("Y-m-d H:i"), new DateTimeZone($data->getTimeZone()) ); $date = new DateTime($data->getScheduledAt()->format("Y-m-d H:i"), new DateTimeZone($data->getTimeZone()));
$date->setTimezone( new DateTimeZone("UTC")); $date->setTimezone(new DateTimeZone("UTC"));
$params['scheduled_at'] = $date->format(DateTime::ISO8601); $params['scheduled_at'] = $date->format(DateTime::ISO8601);
} catch (\Exception $e) {} } catch (Exception $e) {
try { }
$response = $mastodon_api->post_statuses($params); $response = $mastodon_api->post_statuses($params);
} catch (\ErrorException $e) {}
$session = $request->getSession(); $session = $request->getSession();
if( isset($response['error']) ){ if (isset($response['error'])) {
$session->getFlashBag()->add( $session->getFlashBag()->add(
'Error', 'Error',
$response['error_message'] $response['error_message']
); );
}else{ } else {
unset($compose); unset($compose);
unset($form); unset($form);
$compose = new Compose(); $compose = new Compose();
@ -263,7 +241,7 @@ class FediPlanController extends AbstractController
$user = $this->getUser(); $user = $this->getUser();
/** @var $user MastodonAccount */ /** @var $user MastodonAccount */
return $this->render("fediplan/schedule.html.twig",[ return $this->render("fediplan/schedule.html.twig", [
'form' => $form->createView(), 'form' => $form->createView(),
'instance' => $user->getInstance(), 'instance' => $user->getInstance(),
'token' => $user->getToken(), 'token' => $user->getToken(),
@ -284,27 +262,19 @@ class FediPlanController extends AbstractController
/** /**
* @Route("/{_locale}/scheduled/messages/{max_id}", options={"expose"=true}, name="load_more") * @Route("/{_locale}/scheduled/messages/{max_id}", options={"expose"=true}, name="load_more")
*/ */
public function loadMoreAction(Mastodon_api $mastodon_api, String $max_id = null){ public function loadMoreAction(Mastodon_api $mastodon_api, string $max_id = null)
{
$user = $this->getUser(); $user = $this->getUser();
/** @var $mastodon_api Mastodon_api */
$mastodon_api->set_url("https://" . $user->getInstance()); $mastodon_api->set_url("https://" . $user->getInstance());
$token = explode(" ", $user->getToken())[1];
$token = explode(" " ,$user->getToken())[1];
$type = explode(" ", $user->getToken())[0]; $type = explode(" ", $user->getToken())[0];
$mastodon_api->set_token($token, $type); $mastodon_api->set_token($token, $type);
$params = []; $params = [];
if ($max_id != null) {
if( $max_id != null){
$params['max_id'] = $max_id; $params['max_id'] = $max_id;
} }
$scheduled_reply = [];
try {
$scheduled_reply = $mastodon_api->get_scheduled($params); $scheduled_reply = $mastodon_api->get_scheduled($params);
} catch (\ErrorException $e) {
}
$statuses = $mastodon_api->getScheduledStatuses($scheduled_reply['response'], $this->getUser()); $statuses = $mastodon_api->getScheduledStatuses($scheduled_reply['response'], $this->getUser());
$data['max_id'] = $scheduled_reply['max_id']; $data['max_id'] = $scheduled_reply['max_id'];
$data['html'] = $this->renderView('fediplan/Ajax/layout.html.twig', ['statuses' => $statuses]); $data['html'] = $this->renderView('fediplan/Ajax/layout.html.twig', ['statuses' => $statuses]);
@ -314,19 +284,14 @@ class FediPlanController extends AbstractController
/** /**
* @Route("/{_locale}/scheduled/delete/messages/{id}", options={"expose"=true}, name="delete_message", methods={"POST"}, defaults={"_locale"="en"}, requirements={"_locale": "%allowed_language%"}) * @Route("/{_locale}/scheduled/delete/messages/{id}", options={"expose"=true}, name="delete_message", methods={"POST"}, defaults={"_locale"="en"}, requirements={"_locale": "%allowed_language%"})
*/ */
public function deleteMessage(Mastodon_api $mastodon_api, String $id = null){ public function deleteMessage(Mastodon_api $mastodon_api, string $id = null)
{
$user = $this->getUser(); $user = $this->getUser();
/** @var $mastodon_api Mastodon_api */
$mastodon_api->set_url("https://" . $user->getInstance()); $mastodon_api->set_url("https://" . $user->getInstance());
$token = explode(" " ,$user->getToken())[1]; $token = explode(" ", $user->getToken())[1];
$type = explode(" ", $user->getToken())[0]; $type = explode(" ", $user->getToken())[0];
$mastodon_api->set_token($token, $type); $mastodon_api->set_token($token, $type);
$response = [];
try {
$response = $mastodon_api->delete_scheduled($id); $response = $mastodon_api->delete_scheduled($id);
} catch (\ErrorException $e) {}
return new JsonResponse($response); return new JsonResponse($response);
} }

View file

@ -22,6 +22,14 @@ class LocaleSubscriber implements EventSubscriberInterface
$this->defaultLocale = $defaultLocale; $this->defaultLocale = $defaultLocale;
} }
public static function getSubscribedEvents()
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 20]],
];
}
public function onKernelRequest(RequestEvent $event) public function onKernelRequest(RequestEvent $event)
{ {
$request = $event->getRequest(); $request = $event->getRequest();
@ -37,12 +45,4 @@ class LocaleSubscriber implements EventSubscriberInterface
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale)); $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
} }
} }
public static function getSubscribedEvents()
{
return [
// must be registered before (i.e. with a higher priority than) the default Locale listener
KernelEvents::REQUEST => [['onKernelRequest', 20]],
];
}
} }

View file

@ -1,4 +1,5 @@
<?php <?php /** @noinspection PhpTranslationKeyInspection */
/** /**
* Created by fediplan. * Created by fediplan.
* User: tom79 * User: tom79
@ -14,6 +15,7 @@ use App\SocialEntity\MastodonAccount;
use DateTime; use DateTime;
use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType; use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType; use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\SubmitType;
@ -22,11 +24,11 @@ use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TimezoneType; use Symfony\Component\Form\Extension\Core\Type\TimezoneType;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Security\Core\Security; use Symfony\Component\Security\Core\Security;
use Symfony\Component\Translation\Translator; use Symfony\Component\Translation\Translator;
class ComposeType extends AbstractType { class ComposeType extends AbstractType
{
private $securityContext; private $securityContext;
@ -40,17 +42,17 @@ class ComposeType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) public function buildForm(FormBuilderInterface $builder, array $options)
{ {
/**@var $user MastodonAccount*/ /**@var $user MastodonAccount */
$user = $options['user']; $user = $options['user'];
if( $user->getDefaultSensitivity()) { if ($user->getDefaultSensitivity()) {
$checkbox = [ $checkbox = [
'required' => false, 'required' => false,
'attr' => ['checked' => 'checked'], 'attr' => ['checked' => 'checked'],
'label' => 'page.schedule.form.sensitive', 'label' => 'page.schedule.form.sensitive',
'translation_domain' => 'fediplan' 'translation_domain' => 'fediplan'
]; ];
}else { } else {
$checkbox = ['required' => false, 'label' => 'page.schedule.form.sensitive', $checkbox = ['required' => false, 'label' => 'page.schedule.form.sensitive',
'translation_domain' => 'fediplan']; 'translation_domain' => 'fediplan'];
} }
@ -79,7 +81,7 @@ class ComposeType extends AbstractType {
'label' => 'page.schedule.form.timeZone', 'label' => 'page.schedule.form.timeZone',
'translation_domain' => 'fediplan']); 'translation_domain' => 'fediplan']);
$builder->add('sensitive', CheckboxType::class, $checkbox); $builder->add('sensitive', CheckboxType::class, $checkbox);
$builder->add('scheduled_at', DateTimeType::class,[ $builder->add('scheduled_at', DateTimeType::class, [
'widget' => 'single_text', 'widget' => 'single_text',
"data" => new DateTime(), "data" => new DateTime(),
'label' => 'page.schedule.form.scheduled_at', 'label' => 'page.schedule.form.scheduled_at',
@ -101,16 +103,16 @@ class ComposeType extends AbstractType {
$builder->add('poll_expires_at', ChoiceType::class, $builder->add('poll_expires_at', ChoiceType::class,
[ [
'choices' => [ 'choices' => [
$this->translator->trans('poll.duration_m', ['minutes' => 5], 'fediplan') => 5*60, $this->translator->trans('poll.duration_m', ['minutes' => 5], 'fediplan') => 5 * 60,
$this->translator->trans('poll.duration_m', ['minutes' => 30], 'fediplan') => 30*60, $this->translator->trans('poll.duration_m', ['minutes' => 30], 'fediplan') => 30 * 60,
$this->translator->trans('poll.duration_h', ['hours' => 1], 'fediplan') => 60*60, $this->translator->trans('poll.duration_h', ['hours' => 1], 'fediplan') => 60 * 60,
$this->translator->trans('poll.duration_h', ['hours' => 6], 'fediplan') => 6*60*60, $this->translator->trans('poll.duration_h', ['hours' => 6], 'fediplan') => 6 * 60 * 60,
$this->translator->trans('poll.duration_d', ['days' => 1], 'fediplan') => 24*60*60, $this->translator->trans('poll.duration_d', ['days' => 1], 'fediplan') => 24 * 60 * 60,
$this->translator->trans('poll.duration_d', ['days' => 3], 'fediplan') => 3*24*60*60, $this->translator->trans('poll.duration_d', ['days' => 3], 'fediplan') => 3 * 24 * 60 * 60,
$this->translator->trans('poll.duration_d', ['days' => 7], 'fediplan') => 7*24*60*60, $this->translator->trans('poll.duration_d', ['days' => 7], 'fediplan') => 7 * 24 * 60 * 60,
], ],
'data' => 24*60*60, 'data' => 24 * 60 * 60,
'required' => false, 'required' => false,
'label' => 'page.schedule.form.end_in', 'label' => 'page.schedule.form.end_in',
'translation_domain' => 'fediplan']); 'translation_domain' => 'fediplan']);

View file

@ -11,9 +11,11 @@ namespace App\Form;
use Craue\FormFlowBundle\Form\FormFlow; use Craue\FormFlowBundle\Form\FormFlow;
class ConnectMastodonAccountFlow extends FormFlow { class ConnectMastodonAccountFlow extends FormFlow
{
protected function loadStepsConfig() { protected function loadStepsConfig()
{
return [ return [
[ [
'form_type' => ConnectMastodonAccountType::class, 'form_type' => ConnectMastodonAccountType::class,

View file

@ -7,15 +7,18 @@
*/ */
namespace App\Form; namespace App\Form;
use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType; use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolver;
class ConnectMastodonAccountType extends AbstractType { class ConnectMastodonAccountType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options) { public function buildForm(FormBuilderInterface $builder, array $options)
{
switch ($options['flow_step']) { switch ($options['flow_step']) {
case 1: case 1:
$builder->add('host', TextType::class, [ $builder->add('host', TextType::class, [
@ -35,7 +38,8 @@ class ConnectMastodonAccountType extends AbstractType {
} }
} }
public function getBlockPrefix() { public function getBlockPrefix()
{
return 'addMastodonAccount'; return 'addMastodonAccount';
} }

View file

@ -14,7 +14,8 @@ use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Security; use Symfony\Component\Security\Core\Security;
class PollOptionType extends AbstractType { class PollOptionType extends AbstractType
{
private $securityContext; private $securityContext;
@ -29,7 +30,7 @@ class PollOptionType extends AbstractType {
$builder->add('title', TextType::class, $builder->add('title', TextType::class,
[ [
'required' => false, 'required' => false,
'attr'=> ['class'=>'form-control'], 'attr' => ['class' => 'form-control'],
'label' => 'page.schedule.form.poll_item', 'label' => 'page.schedule.form.poll_item',
]); ]);
} }

View file

@ -8,6 +8,7 @@ use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel; use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\RouteCollectionBuilder; use Symfony\Component\Routing\RouteCollectionBuilder;
use function dirname;
class Kernel extends BaseKernel class Kernel extends BaseKernel
{ {
@ -17,7 +18,7 @@ class Kernel extends BaseKernel
public function registerBundles(): iterable public function registerBundles(): iterable
{ {
$contents = require $this->getProjectDir().'/config/bundles.php'; $contents = require $this->getProjectDir() . '/config/bundles.php';
foreach ($contents as $class => $envs) { foreach ($contents as $class => $envs) {
if ($envs[$this->environment] ?? $envs['all'] ?? false) { if ($envs[$this->environment] ?? $envs['all'] ?? false) {
yield new $class(); yield new $class();
@ -27,27 +28,27 @@ class Kernel extends BaseKernel
public function getProjectDir(): string public function getProjectDir(): string
{ {
return \dirname(__DIR__); return dirname(__DIR__);
} }
protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader): void protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader): void
{ {
$container->addResource(new FileResource($this->getProjectDir().'/config/bundles.php')); $container->addResource(new FileResource($this->getProjectDir() . '/config/bundles.php'));
$container->setParameter('container.dumper.inline_class_loader', true); $container->setParameter('container.dumper.inline_class_loader', true);
$confDir = $this->getProjectDir().'/config'; $confDir = $this->getProjectDir() . '/config';
$loader->load($confDir.'/{packages}/*'.self::CONFIG_EXTS, 'glob'); $loader->load($confDir . '/{packages}/*' . self::CONFIG_EXTS, 'glob');
$loader->load($confDir.'/{packages}/'.$this->environment.'/**/*'.self::CONFIG_EXTS, 'glob'); $loader->load($confDir . '/{packages}/' . $this->environment . '/**/*' . self::CONFIG_EXTS, 'glob');
$loader->load($confDir.'/{services}'.self::CONFIG_EXTS, 'glob'); $loader->load($confDir . '/{services}' . self::CONFIG_EXTS, 'glob');
$loader->load($confDir.'/{services}_'.$this->environment.self::CONFIG_EXTS, 'glob'); $loader->load($confDir . '/{services}_' . $this->environment . self::CONFIG_EXTS, 'glob');
} }
protected function configureRoutes(RouteCollectionBuilder $routes): void protected function configureRoutes(RouteCollectionBuilder $routes): void
{ {
$confDir = $this->getProjectDir().'/config'; $confDir = $this->getProjectDir() . '/config';
$routes->import($confDir.'/{routes}/'.$this->environment.'/**/*'.self::CONFIG_EXTS, '/', 'glob'); $routes->import($confDir . '/{routes}/' . $this->environment . '/**/*' . self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir.'/{routes}/*'.self::CONFIG_EXTS, '/', 'glob'); $routes->import($confDir . '/{routes}/*' . self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir.'/{routes}'.self::CONFIG_EXTS, '/', 'glob'); $routes->import($confDir . '/{routes}' . self::CONFIG_EXTS, '/', 'glob');
} }
} }

View file

@ -1,7 +1,10 @@
<?php <?php /** @noinspection PhpUnused */
namespace App\Services; namespace App\Services;
use CurlFile;
use ErrorException;
/** /**
* An object-oriented wrapper of the PHP cURL extension. * An object-oriented wrapper of the PHP cURL extension.
* *
@ -67,91 +70,75 @@ class Curl
* @var string The user agent name which is set when making a request * @var string The user agent name which is set when making a request
*/ */
const USER_AGENT = 'PHP Curl/1.9 (+https://github.com/php-mod/curl)'; const USER_AGENT = 'PHP Curl/1.9 (+https://github.com/php-mod/curl)';
private $_cookies = array();
private $_headers = array();
/** /**
* @var resource Contains the curl resource created by `curl_init()` function * @var resource Contains the curl resource created by `curl_init()` function
*/ */
public $curl; public $curl;
/** /**
* @var bool Whether an error occured or not * @var bool Whether an error occured or not
*/ */
public $error = false; public $error = false;
/** /**
* @var int Contains the error code of the curren request, 0 means no error happend * @var int Contains the error code of the curren request, 0 means no error happend
*/ */
public $error_code = 0; public $error_code = 0;
/** /**
* @var string If the curl request failed, the error message is contained * @var string If the curl request failed, the error message is contained
*/ */
public $error_message = null; public $error_message = null;
/** /**
* @var bool Whether an error occured or not * @var bool Whether an error occured or not
*/ */
public $curl_error = false; public $curl_error = false;
/** /**
* @var int Contains the error code of the curren request, 0 means no error happend. * @var int Contains the error code of the curren request, 0 means no error happend.
* @see https://curl.haxx.se/libcurl/c/libcurl-errors.html * @see https://curl.haxx.se/libcurl/c/libcurl-errors.html
*/ */
public $curl_error_code = 0; public $curl_error_code = 0;
/** /**
* @var string If the curl request failed, the error message is contained * @var string If the curl request failed, the error message is contained
*/ */
public $curl_error_message = null; public $curl_error_message = null;
/** /**
* @var bool Whether an error occured or not * @var bool Whether an error occured or not
*/ */
public $http_error = false; public $http_error = false;
/** /**
* @var int Contains the status code of the current processed request. * @var int Contains the status code of the current processed request.
*/ */
public $http_status_code = 0; public $http_status_code = 0;
/** /**
* @var string If the curl request failed, the error message is contained * @var string If the curl request failed, the error message is contained
*/ */
public $http_error_message = null; public $http_error_message = null;
/** /**
* @var string|array TBD (ensure type) Contains the request header informations * @var string|array TBD (ensure type) Contains the request header informations
*/ */
public $request_headers = null; public $request_headers = null;
/** /**
* @var string|array TBD (ensure type) Contains the response header informations * @var string|array TBD (ensure type) Contains the response header informations
*/ */
public $response_headers = array(); public $response_headers = array();
/** /**
* @var string Contains the response from the curl request * @var string Contains the response from the curl request
*/ */
public $response = null; public $response = null;
/** /**
* @var bool Whether the current section of response headers is after 'HTTP/1.1 100 Continue' * @var bool Whether the current section of response headers is after 'HTTP/1.1 100 Continue'
*/ */
protected $response_header_continue = false; protected $response_header_continue = false;
private $_cookies = array();
private $_headers = array();
/** /**
* Constructor ensures the available curl extension is loaded. * Constructor ensures the available curl extension is loaded.
* *
* @throws \ErrorException * @throws ErrorException
*/ */
public function __construct() public function __construct()
{ {
if (!extension_loaded('curl')) { if (!extension_loaded('curl')) {
throw new \ErrorException('The cURL extensions is not loaded, make sure you have installed the cURL extension: https://php.net/manual/curl.setup.php'); throw new ErrorException('The cURL extensions is not loaded, make sure you have installed the cURL extension: https://php.net/manual/curl.setup.php');
} }
$this->init(); $this->init();
@ -176,6 +163,44 @@ class Curl
return $this; return $this;
} }
/**
* Provide a User Agent.
*
* In order to provide you cusomtized user agent name you can use this method.
*
* ```php
* $curl = new Curl();
* $curl->setUserAgent('My John Doe Agent 1.0');
* $curl->get('http://example.com/request.php');
* ```
*
* @param string $useragent The name of the user agent to set for the current request
* @return self
*/
public function setUserAgent($useragent)
{
$this->setOpt(CURLOPT_USERAGENT, $useragent);
return $this;
}
// protected methods
/**
* Set customized curl options.
*
* To see a full list of options: http://php.net/curl_setopt
*
* @see http://php.net/curl_setopt
*
* @param int $option The curl option constante e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION`
* @param mixed $value The value to pass for the given $option
* @return bool
*/
public function setOpt($option, $value)
{
return curl_setopt($this->curl, $option, $value);
}
/** /**
* Handle writing the response headers * Handle writing the response headers
* *
@ -183,6 +208,7 @@ class Curl
* @param string $header_line A line from the list of response headers * @param string $header_line A line from the list of response headers
* *
* @return int Returns the length of the $header_line * @return int Returns the length of the $header_line
* @noinspection PhpUnusedParameterInspection
*/ */
public function addResponseHeaderLine($curl, $header_line) public function addResponseHeaderLine($curl, $header_line)
{ {
@ -199,7 +225,15 @@ class Curl
return strlen($header_line); return strlen($header_line);
} }
// protected methods /**
* @deprecated calling exec() directly is discouraged
*/
public function _exec()
{
return $this->exec();
}
// public methods
/** /**
* Execute the curl request based on the respectiv settings. * Execute the curl request based on the respectiv settings.
@ -224,61 +258,6 @@ class Curl
return $this->error_code; return $this->error_code;
} }
/**
* @param array|object|string $data
*/
protected function preparePayload($data)
{
$this->setOpt(CURLOPT_POST, true);
if (is_array($data) || is_object($data)) {
$skip = false;
foreach ($data as $key => $value) {
// If a value is an instance of CurlFile skip the http_build_query
// see issue https://github.com/php-mod/curl/issues/46
// suggestion from: https://stackoverflow.com/a/36603038/4611030
if ($value instanceof \CurlFile) {
$skip = true;
}
}
if (!$skip) {
$data = http_build_query($data);
}
}
$this->setOpt(CURLOPT_POSTFIELDS, $data);
}
/**
* Set auth options for the current request.
*
* Available auth types are:
*
* + self::AUTH_BASIC
* + self::AUTH_DIGEST
* + self::AUTH_GSSNEGOTIATE
* + self::AUTH_NTLM
* + self::AUTH_ANY
* + self::AUTH_ANYSAFE
*
* @param int $httpauth The type of authentication
*/
protected function setHttpAuth($httpauth)
{
$this->setOpt(CURLOPT_HTTPAUTH, $httpauth);
}
// public methods
/**
* @deprecated calling exec() directly is discouraged
*/
public function _exec()
{
return $this->exec();
}
// functions // functions
/** /**
@ -293,7 +272,7 @@ class Curl
public function get($url, $data = array()) public function get($url, $data = array())
{ {
if (count($data) > 0) { if (count($data) > 0) {
$this->setOpt(CURLOPT_URL, $url.'?'.http_build_query($data)); $this->setOpt(CURLOPT_URL, $url . '?' . http_build_query($data));
} else { } else {
$this->setOpt(CURLOPT_URL, $url); $this->setOpt(CURLOPT_URL, $url);
} }
@ -307,11 +286,12 @@ class Curl
* *
* @param string $url The url to make the post request * @param string $url The url to make the post request
* @param array $data Post data to pass to the url * @param array $data Post data to pass to the url
* @param bool $payload
* @return self * @return self
*/ */
public function post($url, $data = array(), $payload = false) public function post($url, $data = array(), $payload = false)
{ {
if (! empty($data)) { if (!empty($data)) {
if ($payload === false) { if ($payload === false) {
// Check if the url has not already been modified // Check if the url has not already been modified
$url .= strpos($url, '?') !== false ? '&' : '?'; $url .= strpos($url, '?') !== false ? '&' : '?';
@ -327,6 +307,32 @@ class Curl
return $this; return $this;
} }
/**
* @param array|object|string $data
*/
protected function preparePayload($data)
{
$this->setOpt(CURLOPT_POST, true);
if (is_array($data) || is_object($data)) {
$skip = false;
foreach ($data as $key => $value) {
// If a value is an instance of CurlFile skip the http_build_query
// see issue https://github.com/php-mod/curl/issues/46
// suggestion from: https://stackoverflow.com/a/36603038/4611030
if ($value instanceof CurlFile) {
$skip = true;
}
}
if (!$skip) {
$data = http_build_query($data);
}
}
$this->setOpt(CURLOPT_POSTFIELDS, $data);
}
/** /**
* Make a put request with optional data. * Make a put request with optional data.
* *
@ -339,9 +345,9 @@ class Curl
*/ */
public function put($url, $data = array(), $payload = false) public function put($url, $data = array(), $payload = false)
{ {
if (! empty($data)) { if (!empty($data)) {
if ($payload === false) { if ($payload === false) {
$url .= '?'.http_build_query($data); $url .= '?' . http_build_query($data);
} else { } else {
$this->preparePayload($data); $this->preparePayload($data);
} }
@ -365,9 +371,9 @@ class Curl
*/ */
public function patch($url, $data = array(), $payload = false) public function patch($url, $data = array(), $payload = false)
{ {
if (! empty($data)) { if (!empty($data)) {
if ($payload === false) { if ($payload === false) {
$url .= '?'.http_build_query($data); $url .= '?' . http_build_query($data);
} else { } else {
$this->preparePayload($data); $this->preparePayload($data);
} }
@ -379,6 +385,8 @@ class Curl
return $this; return $this;
} }
// setters
/** /**
* Make a delete request with optional data. * Make a delete request with optional data.
* *
@ -389,9 +397,9 @@ class Curl
*/ */
public function delete($url, $data = array(), $payload = false) public function delete($url, $data = array(), $payload = false)
{ {
if (! empty($data)) { if (!empty($data)) {
if ($payload === false) { if ($payload === false) {
$url .= '?'.http_build_query($data); $url .= '?' . http_build_query($data);
} else { } else {
$this->preparePayload($data); $this->preparePayload($data);
} }
@ -403,8 +411,6 @@ class Curl
return $this; return $this;
} }
// setters
/** /**
* Pass basic auth data. * Pass basic auth data.
* *
@ -423,10 +429,29 @@ class Curl
public function setBasicAuthentication($username, $password) public function setBasicAuthentication($username, $password)
{ {
$this->setHttpAuth(self::AUTH_BASIC); $this->setHttpAuth(self::AUTH_BASIC);
$this->setOpt(CURLOPT_USERPWD, $username.':'.$password); $this->setOpt(CURLOPT_USERPWD, $username . ':' . $password);
return $this; return $this;
} }
/**
* Set auth options for the current request.
*
* Available auth types are:
*
* + self::AUTH_BASIC
* + self::AUTH_DIGEST
* + self::AUTH_GSSNEGOTIATE
* + self::AUTH_NTLM
* + self::AUTH_ANY
* + self::AUTH_ANYSAFE
*
* @param int $httpauth The type of authentication
*/
protected function setHttpAuth($httpauth)
{
$this->setOpt(CURLOPT_HTTPAUTH, $httpauth);
}
/** /**
* Provide optional header informations. * Provide optional header informations.
* *
@ -444,32 +469,14 @@ class Curl
*/ */
public function setHeader($key, $value) public function setHeader($key, $value)
{ {
$this->_headers[$key] = $key.': '.$value; $this->_headers[$key] = $key . ': ' . $value;
$this->setOpt(CURLOPT_HTTPHEADER, array_values($this->_headers)); $this->setOpt(CURLOPT_HTTPHEADER, array_values($this->_headers));
return $this; return $this;
} }
/** /**
* Provide a User Agent. * @param $referrer
* * @return Curl
* In order to provide you cusomtized user agent name you can use this method.
*
* ```php
* $curl = new Curl();
* $curl->setUserAgent('My John Doe Agent 1.0');
* $curl->get('http://example.com/request.php');
* ```
*
* @param string $useragent The name of the user agent to set for the current request
* @return self
*/
public function setUserAgent($useragent)
{
$this->setOpt(CURLOPT_USERAGENT, $useragent);
return $this;
}
/**
* @deprecated Call setReferer() instead * @deprecated Call setReferer() instead
*/ */
public function setReferrer($referrer) public function setReferrer($referrer)
@ -506,36 +513,6 @@ class Curl
return $this; return $this;
} }
/**
* Set customized curl options.
*
* To see a full list of options: http://php.net/curl_setopt
*
* @see http://php.net/curl_setopt
*
* @param int $option The curl option constante e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION`
* @param mixed $value The value to pass for the given $option
*/
public function setOpt($option, $value)
{
return curl_setopt($this->curl, $option, $value);
}
/**
* Get customized curl options.
*
* To see a full list of options: http://php.net/curl_getinfo
*
* @see http://php.net/curl_getinfo
*
* @param int $option The curl option constante e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION`
* @param mixed $value The value to check for the given $option
*/
public function getOpt($option)
{
return curl_getinfo($this->curl, $option);
}
/** /**
* Return the endpoint set for curl * Return the endpoint set for curl
* *
@ -548,12 +525,25 @@ class Curl
return $this->getOpt(CURLINFO_EFFECTIVE_URL); return $this->getOpt(CURLINFO_EFFECTIVE_URL);
} }
/**
* Get customized curl options.
*
* To see a full list of options: http://php.net/curl_getinfo
*
* @see http://php.net/curl_getinfo
*
* @param int $option The curl option constante e.g. `CURLOPT_AUTOREFERER`, `CURLOPT_COOKIESESSION`
* @return mixed
*/
public function getOpt($option)
{
return curl_getinfo($this->curl, $option);
}
/** /**
* Enable verbositiy. * Enable verbositiy.
* *
* @todo As to keep naming convention it should be renamed to `setVerbose()` * @param bool $on
*
* @param string $on
* @return self * @return self
*/ */
public function verbose($on = true) public function verbose($on = true)
@ -683,7 +673,7 @@ class Curl
* ``` * ```
* *
* @param string $headerKey Optional key to get from the array. * @param string $headerKey Optional key to get from the array.
* @return bool|string * @return array
* @since 1.9 * @since 1.9
*/ */
public function getResponseHeaders($headerKey = null) public function getResponseHeaders($headerKey = null)
@ -701,7 +691,7 @@ class Curl
} }
if ($headerKey) { if ($headerKey) {
return isset($headers[$headerKey]) ? $headers[$headerKey] : false; return isset($headers[$headerKey]) ? $headers[$headerKey] : [];
} }
return $headers; return $headers;

File diff suppressed because it is too large Load diff

View file

@ -5,7 +5,6 @@ namespace App\SocialEntity;
use DateTime; use DateTime;
use DateTimeInterface; use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
class Compose class Compose
@ -39,7 +38,6 @@ class Compose
public function __construct() public function __construct()
{ {
$this->attachments = new ArrayCollection();
$this->poll_options = new ArrayCollection(); $this->poll_options = new ArrayCollection();
} }

View file

@ -27,9 +27,9 @@ class AppExtension extends AbstractExtension
public function accountEmoji($account, $content) public function accountEmoji($account, $content)
{ {
if( $account instanceof MastodonAccount){ if ($account instanceof MastodonAccount) {
foreach( $account->getEmojis() as $emoji){ foreach ($account->getEmojis() as $emoji) {
$content = preg_replace("(:" . $emoji->getShortcode() .":)", "<img src='". $emoji->getUrl() . "' alt='".$emoji->getShortcode()."' title='".$emoji->getShortcode()."' width='20'/>", $content); $content = preg_replace("(:" . $emoji->getShortcode() . ":)", "<img src='" . $emoji->getUrl() . "' alt='" . $emoji->getShortcode() . "' title='" . $emoji->getShortcode() . "' width='20'/>", $content);
} }
} }
return $content; return $content;
@ -37,9 +37,9 @@ class AppExtension extends AbstractExtension
public function statusEmoji($status, $content) public function statusEmoji($status, $content)
{ {
if( $status instanceof Status){ if ($status instanceof Status) {
foreach( $status->getEmojis() as $emoji){ foreach ($status->getEmojis() as $emoji) {
$content = preg_replace("(:" . $emoji->getShortcode() . ":)", "<img src='". $emoji->getUrl() . "' alt='".$emoji->getShortcode()."' title='".$emoji->getShortcode()."' width='20'/>", $content); $content = preg_replace("(:" . $emoji->getShortcode() . ":)", "<img src='" . $emoji->getUrl() . "' alt='" . $emoji->getShortcode() . "' title='" . $emoji->getShortcode() . "' width='20'/>", $content);
} }
} }
return $content; return $content;
@ -47,7 +47,7 @@ class AppExtension extends AbstractExtension
public function language($locale) public function language($locale)
{ {
switch ($locale){ switch ($locale) {
case "en": case "en":
return "English"; return "English";
case "fr": case "fr":