Wednesday, May 8, 2019

Mapping aditional attributes coming from SimpleSAML ADFS


For example , consider if ADFS SSO giving additional parameters like first name, surname, job title, etc., so how we map these additional attributes?
The 'simplesamlphp_auth' module gives us the option to map username, email, etc., from its user sync configuration page, buts it's not sufficient to map all fields. So here I would like to mention a way to map the additional fields.

There is a hook available for this.

hook_simplesamlphp_auth_user_attributes

I have a module named general in my code path. So I will write the above hook like below.

<?php
/**
 * Mapping of additional parameters/SAML attributes to Drupal user profile fields.
 * @param \Drupal\user\UserInterface $account
 *   The Drupal account/user
 * @param array $attributes
 *   The SimpleSAMLphp attributes for this account.
 */

function general_simplesamlphp_auth_user_attributes(\Drupal\user\UserInterface $account, $attributes) {
  $first_name = $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'];
  $sur_name = $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname'];
  $job_title = $attributes['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/jobtitle'];

  $account->set('field_first_name', $saml_first_name);
  $account->set('field_last_name', $sur_name); 
  $account->set('field_job_title', $job_title);
  return $account;

}
?>

SSO Implementation using SimpleSAML - in Drupal


A great tutorial here : https://www.chapterthree.com/blog/how-to-configure-simplesamlphp-for-drupal-8-on-acquia

After successfully setting the library and modules you have to send the metadata to the ADFS provider.
They will send you an XML adfs metadata.
You need to convert the XML metadata into PHP array, for that please go to the simplesaml configuration page. Which is normally http://www.examplesite.com/simplesaml
Go to Federation tab
Click the link labelled 'XML to SimpleSAMLphp metadata converter'. Which will ask you to log-in(if you are not logged in)
Paste the XML metadata/or upload the XML file here and click parse, you will get the required PHP array
Copy and paste the content in /simplesamlphp/metadata/saml20-idp-remote.php

Monday, February 25, 2019

Content export to CSV, JSON or XML

1. Download and install Views Data Export Module (https://www.drupal.org/project/views_data_export)

If you are using composer to install the module, then all the dependencies will automatically be downloaded.  Otherwise, follow the below steps

1.a. Download and install the CSV Serialization module(https://www.drupal.org/project/csv_serialization), this module requires a library League\Csv. So if you trying to install this module you may get below error message

CSV serialization requires the League\Csv library.


1.b To fix the above issue, download and install Ludwig module (https://www.drupal.org/project/ludwig) It provides a manual alternative to Composer.

After installing Ludwig, go to reports > packages.

Follow the instructions mentioned on that page. You may be instructed to download the library and copy to a specified folder. Do as per that then,

1.c Install CSV Serialization and Views Data export modules respectively.

After successful installation,

Follow the instruction mentioned here (https://www.drupal.org/node/1820452).

Wednesday, February 13, 2019

Drupal 8 Interview questions


  1. What are the custom entities? When and how it can be used?https://opensenselabs.com/blog/tech/how-create-custom-entity-drupal-8
  2. How to create a patch?
  3. Mysql rollback to flag
  4. What are cache tags in Drupal 8?
    https://www.drupal.org/docs/8/api/cache-api/cache-tags
  5. How to create a module using Drupal console?
  6. How to deploy code - Acquia
  7. Custom entities into the single table
  8. Why we need an interface?
    An interface allows unrelated classes to implement the same set of methods, regardless of their positions in the class inheritance hierarchy. An interface enables you to model multiple inheritances because a class can implement more than one interface whereas it can extend only one class.
  9. How to pass the interface variable in the constructor
  10. How to make a string to upper case in Twig
    To make a string in upper case use filter 'upper'
    {{ 'a string'|upper }}
  11. How to create a custom pipe.
    https://symfony.com/doc/current/templating/twig_extension.html
  12. What happens behind when the twig filter used?

Tuesday, February 12, 2019

How to ping an IP address from PHP script?

<?php

$ip_address =   "32.33.45.67"; //ip or web address
exec("ping -n 3 $ip_address", $output, $status);
print_r($output);

?>

The above script will try to ping the IP address 3 times and the response will be available in variable output. It is an array variable and result will look like below

Array
(
    [0] =>
    [1] => Pinging 32.33.45.67 with 32 bytes of data:
    [2] => Reply from 32.33.45.67: bytes=32 time<1ms TTL=128
    [3] => Reply from 32.33.45.67: bytes=32 time<1ms TTL=128
    [4] => Reply from 32.33.45.67: bytes=32 time<1ms TTL=128
    [5] =>
    [6] => Ping statistics for 32.33.45.67:
    [7] =>     Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),
    [8] => Approximate round trip times in milli-seconds:
    [9] =>     Minimum = 0ms, Maximum = 0ms, Average = 0ms
)

If you are running the above script from Linux and the output array results empty, then try

exec("ping -c 3 $ip_address", $output, $status);

You can also check the value of $status for the ping status. It will result in 0 if ping is successful.

Monday, February 11, 2019

Git workflow to merge 2 branches



1. Switch to the branch you want to merge another branch

git checkout branch1

2. Execute merge command, here we are going to mcommandnch2 into branch1

git merge branch1

3. If conflict occures, manually resolve the conflict and add/stage the resolved files by executing

git add <file1 file2 ...>

4. Commit the merges.

git commit -m "message"

5. Push the changes.

git push origin branch1

Saturday, February 2, 2019

How to create an empty git branch


Sometimes we may want to create a different project (storing some documentation or some other files)inside our available repository. We can achieve this by creating a new branch by using normal "git checkout <branch-name>" command. But the correct way is

git checkout --orphan <branchname>


so that a new branch will be created inside the repo and automatically switched to the same. The new branch doesn't have a parent branch. We may need to execute the below commands to clear the cache and leftover files.

git rm --cached -r
git reset --hard


Once you created the orphan branch and after adding your new files, commit and push it. So that the branch will be available to all team members.

Tuesday, January 29, 2019

How to create a subsite in Drupal


  1. Create a subdirectory inside sites folder of your Drupal installation, it will be inside docroot folder.
    Drupal-Multisite Directory Structure
  2. Create a virtual host. You can follow any of the steps from traditional way to executing a bash script. I recommend executing a bash script so that you don't need to go through all steps everytime.
  3. Make a copy of /docroot/sites/example.sites.php called /docroot/sites/sites.php
  4. Add the below line of code inside the sites.php.
    $sites['sub-site-address.domain'] = 'subsite';
  5. Check the newly created subsite from your browser 'sub-site-address.domain' and install the site.
  6. Create folders for modules, themes, libraries etc., and add your custom theme or module specific to this newly created site if you wish.

Friday, January 25, 2019

Steps involved from request to response of website

When you first type in an address, the browser will look up the hostname in DNS, if it is not already in the browser cache.
Then the browser sends an HTTP GET request to the remote server.
What happens on the server is really up to the server; but it should respond back with an HTTP response, that includes headers, which perhaps describe the content to the browser and how long it is allowed to be cached. The response might be a redirect, in which case the browser will send another request to the redirected page.
Obviously, server response time will be one of the critical points for perceived performance, but there are many other things to it.
When a response is returned from the server, the browser will do a few things. First, it will parse the HTML returned, and create it's DOM (Document Object Model) from that. Then it will run any startup Javascript on the page; before the page is ready to be displayed in the browser. Remember, that if the page contains any resources such as external stylesheets, scripts, images and so on, the browser will have to download those, before it can display the page. Each resource is a separate HTTP get, and there is some latency time involved here. Therefore, one thing that in some cases can greatly reduce load times is to use as few external resources as possible, and make sure they are cached on the client (so the browser don't have to fetch them for each pageview).
To summarize, to optimize performance for a web page, you want to look at, as a minimum:
  • Server response time
  • Bandwidth /content transfer time.
  • Make sure you have a small and simple DOM (especially if you need to support IE6).
  • Make sure you understand client-side caching and the settings you need to set on the server.
  • Make sure you make the client download as little data as possible. Consider GZipping resources and perhaps dynamic content also (dependent on your situation).
  • Make sure you don't have any CPU intensive javascript on Page load.
Ref: https://stackoverflow.com/questions/2896199/what-are-the-steps-involved-from-entering-a-web-site-address-to-the-page-being-d

Tuesday, January 22, 2019

PHP Quick Help

Static late binding

As of version 5.3, PHP introduced a new feature called PHP static late binding. Basically, instead of using the self, you use the static keyword that references to the exact class that was called at runtime.

Traits

Introduced in PHP 5.4.0.

Inheritance makes the code very tightly coupled therefore makes the code hard to maintain.

To overcome this problem, as of version 5.4.0,  PHP introduced a new unit of code reuse named trait. Traits allow you to reuse a set of methods freely in many different classes that do not need to be in the same class hierarchy.

The trait is similar to a class but it is only for grouping methods in a fine-grained and consistent way. It is not allowed to instantiate a trait on its own.

To use a trait in a class, you use the use keyword. All the trait’s methods are available in the class where it is used. Calling a method of a trait is similar to calling an instance method.

Abstract Class

Can not be instantiated. Should contain at least one abstract method.

Shallow Copy & Deep Copy


$p2 = $p1; // $p2 & $p1 objects will point to same object, reference change only.


$p2 = clone $p1; //Creates a new object from $p1 object

Function & Method

Both are same, a set of statements grouped by a name. So that they can execute wherever we want by using that name. The only difference is that a method is written inside a class, so it's always part of the class and can be called by using the object of the same class. Functions are written outside the class or normally in a plain PHP file.

Magic Methods


Magic methods are nothing but class member functions that are automatically executed based on some other actions.


__set(), __get(), __construct(), __destruct(), __call(), __clone(), __toString(), __autoload()  are examples of magic methods.


__set() & __get() are executed when an object tries to access(read / write) a private or non existent property.



__call() is executed when an object tries to call a nonexistent method.

Interface


An interface is nothing but a class with some skeleton member functions(methods) which will help the programmers to implement the same methods in a different class which are unrelated. So this will allows you to model multiple inheritances so that a class can implement multiple interfaces whereas it can extend only one class.

Why should we use PHP interfaces?
There are several reasons that we should use interface in our PHP object-oriented programming:

By implement an interface, the caller of the object need to care only about the object’s interface, not implementations of the object’s methods. Therefore the implementations can be changed without affecting the caller of the interface.
An interface allows unrelated classes to implement the same set of methods, regardless of their positions in the class inheritance hierarchy.
An interface enables you to model multiple inheritances because a class can implement more than one interface whereas it can extend only one class.

Thursday, January 17, 2019

Some useful Linux commands

Copy files from one folder to another

The below will command will copy all files inside the source folder to the destination folder.

cp path/to/source/* path/to/destination

This will not copy sub-folders and files in it.


cp -r path/to/source/* path/to/destination

or

cp -a path/to/source/* path/to/destination

This will recursively copy folders, sub-folders, and files in it.

Rename a folder


MV path/to/old path/to/new

Change read/write/access/owner/group permissions of a folder


CHMOD [XYZ] path/to/folder

X - Will affect Owner permissions
Y - Will affect Group permissions
Z - Will affect Others permissions

[X, Y & Z] will be calculated from below

0 – no permission
1 – execute
2 – write
3 – write and execute
4 – read
5 – read and execute
6 – read and write
7 – read, write, and execute

For example, if we want to give Read, write and execute permission to Owner, Read & Execute permissions to Group and read permission to Others, we have to execute the command like below

CHMOD 754 path/to/folder

Change ownership of a folder or file with current user


sudo chown -R $USER /path/to/folder

Tuesday, January 15, 2019

Show previous chapter, next chapter navigation in book page of Drupal 8.

Q: I want to show a navigation to previous chapter & next chapter in my book detail page(node view). I'll explain the scenario: I have a parent book and multiple child pages, each may have children up-to level n. I'm showing the level 1(depth 2) pages in a single view(details page) and the children in same page. Here comes the navigation part. I want to show a navigation to previous and next chapters in the Book details page.

A: After creation of the Book page details page, create a view as per the below pictures

1.Create a View-Give name and select the content type. Check 'Create a Block'.

2. As per the scenario I want to see Level 2 book pages(siblings of current page), so I set Depth is equal to 2 under Filter criteria. Sort criteria set us Depth's Ascending order.
3. Created a contextual filter: Node ID and set its default value from the URL(as we are viewing the node view page)
4. Under more we have to check the exclude option so that the result will exclude the current book page.

5.Save the view. See I created two blocks , one for previous link and one for next link. 
By visiting structure > Block Layout you are able to place the newly created blocks.

 6. Now we have to create a module to apply some query conditions to the view. Simply create a module and paste the below code in your module's .module file and enable it.

<?php
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
/**
 * To get the next and previous chapters
 *
 * @param ViewExecutable $view
 * @param QueryPluginBase $query
 * @return void
 */
function chapter_navigation_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {   
  
  $node = \Drupal::routeMatch()->getParameter('node');
  
  if ($view->id() == 'chapter_navigation' && $node) {
    $operator = $view->getDisplay()->display['id'] == 'next_chapter' ? '>=' : '<=';
    foreach ($query->where as &$condition_group) {
      array_push($condition_group['conditions'], [
        'field' => 'book.weight '.$operator.' ' . $node->book['weight'],
        'value' => [],
        'operator' => 'formula',

      ]);

    }   
 
  }

}