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/twig-bundle": "4.3.*",
"symfony/yaml": "4.3.*",
"twig/extensions": "^1.5"
"twig/extensions": "^1.5",
"ext-curl": "*",
"ext-json": "*"
},
"require-dev": {
"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.
* User: tom79
@ -17,16 +22,17 @@ use App\SocialEntity\MastodonAccount;
use App\SocialEntity\PollOption;
use DateTime;
use DateTimeZone;
use Exception;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
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\Http\Event\InteractiveLoginEvent;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class FediPlanController extends AbstractController
@ -86,37 +92,13 @@ class FediPlanController extends AbstractController
$mastodon_api->set_client($client->getClientId(), $client->getClientSecret());
$reply = $mastodon_api->loginAuthorization($code);
if (isset($reply['error'])) {
/* $access_token = $code;
$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'];
$token_type = $reply['response']['token_type'];
$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 {
@ -126,7 +108,7 @@ class FediPlanController extends AbstractController
$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);
$eventDispatcher->dispatch($event, "security.interactive_login");
return $this->redirectToRoute('schedule');
}
}
@ -168,7 +150,6 @@ class FediPlanController extends AbstractController
/* @var $user MastodonAccount */
$user = $this->getUser();
$mastodon_api->set_url("https://" . $user->getInstance());
$token = explode(" ", $user->getToken())[1];
$type = explode(" ", $user->getToken())[0];
$mastodon_api->set_token($token, $type);
@ -183,9 +164,7 @@ class FediPlanController extends AbstractController
$description = $_POST['media_description_' . $mediaId];
//update description if needed
if ($description != null && trim($description) != "") {
try {
$res = $mastodon_api->update_media($mediaId, ['description' => $description]);
} catch (\ErrorException $e) {}
$mastodon_api->update_media($mediaId, ['description' => $description]);
}
$params['media_ids'][] = $mediaId;
}
@ -231,10 +210,9 @@ class FediPlanController extends AbstractController
$date = new DateTime($data->getScheduledAt()->format("Y-m-d H:i"), new DateTimeZone($data->getTimeZone()));
$date->setTimezone(new DateTimeZone("UTC"));
$params['scheduled_at'] = $date->format(DateTime::ISO8601);
} catch (\Exception $e) {}
try {
} catch (Exception $e) {
}
$response = $mastodon_api->post_statuses($params);
} catch (\ErrorException $e) {}
$session = $request->getSession();
@ -284,27 +262,19 @@ class FediPlanController extends AbstractController
/**
* @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();
/** @var $mastodon_api Mastodon_api */
$mastodon_api->set_url("https://" . $user->getInstance());
$token = explode(" ", $user->getToken())[1];
$type = explode(" ", $user->getToken())[0];
$mastodon_api->set_token($token, $type);
$params = [];
if ($max_id != null) {
$params['max_id'] = $max_id;
}
$scheduled_reply = [];
try {
$scheduled_reply = $mastodon_api->get_scheduled($params);
} catch (\ErrorException $e) {
}
$statuses = $mastodon_api->getScheduledStatuses($scheduled_reply['response'], $this->getUser());
$data['max_id'] = $scheduled_reply['max_id'];
$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%"})
*/
public function deleteMessage(Mastodon_api $mastodon_api, String $id = null){
public function deleteMessage(Mastodon_api $mastodon_api, string $id = null)
{
$user = $this->getUser();
/** @var $mastodon_api Mastodon_api */
$mastodon_api->set_url("https://" . $user->getInstance());
$token = explode(" ", $user->getToken())[1];
$type = explode(" ", $user->getToken())[0];
$mastodon_api->set_token($token, $type);
$response = [];
try {
$response = $mastodon_api->delete_scheduled($id);
} catch (\ErrorException $e) {}
return new JsonResponse($response);
}

View file

@ -22,6 +22,14 @@ class LocaleSubscriber implements EventSubscriberInterface
$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)
{
$request = $event->getRequest();
@ -37,12 +45,4 @@ class LocaleSubscriber implements EventSubscriberInterface
$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.
* User: tom79
@ -14,6 +15,7 @@ use App\SocialEntity\MastodonAccount;
use DateTime;
use Symfony\Component\Form\AbstractType;
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\DateTimeType;
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\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Translation\Translator;
class ComposeType extends AbstractType {
class ComposeType extends AbstractType
{
private $securityContext;

View file

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

View file

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

View file

@ -14,7 +14,8 @@ use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Security;
class PollOptionType extends AbstractType {
class PollOptionType extends AbstractType
{
private $securityContext;

View file

@ -8,6 +8,7 @@ use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
use function dirname;
class Kernel extends BaseKernel
{
@ -27,7 +28,7 @@ class Kernel extends BaseKernel
public function getProjectDir(): string
{
return \dirname(__DIR__);
return dirname(__DIR__);
}
protected function configureContainer(ContainerBuilder $container, LoaderInterface $loader): void

View file

@ -1,7 +1,10 @@
<?php
<?php /** @noinspection PhpUnused */
namespace App\Services;
use CurlFile;
use ErrorException;
/**
* 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
*/
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
*/
public $curl;
/**
* @var bool Whether an error occured or not
*/
public $error = false;
/**
* @var int Contains the error code of the curren request, 0 means no error happend
*/
public $error_code = 0;
/**
* @var string If the curl request failed, the error message is contained
*/
public $error_message = null;
/**
* @var bool Whether an error occured or not
*/
public $curl_error = false;
/**
* @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
*/
public $curl_error_code = 0;
/**
* @var string If the curl request failed, the error message is contained
*/
public $curl_error_message = null;
/**
* @var bool Whether an error occured or not
*/
public $http_error = false;
/**
* @var int Contains the status code of the current processed request.
*/
public $http_status_code = 0;
/**
* @var string If the curl request failed, the error message is contained
*/
public $http_error_message = null;
/**
* @var string|array TBD (ensure type) Contains the request header informations
*/
public $request_headers = null;
/**
* @var string|array TBD (ensure type) Contains the response header informations
*/
public $response_headers = array();
/**
* @var string Contains the response from the curl request
*/
public $response = null;
/**
* @var bool Whether the current section of response headers is after 'HTTP/1.1 100 Continue'
*/
protected $response_header_continue = false;
private $_cookies = array();
private $_headers = array();
/**
* Constructor ensures the available curl extension is loaded.
*
* @throws \ErrorException
* @throws ErrorException
*/
public function __construct()
{
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();
@ -176,6 +163,44 @@ class Curl
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
*
@ -183,6 +208,7 @@ class Curl
* @param string $header_line A line from the list of response headers
*
* @return int Returns the length of the $header_line
* @noinspection PhpUnusedParameterInspection
*/
public function addResponseHeaderLine($curl, $header_line)
{
@ -199,7 +225,15 @@ class Curl
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.
@ -224,61 +258,6 @@ class Curl
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
/**
@ -307,6 +286,7 @@ class Curl
*
* @param string $url The url to make the post request
* @param array $data Post data to pass to the url
* @param bool $payload
* @return self
*/
public function post($url, $data = array(), $payload = false)
@ -327,6 +307,32 @@ class Curl
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.
*
@ -379,6 +385,8 @@ class Curl
return $this;
}
// setters
/**
* Make a delete request with optional data.
*
@ -403,8 +411,6 @@ class Curl
return $this;
}
// setters
/**
* Pass basic auth data.
*
@ -427,6 +433,25 @@ class Curl
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.
*
@ -450,26 +475,8 @@ class Curl
}
/**
* 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;
}
/**
* @param $referrer
* @return Curl
* @deprecated Call setReferer() instead
*/
public function setReferrer($referrer)
@ -506,36 +513,6 @@ class Curl
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
*
@ -548,12 +525,25 @@ class Curl
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.
*
* @todo As to keep naming convention it should be renamed to `setVerbose()`
*
* @param string $on
* @param bool $on
* @return self
*/
public function verbose($on = true)
@ -683,7 +673,7 @@ class Curl
* ```
*
* @param string $headerKey Optional key to get from the array.
* @return bool|string
* @return array
* @since 1.9
*/
public function getResponseHeaders($headerKey = null)
@ -701,7 +691,7 @@ class Curl
}
if ($headerKey) {
return isset($headers[$headerKey]) ? $headers[$headerKey] : false;
return isset($headers[$headerKey]) ? $headers[$headerKey] : [];
}
return $headers;

File diff suppressed because it is too large Load diff

View file

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