Codeigniter 4: authfilter filter must have a matching alias defined - linux

I'm new to Codeigniter 4.
I'm developing something localy (Win10/XAMPP) and everything works fine. I uploaded code to linux hosting and suddenly I got error: authfilter filter must have a matching alias defined. 'authfilter' was an allias name in Config/Filters file. Than I noticed that allias is lowercased filter class name, so I changed allias to authfil and now I am getting error: Class 'App\Filters\AuthFilter' not found (SYSTEMPATH/Filters/Filters.php at line 167).
Can anyone explain to me what makes the difference; same code, Windows vs. Linux.
My App/Config/Filters contains following code:
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\SecureHeaders;
use App\Filters\FilterInterface;
use App\Filters\AuthFilter;
class Filters extends BaseConfig
{
/**
* Configures aliases for Filter classes to
* make reading things nicer and simpler.
*
* #var array
*/
public $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'authfil' => \App\Filters\AuthFilter::class,
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* #var array
*/
public $globals = [
'before' => [
// 'honeypot',
// 'csrf',
// 'invalidchars',
'authfil' ///=> ['except' => 'auth/login']
],
'after' => [
'toolbar',
// 'honeypot',
// 'secureheaders',
],
];
My routes looks like:
$routes->group('auth', ['filter' => 'authfil'],['namespace' => 'IonAuth\Controllers'], function ($routes) {
$routes->get('/', 'Auth::index');
$routes->add('login', 'Auth::login');
$routes->get('logout', 'Auth::logout');
...
}
Thanx in advance,
SiniĊĦa
P.S. I put: use App\Filters\AuthFilter to SYSTEMPATH/Filters/Filters.php but with no success. I also tried to add filter to the route, and all combinations that I can think of before I post the question.
The fact is, my project is quite large and today, after few months of working, I find out that I should use filters for login check instead of put login check inside initController function... InitController function is a strange approach to me, instead of using standard OOP concepts (constructors). However, there is a reason for everything, even if it's not obvious to me :).

Related

Can't get CollectionField to work in EasyAdmin 3.0

I am trying to use "Tags" in my Account Entity.
So
I have Entity "Account"
I have Entity "Tag"
In "Account" Entity, I have
/**
* #ORM\ManyToMany(targetEntity=Tag::class, inversedBy="accounts")
* #ORM\JoinTable(name="account_tag")
*/
private $tags;
In "Tag" entity I have
/**
* #ORM\ManyToMany(targetEntity=Account::class, mappedBy="tags")
*/
private $accounts;
In my AccountCrudController => ConfigureFields, I use "CollectionField" for my "tags" property
public function configureFields(string $pageName): iterable
{
return [
TextField::new('name'),
AssociationField::new('owner'),
AssociationField::new('parent'),
CollectionField::new('tags'),
];
}
I am getting below
[Expected value of type "App\Entity\Tag" for association field "App\Entity\Account#$tags", got "string" instead.1
You should be able to use an AssociationField here as well, which would fit your purpose.
AssociationField::new('tags') will allow you to reference existing Tags.
If you wish to create all new Tags together, you could use something like this as there is no way to add Tags on the fly in the AssociationField at the moment.
Have you tried setting your CollectionField like this:
CollectionField::new('tags')
->allowAdd()
->allowDelete()
->setEntryType(TagType::class)
;
The important part is the TagType where you define your own FormType. I am also trying to implement this feature, so if you have a fully working example, let us know!
public function configureFields(string $pageName): iterable
{
return [
TextField::new('name'),
AssociationField::new('owner'),
AssociationField::new('parent'),
CollectionField::new('tags')
->SetEntryType(Tag::class)
];
}

How do I return text from the MediaWiki SearchAfterNoDirectMatch hook?

I am trying to write a MediaWiki Search Hook that will list native files in the file system and then, eventually, allow a person to click on one of the files and view its content.
My extensions.json contains this:
"Hooks": {
"SearchAfterNoDirectMatch": "MediaWiki\\Extension\\NativeFileList\\Hooks::onSearchAfterNoDirectMatch"
},
My Hooks::onSearchAfterNoDirectMatch file looks like this:
namespace MediaWiki\Extension\NativeFileList;
class Hooks {
/**
* #see https://www.mediawiki.org/wiki/Manual:Hooks/SearchAfterNoDirectMatch
* #called from https://gerrit.wikimedia.org/g/mediawiki/core/+/master/includes/search/SearchNearMatcher.php
* #param $searchterm
* #param $title - array of titles
* Returns true if it found something, false is otherwise
*/
public static function onSearchAfterNoDirectMatch( $searchterm, &$title ) {
$title=Title::newFromText( "test", "bar");
return false;
}
}
My problem is that no text is returned. Well, it's worse than that. With the above code, I get an exception (but I don't know how to debug it, because I can't see the exception). If I take the line setting $title out, it returns. If i change the line to $title=undefined(); I get another error. If I set $title="foo"; I get no error, but no foo.
So how do I return a search hit or, even better, a set of search hits?
None of the existing search plug-ins use the modern search Hook api, which is documented in these locations:
https://www.mediawiki.org/wiki/Manual:Hooks/SearchAfterNoDirectMatch
https://gerrit.wikimedia.org/g/mediawiki/core/+/master/includes/search/SearchNearMatcher.php
https://doc.wikimedia.org/mediawiki-core/master/php/classSearchNearMatcher.html
That hook can't return text, you just can change the title in order to generate a match from the hook. $title has to be a Title object, if the code you posted above is the exact code you are using your exception is due to the second parameter not being one of the namespace constants like NS_MAIN
SearchAfterNoDirectMatch is used to return the title of a near-match, rather than to supplement the search results. For supplementing search results, use the onSpecialSearchResultsAppend. Here is code adds three lines to the search results:
class Hooks {
/**
* #see https://www.mediawiki.org/wiki/Manual:Hooks/SearchAfterNoDirectMatch
* #called from https://gerrit.wikimedia.org/g/mediawiki/core/+/master/includes/search/SearchNearMatcher.php
* #param $searchterm
* #param $title - array of titles
*/
public static function onSpecialSearchResultsAppend( $that, $out, $term ) {
$out->addHTML("<h3>Extra Search Results:</h3>");
$out->addHTML("<ul>");
$out->addHTML("<li>Extra Result #1</li>");
$out->addHTML("<li>Extra Result #2</li>");
$out->addHTML("<li>Extra Result #3</li>");
$out->addHTML("</ul>");
}
}
}
That should be enough to get most people going.

Find a div in a block render in Symfony

I am doing a site with symfony 4. I start on this framework and I have a problem of design on my site.
I've been looking for where it might come from, but I can not find the code I'd like to remove.
The part of the code I would like to remove is the following because the result is pretty ugly:
I can not find this in my code:
in my controller :
/**
* #return Response
*/
public function newLetterAction(Request $request): Response
{
$form = $this->createForm(CustomerNewsletterType::class, new Customer());
$form->handleRequest($request);
$facebook = $this->manager->getRepository(ExternalUrl::class)->findOneByCode('facebook');
$instagram = $this->manager->getRepository(ExternalUrl::class)->findOneByCode('instagram');
return $this->templatingEngine->renderResponse('#SyliusShop/Homepage/_newsletter.html.twig', [
'facebook' => $facebook,
'instagram' => $instagram,
'form' => $form->createView(),
'rova_refonte' => (in_array($this->container->get('request_stack')->getMasterRequest()->attributes->get('_route'),["sylius_shop_homepage"]) ? true : false)
]);
}
in my formType :
class CustomerNewsletterType extends AbstractResourceType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('email', EmailType::class, [
'label' => 'app.ui.newsletter',
'attr' => [
'placeholder' => 'app.ui.email'
]
])
;
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix(): string
{
return 'app_customer_newsletter';
}
}
in my twig:
{{ render(controller('app.controller.shop_homepage:newLetterAction')) }}
if anyone could tell me how to find the code, it would help me a lot.
Thank you
Everything is done under the hood when you call $form->createView().
To sum up, every type of field into the form has a base rendering using twig blocks (so does the form itself), which can be overriden. This is what is called the form theme, there's a base one which is usually this one in the twig-bridge.
You can create new themes, extend the existing one, or event create just what you need for a specific form (hint : the getBlockPrefix function in your form type is used for this).
You can find all the documentation about the form rendering here :
https://symfony.com/doc/current/form/form_customization.html
Most functions described in this documentation are in fact calling twig blocks of form themes, and you can find the documentation about this here :
https://symfony.com/doc/current/form/form_themes.html
Keep in mind: Removing such a class / div might break existing CSS, error rendering or everything done in javascript targeting this class.
Most likely you use a bootstrap 3/4 form theme and there works standard form_row template layout.
To customize current form/another form elements, use "How to Work with Form Themes" tutorial.

How to move issues from Google Code to Phabricator

Google Code is shutting down so I want to move my 2500 issues to Phabricator (hosted at Phoreplay).
While there are moving procedure for Github and others, I did not manage to find similar tools for Phabricator.
How to move issues from Google Code to Phabricator?
Only issues, not wiki/code/downloads/etc.
Note: I use Phabricator instead of Github because it fits my requirements better.
Preliminary note if you wish to keep tasks IDs
Migrations project could be facilitated if we can temporarily edit the Maniphest application code, so as you aren't in control of your installation, this is difficult to offer a clean solution to get consistent ID. So, first, you should be in control of your installation.
Such migration code has been written by the Blender project: here their repository at import moment.
The steps
Export Google code tasks in CSV or JSON format
Run a Phabricator script to import them, or, call the API conduit
Export
Google provides some tools to perform the migration. These tools include a issues.py script to parse issues on Google code.
With that, you can dump your issues in a workable format, for example JSON to store an array of comments.
Import through API (best for smallest tasks, without comments)
You could use the API and call through conduit maniphest.createtask. But this is not really convenient, as it's not the easiest way to add comments, closes the issue, etc.
Import through a script
This is probably the most interesting way to import the tasks, and this is the solution offering the maximal flexibility.
Here the skeleton of such script I drafting from the Blender code and some of my internal codes:
#!/usr/bin/env php
<?php
$root = dirname(dirname(__FILE__));
require_once $root . '/scripts/__init_script__.php';
/**
* Represents a task importable into Phabricator
*/
class LegacyTask {
private $id;
private $title;
//... other tasks properties, depending the Google Code fields
public function importIntoPhabricator () {
$projects = ......... // we need an array with one or more PHIDs, according what you created
$task = ManiphestTask::initializeNewTask($reporter);
$task->setTitle($title);
$task->attachProjectPHIDs($projects);
$task->setDescription($this->description);
$task->setPriority($this->priority);
$task->setOverrideID($this->id); //This is the method you want to borrow to the Blender migration code
$task->save();
//Initial transaction
$changes = [
ManiphestTransaction::TYPE_STATUS => ManiphestTaskStatus::STATUS_OPEN,
PhabricatorTransactions::TYPE_VIEW_POLICY => 'public'
];
self::applyTransactionsForChanges($task, $changes);
//Closes task
if ($this->closed) {
$status = ... //ManiphestTaskStatus::STATUS_CLOSED_RESOLVED
self::closeTask($task, $status);
}
//Project transaction
self::associateTaskToProject($task, $projects);
//Adds comments
//...
}
static public function getTransactions ($changes) {
$transactions = [];
$template = new ManiphestTransaction();
foreach ($changes as $type => $value) {
$transaction = clone $template;
$transaction->setTransactionType($type);
if ($type == PhabricatorTransactions::TYPE_EDGE) {
$transaction->setMetadataValue('edge:type', PhabricatorProjectObjectHasProjectEdgeType::EDGECONST);
}
$transaction->setNewValue($value);
$transactions[] = $transaction;
}
return $transactions;
}
static public function applyTransactionsForChanges ($task, $changes) {
$transactions = self::getTransactions($changes);
self::applyTransactions($task, $transactions);
}
static public function applyTransactions ($task, $transactions) {
$editor = id(new ManiphestTransactionEditor())
->setActor(self::getReporterUser())
->setContentSource(self::getContentSource())
->setContinueOnNoEffect(true)
->applyTransactions($task, $transactions);
}
static function associateTaskToProject($task, $projects) {
$project_type = PhabricatorProjectObjectHasProjectEdgeType::EDGECONST;
$transactions = [
id(new ManiphestTransaction())
->setTransactionType(PhabricatorTransactions::TYPE_EDGE)
->setMetadataValue('edge:type', $project_type)
->setNewValue([
'=' => array_fuse($projects)
])
];
self::applyTransactions($task, $transactions);
}
/**
* Closes the task
*/
static public function closeTask ($task, $status) {
$changes = [
ManiphestTransaction::TYPE_STATUS => $status
];
self::applyTransactionsForChanges($task, $changes);
}
}
Close status are documented here.
It works best.
Ask your core developers and top reporters if any to create an account, try to map their users, and for everyone else, attribute issues and comments to a bot account created for the migration.

Groovy - how to use dynamically domain classes static functions

I have list of domain objects which each one of them need to be called as follows:
(<DOMAIN CLASS>.withCriteria {
dataSecurityGroups {
'in' 'id', entitiesIds as Long[]
}
})
The idea is to have this code once, while changing the code a given parameter.
I know that there are several ways to implement it using groovy, and I tried to use them all.
I need to know what is the best practice and short way to do this.
Thanks!
You said you have a List of domain classes so the code below assumes that is true. You don't say what you want to do with the results of each of those queries, so I will assume you have that under control.
You could do something like this...
def listOfDomainClasses = // you have initialized this list somehow...
listOfDomainClasses.each { domainClass ->
def resultForThisClass = domainClass.withCriteria {
dataSecurityGroups {
'in' 'id', entitiesIds as Long[]
}
})
// do something with resultForThisClass
}
I hope that helps.
I'm assuming you are using Grails, since you tagged this question with Gorm. If so, try this:
Class clazz = grailsApplication.domainClasses.find { it.clazz.simpleName == "<DOMAINCLASS>" }.clazz
clazz.withCriteria {
dataSecurityGroups {
'in' 'id', entitiesIds as Long[]
}
}
Or replace grailsApplication.domainClasses and use your list of domain classes instead.
It is not clear what you are really trying to do but maybe what you want is to write a method like this...
/**
* #param someDomainClass A domain class
* #return the results of the query
*/
def myQueryMethod(Class someDomainClass) {
someDomainClass.withCriteria {
dataSecurityGroups {
'in' 'id', entitiesIds as Long[]
}
}
}
Then you can call that method and pass as an argument whatever domain class is appropriate.
Is that the sort of thing you are looking for?

Resources