Posts

Showing posts from 2023

Git - How to revert, cancel last changes on remote server

Sometimes you do something wrong. For example, push to master branch dev commits or something else, what does not have to find itself here.  There are present a lot of official recommends how to push revert commits... but honestly, in my case, it does not work in proper way, as you want. So, I found ferroconcrete method how to solve this issue. But it seems to somebody not gracefully, but it works at least. First step: Revert to required commit.  git reset --hard <commit-hash> (This command will reset the branch to the specified commit. Be cautious when using --hard as it will discard changes in your working directory and staging area.) Second step: Create new branch from this point.  git checkout -b <new-branch-name> (This command creates a new branch and switches to it. Replace <new-branch-name> with the desired name for your new branch.) Third step: Remove your damaged branch on server. git push origin --delete <branch-name> (Replace <branch-name> with

Symfony - Doctrine - How to change old attributes in entity to new PHP 8 attributes

Old-Style Annotations: Written as comments, typically using PHPDoc syntax (/** ... */). Annotations are interpreted by external tools or libraries. Doctrine ORM interprets annotations to configure database mappings. Limited flexibility in terms of syntax and available metadata types. May lack type safety and validation. PHP 8 Attributes: Written using the #[...] syntax. Introduced as a language feature in PHP 8 for adding metadata directly to code. Provides a more structured and standardized way of associating metadata with classes, methods, or properties. Attributes are a built-in language feature, eliminating the need for external interpretation in many cases. Attributes are directly handled by the PHP runtime. Offers better type safety and validation compared to traditional annotations. Supports the use of PHP's native types and expressions within attribute values. Attributes support namespacing, allowing for better organization and

JavaScript - How to create select options from array

Define an array with the values you want to populate in the <select> element. var fruits = ["Apple", "Banana", "Orange", "Grapes", "Mango"]; Create a <select> element in your HTML markup. <select id="mySelect"></select> Iterate through the array and create <option> elements for each value, then append them to the <select> element. Here's an example: document.addEventListener("DOMContentLoaded", function () { var fruits = ["Apple", "Banana", "Orange", "Grapes", "Mango"]; var selectElement = document.getElementById("mySelect"); for (var i = 0; i < fruits.length; i++) { var option = document.createElement("option"); option.value = fruits[i]; option.text = fruits[i]; selectElement.appendChild(option); } }); In this example, the JavaScript code runs

Symfony - Doctrine - How to add subquery into where clause

If you want to add subquery into where clause, you need to create subquery firstly: $sub = $this->_em->createQueryBuilder()             ->select('cf.id')             ->from(CustomField::class, 'cf')             ->where('cf.type = :type AND cf.fieldName = :fieldName'); After that you can use this subquery as DQL: $this->_em->createQueryBuilder()->expr()->in('cfv.fieldId', $sub->getDQL()) In that case we use it as IN condition. But it is just example. And finally it will look like that: $this->createQueryBuilder('cfv')             ->update(CustomFieldValue::class, 'cfv')             ->set('cfv.value', ':value')             ->where($this->_em->createQueryBuilder()->expr()->in('cfv.fieldId', $sub->getDQL()))             ->setParameter(':type', 'product')             ->setParameter(':fieldName', $fieldName)            

WordPress - How to create simple plugin with shortcode

Creating a simple WordPress plugin involves a few steps. Below is an example of a minimalistic WordPress plugin that adds a custom shortcode to display a greeting message. Step 1: Set Up Plugin Structure Create a new folder for your plugin in the "wp-content/plugins" directory. Let's call it "simple-greeting-plugin". Step 2: Create the Main Plugin File Inside your plugin folder (simple-greeting-plugin), create a main PHP file, e.g., "simple-greeting-plugin.php". Step 3: Add Plugin Information In your main PHP file, add the plugin information in the comment header. <?php /* Plugin Name: Simple Greeting Plugin Description: A simple WordPress plugin that adds a greeting shortcode. Version: 1.0 Author: Your Name */ Step 4: Add Greeting Shortcode Functionality Now, let's add the functionality to display a greeting message using a shortcode. Update your "simple-greeting-plugin.php" file as follows: <?php /* Plugin Name:

Symfony - How to fix Circular Reference

 A circular reference in Symfony typically occurs when there's a loop in the dependency injection graph. It means that one service depends on another service, which in turn depends on the first one, creating an infinite loop. Check Your Service Definitions: Review your service definitions in the services.yaml or other configuration files. Look for any circular dependencies. A circular reference often occurs when Service A depends on Service B, and Service B depends on Service A. Use Setter Injection: Instead of injecting dependencies through the constructor, use setter injection. In Symfony, you can use setter injection by creating setter methods in your services and injecting dependencies through these methods after the service is instantiated. Lazy Loading: Consider using lazy loading for dependencies. Symfony allows lazy loading of services, which means that the actual instantiation of a service is delayed until it's actually used. You can enable lazy loading for a service b

PHP - How to show expected return array elements

When your function or method returns an associative array, it's beneficial to document the expected structure of that array using PHPDoc type annotations. This practice not only serves as documentation for developers using your code but also enables features like auto-completion in integrated development environments (IDEs). For example: /** * Creates a user. * * @return array{"name": string, "age": int, "married": bool} */ function createUser(): array { return ['name' => 'Nayf', 'age' => 38, 'married' => true]; } In this PHPDoc block, the @return annotation is used to specify that the function returns an associative array with three elements: "name" of type string, "age" of type int, and "married" of type bool. This information provides clarity on the expected structure of the returned array. The PHPDoc type system supports various basic PHP types such as string, bool, in

Symfony - How to generate URL without controller or path

If you need to generate URL out of controller, you need to create you own Route with necessary path. $route = new \Symfony\Component\Routing\Route('/calculator/new'); And add this route to Route Collection: $routes = new \Symfony\Component\Routing\RouteCollection(); $routes->add('calculator_new', $route); After that you can generate URL: $generator = new \Symfony\Component\Routing\Generator\UrlGenerator($routes, new \Symfony\Component\Routing\RequestContext()); $url = $generator->generate('calculator_new'); This returns: "/calculator/new" If you need to add any query parameters: $url = $generator->generate('calculator_new', ['width' => 100]); This will return "/calculator/new?width=100" as the generated URL, including the specified query parameter. In summary, by creating a route, adding it to a collection, and using a URL generator, you can easily generate URLs and include additional query parameters

Javascript - How to build URL with query parameters

If we just need to add GET parameters to current URL: Firstly, let`s create URL object with current link. const url = new URL(window.location.protocol+window.location.host+window.location.pathname); Where: window.location.protocol - https or http; window.location.host - current host; window.location.pathname - current url after host and before query parameter; After that, let`s add necessary query parameters: url.searchParams.set('id', 123); And get URL what we wanted: url.toString(); For example, let`s redirect to new URL: window.location.href = url.toString();

PHP - How to explode empty string with empty array

When you try to explode empty string, you get not empty array, as we would have assumption, but array with one element with blank string. PHP says it is not a bug. So, we need to find a way how to avoid this behavior. As we don`t want to have any element in array after exploding empty string. We want to have empty array as well, obviously. We can use "array_filter" function to remove empty element in array. Example: $correctArray = array_filter(explode(';', ''));

Chrome - This page is not secure (broken HTTPS) How to fix certificate

Today I faced with problem of expired ssl certificate for website. But even after updating (renew) certificate, browser continue to show error "This page is not secure (broken HTTPS)". But at the same time, it shows me that certificate is valid. What didn`t I do: clean cache and cookies where I could find it explored all the settings googled everywhere and nothing helped me. When my patience is over, I just try to open this link in new tab , and it works. Madness.

MySQL - How to copy full Database fast

I know one dirty life-hack, how to copy full data from database with all configs and users. Just copy all files from old base to new one . For example (for Linux): cp -r /var/lib/mysql /new_destination It will transfer not only data from database, but and users with their own passwords and privileges. NOTE: It works only if you database placed on one host (server). I must emphasize that using the method described above to copy a database, including configurations and users, can have serious consequences and is not recommended for various reasons. Firstly, it may violate privacy and security regulations, potentially exposing sensitive information. Secondly, this approach might lead to compatibility issues and corruption of data in the new destination. Moreover, it could compromise the integrity of the database and jeopardize the overall system's stability. It's crucial to follow proper procedures when migrating or copying databases to ensure data security, integrity, and

Wordpress - REST API - How to set up roles

Wordpress REST API allows roles as array. But when you try to set roles as it is, it throws error. Correct list of roles: administrator editor author contributor subscriber customer As you see, all of these role names must be in lower case . For example: $user = WordpressAPI::createUser([ 'username' => 'test', 'email' => 'test@gmail.com', 'password' => '123456QQQ', 'roles' => ['subscriber'] ]); And you can add your own roles that you created in system.

Wordpress - How to log errors

On the first glance, it is easy to answer on this question. But, it is not. Yes, you can simply set WP_DEBUG constant to true, as many sites recommend. But, probably, it comes more problems than convenience. Because, it throws out all unnecessary, for your case, messages on the site, and, most likely, just fall apart whole layout. So, I recommend, do not switch on WP_DEBUG constant, and log what you want silently from users. For that: Set WP_DEBUG constant to true. We need to set up WP_DEBUG_DISPLAY constant to false, to hide errors from users. Write where you need error_log(). After that, you can check your logs and see error messages. If not, try to set up WP_DEBUG_LOG constant. There should be path to log file. wp-config.php file: define( 'WP_DEBUG', true ); define( 'WP_DEBUG_DISPLAY', false ); define( 'WP_DEBUG_LOG', '/path/to/log/file.txt' ); // if needed

Javascript - jQuery - Make menu item Active automatically

There is, as minimum, two ways how to add 'active' class to menu item, to highlight it. First one is on backend side. Second one is on frontend side. Now, I talk about variant with frontend side. So, I choose javascript to decide to add 'active' class to menu item or not. There is a code for this: var pathName = window.location.pathname; // Iterate through each anchor tag within list items $("ul li a").each(function () { // Check if the href attribute matches the current URL if ($(this).attr("href") == pathName) { // If there is a match, traverse up the DOM hierarchy to find the corresponding list item $(this).parents('li').each(function () { // Add the 'active' class to highlight the menu item $(this).addClass("active"); }); } }); This script essentially loops through all anchor "a" tags within list items "li" in the specified unordered list "ul". For each a

Symfony - How to logout locked or banned User automatically

If you want to logout locked or banned User automatically, you need, first of all, add new Listener with onKernelRequest(RequestEvent $event) method. Just FYI, this method Symfony calls every time on every request, so, be careful to use this method. It can shoot yourself in the foot. For example: class SecurityUserListener { public function onKernelRequest(RequestEvent $event) { } } After that, we need to check our User on status: banned or locked (what you need). For this we need to inject Token Storage in class constructor. Token Storage can return User. So, lets do it: class SecurityUserListener { public function __construct(private TokenStorageInterface $tokenStorage) { } public function onKernelRequest(RequestEvent $event) { $user = $this->tokenStorage->getToken()?->getUser(); } } Now, you can examine the user object's status. If it meets your criteria, set the current token to null (indicating no user in the token anymore) and

MySQL - How to rename, replace column

If you are not lucky like me, and do not have MySQL 8.0 version or higher, there is only one way to rename column in table is using CHANGE command. For example: ALTER TABLE products CHANGE old_column new_column INT NOT NULL; For MySQL 8.0 you can use next syntax: ALTER TABLE products RENAME COLUMN old_column TO new_column; But when you use RENAME command, you are not allow to change data type of this column, only name.

Symfony - How to make Facade Service

A Facade Service is employed to obtain any service through a public static method, as opposed to injecting it via the constructor. For example (facade service): Facade::getEntityManager(); In this example, the getEntityManager method is accessed directly from the Facade, providing a simplified and centralized way to obtain the EntityManager service. For example (injecting service): class test { public function __construct(private EntityManagerInterface $em) {} } In this case, the EntityManager service is injected into the constructor of the Test class. While this is a valid approach, Facade Services offer an alternative method for obtaining services. To add creating facade possibility, first of all, need to set Service Container to Bundle boot() method. For example: class CoreBundle extends Bundle { private static $serviceContainer; public function boot() { parent::boot(); self::$serviceContainer = $this->container; } } Now, we have Se

JavaScript - jQuery - How to get array values from multiple select

There are various ways to retrieve the selected values from a "<select>" element in jQuery.  The simplest method involves using the "val()" function, like so: $('select').val();  However, this straightforward approach has its limitations, particularly when it comes to manipulating the selected data.  If you require more control and flexibility in handling the selected options, you can leverage the power of the map function: $('select option:selected').map((index, option) => option.value).get(); In this enhanced method, the map function allows you to iterate through the selected options, providing you with greater control over the extraction process.  The addition of the ":selected" filter in the selector ensures that only the chosen options are considered, enhancing the precision of your selection process. This proves invaluable when dealing with scenarios where you need to perform specific actions or manipulations based on the sel

MySQL - How to add JSON column type

 I use Doctrine ORM with Symfony framework.  Doctrine entities have the capability to handle JSON type columns, automatically converting data from an array to JSON and vice versa. This means they can effortlessly perform the conversion of data from an array format to JSON and vice versa, offering a convenient and dynamic approach. This proves exceptionally useful in scenarios such as storing and managing various settings within the database. Hence, to create a new column in a table with a JSON type, use the following syntax: settings LONGTEXT DEFAULT NULL COMMENT '(DC2Type:json)' This concise yet powerful declaration ensures that the column is set up to handle JSON data effectively. For adding a new column to an existing 'tblcontacts' table, execute the following SQL query: ALTER TABLE tblcontacts ADD COLUMN settings LONGTEXT DEFAULT NULL COMMENT '(DC2Type:json)'; The critical aspect here is the "COMMENT '(DC2Type:json)'". This specific c

MySQL - How to check if exist foreign key

In MySQL, the "IF EXIST" clause doesn't function when checking a foreign key. There is only one method I know to perform this check. Information regarding constraints is stored in the general MySQL table  "information_schema.TABLE_CONSTRAINTS".  The "TABLE_NAME" column indicates the table where the constraint exists. The "CONSTRAINT_NAME" column represents the name of your constraint. The "CONSTRAINT_TYPE" column defines the type of your constraint; in our case, it is a "FOREIGN KEY". So, for example, if you want to check all foreign keys in your table: SELECT * FROM information_schema.TABLE_CONSTRAINTS  WHERE TABLE_NAME='name_of_your_table' AND CONSTRAINT_TYPE='FOREIGN KEY'; In my case it shows: CONSTRAINT_CATALOG CONSTRAINT_SCHEMA CONSTRAINT_NAME TABLE_SCHEMA TABLE_NAME CONSTRAINT_TYPE def test FK_9CA1B3534C397118 test tblproducts FOREIGN KEY def te

Bootstrap - How to make toggle buttons

 At least, you need to have Bootstrap 5 or higher version. The code below will insert Default toggle button. Actually, it is checkbox. < input type ="checkbox" class ="btn-check" id ="default" autocomplete ="off" > < label class ="btn btn-outline-success" for ="default" >Default</ label > And also you can change the color of button by label class. It has checkbox behavior. It means, when it is checked, the toggle button switches own state. So, you can just change checkbox status by 'checked' attribute as usual, and toggle button show this as well.

Idea PhpStorm - How to fix bugs with incorrect code Inspections and Autocomplete

Image
Sometimes IDE starts to show something unpredictable and strange behavior.  For example, PhpStorm says that class is not exist in your project. Or you set up incorrect namespace. Cause all of these things is broken indexes and IDE cache. To fix this problem easy:  Go to Main Menu -> Invalidate Caches Choose Clear file system cache and Local History. Check VCS log caches and indexes. Invalidate and Restart . After that your IDE restarts and relaunch with new indexes. All have to work correctly.

Codeception 5.0 - Error: Call to a member function grabService() on null; Call to a member function grabEntityFromRepository() on null

 If you were on previous version of Codeception, and updated to 5.* you can catch errors like: Call to a member function grabService() on null;  Call to a member function grabEntityFromRepository() on null  To fix this, you need to update your unit.suite.yml config file: replace ' class_name : UnitTester' to ' actor : UnitTester'. So, now, you need to specify your actor class in config file. After that, codeception can see your UnitTester class.

Idea PhpStorm - Database - No databases and tables, all is empty

Image
 Sometimes, when you add new project (site) and configure Database connection, the panel with tables is empty. Even if connection is green and all is OK.  To fix this problem, you just need to add necessary schemes in Database configuration. Go to "Data Source Properties" window. In opened window choose Schemas tab and select "All schemas" checkbox, or another one what you need. So, after saving changes, you see all tables in Database panel.

Wordpress - How to install plugins not using ftp

 Just add to wp-config.php file the next string: define ( 'FS_METHOD' , 'direct' ); And also make sure, that your wp-content folder has full access to create new folders by Wordpress system. 

How to upgrade MediaWiki to 1.40 version

Link to page for web updating - your_site_url/mw-config/index.php If your version older then 1.35 version, then firstly update to 1.35 version . Only after that update to 1.40 version. Otherwise, it can brake you data in DB. If you see 500 error after updating - check permissions for folders: cache, vendor, skins, includes . For changing permission use command: chmod -R 777 ./cache If you see another errors on the pages, try to update extensions . To fix Logo after updating: need to change $wgLogo to $wgLogos. Before:  $wgLogo = "$wgScriptPath/resources/assets/logo.png"; After:  $wgLogos = [    '1x' => "$wgScriptPath/resources/assets/logo.png",    '1.5x' => "$wgScriptPath/resources/assets/logo.png",    '2x' => "$wgScriptPath/resources/assets/logo.png",    'svg' => "$wgScriptPath/resources/assets/logo.png" ];

Wordpress - miniOrange SSO using SAML 2.0 plugin - How to fix logout for FusionAuth

Reason issue : wrong NameID format < saml :NameID xmlns: saml ="urn:oasis:names:tc:SAML:2.0:assertion" > Fixing : use another NameID format < saml :NameID Format ="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress" > It is placed in Utilities.php file on 59 line, the function called createLogoutRequest . There is another issue - all text is encrypted via ASCII codes. Easy to solve this problem: just copy this text and paste into echo with double quotes.  For example: echo " \74\77\x78\x6d\x6c\40\166\x65\x72\163\151\x6f\x6e\x3d\42\x31\x2e\x30\x22 \x20\x65\x6e\x63\157\x64\x69\x6e\147\x3d\42\x55\124\x46\x2d\x38\x22\x3f\76 " ; On the page it will be: <?xml version="1.0" encoding="UTF-8"?> So, after that, you can decode all text what you need to replace LogoutRequest.

How to change Issuer (Entity ID) in Zoho Desk

Image
 If you already created Help Center and added and saved SAML configuration, you can't change Issuer (Entity ID). To change Issuer you need to click Disable button (in right up corner).  Notice: All other settings will be cleaned as well.

How to logout from Zoho Desk via SAML

Image
 As standard SAML request logout does not work, you can use OAuth logout URL . When you try to put standard SAML logout URL, you catch an error: "The SAML v2 logout request is missing the SAMLRequest parameter." As a work case, you can use standard AOuth logout URL. For example, you can get it from Fusion Auth, in "OAuth2 & OpenID Connect Integration details" tab.

How to upload Public Key in Zoho Desk for SAML authentication

Image
 When you try to upload standard Public Key to Zoho Desk with SAML authentication, you got an error. I resolved this issue by upload Certificate instead of Public Key. So honestly Zoho Desk is waiting for Certificate, not a Public Key, as it said on the SAML page ('Public Key (Provide Public Key in .txt or .pem extension file only)').

How to connect Fusion Auth to Zoho Desk via SAML

Image
Create new Application in Fusion Auth. Choose SAML tab. Enable SAML as Identite Provider.  The main thing - set Issuer 'zoho.eu' for any applications. Set 'Authorized redirect URLs' from Zoho 'Help Center SAML Response URL'. Left for Authentication request disabled 'Require signature'.