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
@ -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)
{
if ($authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')){
if ($authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
$local = $request->getSession()->get('_locale');
return $this->redirect($this->generateUrl('schedule',['_locale' => $local]));
return $this->redirect($this->generateUrl('schedule', ['_locale' => $local]));
}
$client = new Client();
$flow->bind($client);
@ -50,25 +56,25 @@ class FediPlanController extends AbstractController
$client_id = null;
$client_secret = null;
if ($flow->isValid($form)) {
if( $flow->getCurrentStep() == 1){
if ($flow->getCurrentStep() == 1) {
$host = $client->getHost();
$result = $mastodon_api->getInstanceNodeInfo($host);
//We currently only support Mastodon accounts
if( $result != "MASTODON" && $result != "PLEROMA"){
$form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_only',[],'fediplan','en')));
}else{
if ($result != "MASTODON" && $result != "PLEROMA") {
$form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_only', [], 'fediplan', 'en')));
} else {
$mastodon_api->set_url("https://" . $host);
$mastodon_api->set_scopes([]);
$createApp = $mastodon_api->create_app("FediPlan", [], '', "https://plan.fedilab.app");
if( isset($createApp['error']) ){
$form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_client_id',[],'fediplan','en')));
}else{
if (isset($createApp['error'])) {
$form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_client_id', [], 'fediplan', 'en')));
} else {
// form for the next step
$mastodon_api->set_client($createApp['response']['client_id'], $createApp['response']['client_secret']);
$urlToMastodon = $mastodon_api->getAuthorizationUrl();
if( isset($createApp['error']) ){
$form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_oauth_url',[],'fediplan','en')));
}else{
if (isset($createApp['error'])) {
$form->get('host')->addError(new FormError($translator->trans('error.instance.mastodon_oauth_url', [], 'fediplan', 'en')));
} else {
$flow->saveCurrentStepData($form);
$client_id = $createApp['response']['client_id'];
$client_secret = $createApp['response']['client_secret'];
@ -85,48 +91,24 @@ class FediPlanController extends AbstractController
$mastodon_api->set_scopes([]);
$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{
if (isset($reply['error'])) {
$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{
$Account = $mastodon_api->getSingleAccount($accountReply['response']);
$accountReply = $mastodon_api->accounts_verify_credentials();
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);
$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);
$eventDispatcher->dispatch($event, "security.interactive_login");
return $this->redirectToRoute('schedule');
}
}
@ -168,58 +150,55 @@ class FediPlanController extends AbstractController
/* @var $user MastodonAccount */
$user = $this->getUser();
$mastodon_api->set_url("https://" . $user->getInstance());
$token = explode(" " ,$user->getToken())[1];
$token = explode(" ", $user->getToken())[1];
$type = explode(" ", $user->getToken())[0];
$mastodon_api->set_token($token, $type);
$params = [];
//Update media description and store their id
foreach ($_POST as $key => $value){
if( $key != "compose"){
foreach ($_POST as $key => $value) {
if ($key != "compose") {
if (strpos($key, 'media_id_') !== false){
if (strpos($key, 'media_id_') !== false) {
$mediaId = $value;
$description = $_POST['media_description_'.$mediaId];
$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) {}
if ($description != null && trim($description) != "") {
$mastodon_api->update_media($mediaId, ['description' => $description]);
}
$params['media_ids'][] = $mediaId;
}
}
}
//Schedule status
if( $data->getContentWarning() ){
if ($data->getContentWarning()) {
$params['spoiler_text'] = $data->getContentWarning();
}
if( $data->getContent() ){
if ($data->getContent()) {
$params['status'] = $data->getContent();
}
if( $data->getVisibility() ){
if ($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();
$pollExpiresAt = $data->getPollExpiresAt();
$isPollMultiple = $data->isPollMultiple();
if( count($pollOptions) > 0){
if (count($pollOptions) > 0) {
$count_correct_values = 0;
foreach($pollOptions as $po) {
foreach ($pollOptions as $po) {
/** @var $po PollOption */
if( $po->getTitle() != null && strlen(trim($po->getTitle())) > 0){
if ($po->getTitle() != null && strlen(trim($po->getTitle())) > 0) {
$count_correct_values++;
}
}
if( $count_correct_values > 1 ){
if ($count_correct_values > 1) {
$params['poll']['options'] = [];
foreach($pollOptions as $po) {
foreach ($pollOptions as $po) {
/** @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());
}
}
@ -228,22 +207,21 @@ class FediPlanController extends AbstractController
}
}
try {
$date = new DateTime( $data->getScheduledAt()->format("Y-m-d H:i"), new DateTimeZone($data->getTimeZone()) );
$date->setTimezone( new DateTimeZone("UTC"));
$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 {
$response = $mastodon_api->post_statuses($params);
} catch (\ErrorException $e) {}
} catch (Exception $e) {
}
$response = $mastodon_api->post_statuses($params);
$session = $request->getSession();
if( isset($response['error']) ){
if (isset($response['error'])) {
$session->getFlashBag()->add(
'Error',
$response['error_message']
);
}else{
} else {
unset($compose);
unset($form);
$compose = new Compose();
@ -263,11 +241,11 @@ class FediPlanController extends AbstractController
$user = $this->getUser();
/** @var $user MastodonAccount */
return $this->render("fediplan/schedule.html.twig",[
return $this->render("fediplan/schedule.html.twig", [
'form' => $form->createView(),
'instance' => $user->getInstance(),
'token' => $user->getToken(),
]);
]);
}
@ -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];
$token = explode(" ", $user->getToken())[1];
$type = explode(" ", $user->getToken())[0];
$mastodon_api->set_token($token, $type);
$params = [];
if( $max_id != null){
if ($max_id != null) {
$params['max_id'] = $max_id;
}
$scheduled_reply = [];
try {
$scheduled_reply = $mastodon_api->get_scheduled($params);
} catch (\ErrorException $e) {
}
$scheduled_reply = $mastodon_api->get_scheduled($params);
$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];
$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) {}
$response = $mastodon_api->delete_scheduled($id);
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;
@ -40,17 +42,17 @@ class ComposeType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
/**@var $user MastodonAccount*/
/**@var $user MastodonAccount */
$user = $options['user'];
if( $user->getDefaultSensitivity()) {
if ($user->getDefaultSensitivity()) {
$checkbox = [
'required' => false,
'attr' => ['checked' => 'checked'],
'label' => 'page.schedule.form.sensitive',
'translation_domain' => 'fediplan'
];
}else {
} else {
$checkbox = ['required' => false, 'label' => 'page.schedule.form.sensitive',
'translation_domain' => 'fediplan'];
}
@ -79,7 +81,7 @@ class ComposeType extends AbstractType {
'label' => 'page.schedule.form.timeZone',
'translation_domain' => 'fediplan']);
$builder->add('sensitive', CheckboxType::class, $checkbox);
$builder->add('scheduled_at', DateTimeType::class,[
$builder->add('scheduled_at', DateTimeType::class, [
'widget' => 'single_text',
"data" => new DateTime(),
'label' => 'page.schedule.form.scheduled_at',
@ -87,7 +89,7 @@ class ComposeType extends AbstractType {
$builder->add('poll_options', CollectionType::class,
[
'entry_type' => PollOptionType::class,
'entry_type' => PollOptionType::class,
'by_reference' => false,
'allow_add' => true,
'prototype' => true,
@ -101,16 +103,16 @@ class ComposeType extends AbstractType {
$builder->add('poll_expires_at', ChoiceType::class,
[
'choices' => [
$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_h', ['hours' => 1], 'fediplan') => 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' => 3], 'fediplan') => 3*24*60*60,
$this->translator->trans('poll.duration_d', ['days' => 7], 'fediplan') => 7*24*60*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_h', ['hours' => 1], 'fediplan') => 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' => 3], 'fediplan') => 3 * 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,
'label' => 'page.schedule.form.end_in',
'translation_domain' => 'fediplan']);

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,19 +7,22 @@
*/
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, [
'label' => 'page.index.form.instance',
'label' => 'page.index.form.instance',
'translation_domain' => 'fediplan'
]);
break;
@ -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;
@ -29,7 +30,7 @@ class PollOptionType extends AbstractType {
$builder->add('title', TextType::class,
[
'required' => false,
'attr'=> ['class'=>'form-control'],
'attr' => ['class' => 'form-control'],
'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\HttpKernel\Kernel as BaseKernel;
use Symfony\Component\Routing\RouteCollectionBuilder;
use function dirname;
class Kernel extends BaseKernel
{
@ -17,7 +18,7 @@ class Kernel extends BaseKernel
public function registerBundles(): iterable
{
$contents = require $this->getProjectDir().'/config/bundles.php';
$contents = require $this->getProjectDir() . '/config/bundles.php';
foreach ($contents as $class => $envs) {
if ($envs[$this->environment] ?? $envs['all'] ?? false) {
yield new $class();
@ -27,27 +28,27 @@ class Kernel extends BaseKernel
public function getProjectDir(): string
{
return \dirname(__DIR__);
return dirname(__DIR__);
}
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);
$confDir = $this->getProjectDir().'/config';
$confDir = $this->getProjectDir() . '/config';
$loader->load($confDir.'/{packages}/*'.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}_'.$this->environment.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 . '/{services}' . self::CONFIG_EXTS, 'glob');
$loader->load($confDir . '/{services}_' . $this->environment . self::CONFIG_EXTS, 'glob');
}
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}/*'.self::CONFIG_EXTS, '/', 'glob');
$routes->import($confDir.'/{routes}'.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');
}
}

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)
{
@ -195,11 +221,19 @@ class Curl
} elseif (!$this->response_header_continue) {
$this->response_headers[] = $trimmed_header;
}
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
/**
@ -286,14 +265,14 @@ class Curl
*
* The get request has no body data, the data will be correctly added to the $url with the http_build_query() method.
*
* @param string $url The url to make the get request for
* @param array $data Optional arguments who are part of the url
* @param string $url The url to make the get request for
* @param array $data Optional arguments who are part of the url
* @return self
*/
public function get($url, $data = array())
{
if (count($data) > 0) {
$this->setOpt(CURLOPT_URL, $url.'?'.http_build_query($data));
$this->setOpt(CURLOPT_URL, $url . '?' . http_build_query($data));
} else {
$this->setOpt(CURLOPT_URL, $url);
}
@ -305,13 +284,14 @@ class Curl
/**
* Make a post request with optional post data.
*
* @param string $url The url to make the post request
* @param array $data Post data to pass to the url
* @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)
{
if (! empty($data)) {
if (!empty($data)) {
if ($payload === false) {
// Check if the url has not already been modified
$url .= strpos($url, '?') !== 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.
*
@ -339,9 +345,9 @@ class Curl
*/
public function put($url, $data = array(), $payload = false)
{
if (! empty($data)) {
if (!empty($data)) {
if ($payload === false) {
$url .= '?'.http_build_query($data);
$url .= '?' . http_build_query($data);
} else {
$this->preparePayload($data);
}
@ -365,9 +371,9 @@ class Curl
*/
public function patch($url, $data = array(), $payload = false)
{
if (! empty($data)) {
if (!empty($data)) {
if ($payload === false) {
$url .= '?'.http_build_query($data);
$url .= '?' . http_build_query($data);
} else {
$this->preparePayload($data);
}
@ -379,6 +385,8 @@ class Curl
return $this;
}
// setters
/**
* Make a delete request with optional data.
*
@ -389,9 +397,9 @@ class Curl
*/
public function delete($url, $data = array(), $payload = false)
{
if (! empty($data)) {
if (!empty($data)) {
if ($payload === false) {
$url .= '?'.http_build_query($data);
$url .= '?' . http_build_query($data);
} else {
$this->preparePayload($data);
}
@ -403,8 +411,6 @@ class Curl
return $this;
}
// setters
/**
* Pass basic auth data.
*
@ -423,10 +429,29 @@ class Curl
public function setBasicAuthentication($username, $password)
{
$this->setHttpAuth(self::AUTH_BASIC);
$this->setOpt(CURLOPT_USERPWD, $username.':'.$password);
$this->setOpt(CURLOPT_USERPWD, $username . ':' . $password);
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.
*
@ -438,38 +463,20 @@ class Curl
* $curl->get('http://example.com/request.php');
* ```
*
* @param string $key The header key
* @param string $key The header key
* @param string $value The value for the given header key
* @return self
*/
public function setHeader($key, $value)
{
$this->_headers[$key] = $key.': '.$value;
$this->_headers[$key] = $key . ': ' . $value;
$this->setOpt(CURLOPT_HTTPHEADER, array_values($this->_headers));
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;
}
/**
* @param $referrer
* @return Curl
* @deprecated Call setReferer() instead
*/
public function setReferrer($referrer)
@ -495,7 +502,7 @@ class Curl
/**
* Set contents of HTTP Cookie header.
*
* @param string $key The name of the cookie
* @param string $key The name of the cookie
* @param string $value The value for the provided cookie name
* @return self
*/
@ -507,53 +514,36 @@ class Curl
}
/**
* Set customized curl options.
* Return the endpoint set for curl
*
* To see a full list of options: http://php.net/curl_setopt
* @see http://php.net/curl_getinfo
*
* @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 string of endpoint
*/
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
*
* @see http://php.net/curl_getinfo
*
* @return string of endpoint
*/
public function getEndpoint()
{
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)
@ -662,7 +652,7 @@ class Curl
{
return $this->http_status_code >= 500 && $this->http_status_code < 600;
}
/**
* Get a specific response header key or all values from the response headers array.
*
@ -683,27 +673,27 @@ 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)
{
$headers = array();
$headerKey = strtolower($headerKey);
foreach ($this->response_headers as $header) {
$parts = explode(":", $header, 2);
$key = isset($parts[0]) ? $parts[0] : null;
$value = isset($parts[1]) ? $parts[1] : null;
$headers[trim(strtolower($key))] = trim($value);
}
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();
}

View file

@ -27,19 +27,19 @@ class AppExtension extends AbstractExtension
public function accountEmoji($account, $content)
{
if( $account instanceof MastodonAccount){
foreach( $account->getEmojis() as $emoji){
$content = preg_replace("(:" . $emoji->getShortcode() .":)", "<img src='". $emoji->getUrl() . "' alt='".$emoji->getShortcode()."' title='".$emoji->getShortcode()."' width='20'/>", $content);
if ($account instanceof MastodonAccount) {
foreach ($account->getEmojis() as $emoji) {
$content = preg_replace("(:" . $emoji->getShortcode() . ":)", "<img src='" . $emoji->getUrl() . "' alt='" . $emoji->getShortcode() . "' title='" . $emoji->getShortcode() . "' width='20'/>", $content);
}
}
return $content;
return $content;
}
public function statusEmoji($status, $content)
{
if( $status instanceof Status){
foreach( $status->getEmojis() as $emoji){
$content = preg_replace("(:" . $emoji->getShortcode() . ":)", "<img src='". $emoji->getUrl() . "' alt='".$emoji->getShortcode()."' title='".$emoji->getShortcode()."' width='20'/>", $content);
if ($status instanceof Status) {
foreach ($status->getEmojis() as $emoji) {
$content = preg_replace("(:" . $emoji->getShortcode() . ":)", "<img src='" . $emoji->getUrl() . "' alt='" . $emoji->getShortcode() . "' title='" . $emoji->getShortcode() . "' width='20'/>", $content);
}
}
return $content;
@ -47,26 +47,26 @@ class AppExtension extends AbstractExtension
public function language($locale)
{
switch ($locale){
case "en":
return "English";
case "fr":
return "Français";
case "de":
return "Deutsch";
case "nl":
return "Nederlands";
case "pt-PT":
return "Português";
case "pt-BR":
return "Brasil";
case "it":
return "Italiano";
case "ca":
return "Català";
case "ar":
return "العربية";
switch ($locale) {
case "en":
return "English";
case "fr":
return "Français";
case "de":
return "Deutsch";
case "nl":
return "Nederlands";
case "pt-PT":
return "Português";
case "pt-BR":
return "Brasil";
case "it":
return "Italiano";
case "ca":
return "Català";
case "ar":
return "العربية";
}
}
}
}