Snippets Collections
//Page Slug Body Class
function add_slug_body_class( $classes ) {
global $post;
if ( isset( $post ) ) {
$classes[] = $post->post_type . '-' . $post->post_name;
}
return $classes;
}
add_filter( 'body_class', 'add_slug_body_class' );
echo var_export($GLOBALS['post'], TRUE);
<pre>
  <?php
    $post_types = get_post_types();
    print_r($post_types);
  ?>
</pre>
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
<?php

// get the value of image_advanced type of custom field for the current taxonomy term 
$clients_gallery = rwmb_meta( 'clients_gallery', ['object_type' => 'term'], get_queried_object_id() );
<?php
// Disable editor for OXYGEN pages
add_action('init', 'my_remove_editor_from_post_type');
function my_remove_editor_from_post_type() {
remove_post_type_support( 'page', 'editor' );
}
// Fully Disable Gutenberg editor.
add_filter('use_block_editor_for_post_type', '__return_false', 10);
// Don't load Gutenberg-related stylesheets.
add_action( 'wp_enqueue_scripts', 'remove_block_css', 100 );
function remove_block_css() {
wp_dequeue_style( 'wp-block-library' ); // WordPress core
wp_dequeue_style( 'wp-block-library-theme' ); // WordPress core
wp_dequeue_style( 'wc-block-style' ); // WooCommerce
wp_dequeue_style( 'storefront-gutenberg-blocks' ); // Storefront theme
}
<?php
    echo do_shortcode(rwmb_get_value('slider_shortcode'));
?>
<?php


add_action( 'woocommerce_before_cart', 'auto_select_free_shipping_by_default' );
function auto_select_free_shipping_by_default() {
    if ( isset(WC()->session) && ! WC()->session->has_session() )
        WC()->session->set_customer_session_cookie( true );

    // Check if "free shipping" is already set
    if ( strpos( WC()->session->get('chosen_shipping_methods')[0], 'woocommerce_flatrate_perpostcode' ) !== false )
        return;

    // Loop through shipping methods
    foreach( WC()->session->get('shipping_for_package_0')['rates'] as $key => $rate ){
        if( $rate->method_id === 'shipping_method_0_woocommerce_flatrate_perpostcode' ){
            // Set "Free shipping" method
            WC()->session->set( 'chosen_shipping_methods', array($rate->id) );
            return;
        }
    }
}

?>
<?php

add_filter( 'woocommerce_checkout_fields', 'xa_remove_billing_checkout_fields' );
function xa_remove_billing_checkout_fields( $fields ) {
    // change below for the method
    $shipping_method ='local_pickup:1'; 
    // change below for the list of fields
    $hide_fields = array( 'billing_address_1', 'billing_address_2', 'billing_city', 'billing_state', 'billing_postcode' );

    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    // uncomment below line and reload checkout page to check current $chosen_methods
     print_r($chosen_methods);
    $chosen_shipping = $chosen_methods[0];

    foreach($hide_fields as $field ) {
        if ($chosen_shipping == $shipping_method) {
            $fields['billing'][$field]['required'] = false;
            $fields['billing'][$field]['class'][] = 'hide';
        }
        $fields['billing'][$field]['class'][] = 'billing-dynamic';
    }

    return $fields;
}

add_action( 'wp_footer', 'cart_update_script', 999 );
function cart_update_script() {
    if (is_checkout()) :
    ?>
    <style>
        .hide {display: none!important;}
    </style>
    <script>
        jQuery( function( $ ) {

            // woocommerce_params is required to continue, ensure the object exists
            if ( typeof woocommerce_params === 'undefined' ) {
                return false;
            }

            $(document).on( 'change', '#shipping_method input[type="radio"]', function() {
                // change local_pickup:1 accordingly 
                $('.billing-dynamic').toggleClass('hide', this.value == 'local_pickup:1');
            });
        });
    </script>
    <?php
    endif;
}
function mytheme_custom_excerpt_length( $length ) {
    return 15;
}
add_filter( 'excerpt_length', 'mytheme_custom_excerpt_length', 999 );
// set current category
$categories = get_the_category();
$category = $categories[0];
$cat_ID = $category->cat_ID;    

// get next post link
$next_post = get_adjacent_post( true, '', false );
if( $next_post ) {
    echo '<a href="' . get_permalink( $next_post->ID ) . '">Next post</a>';
} else {
    $first = new WP_Query( array(
        'post_type' => 'project',
        'post_status' => 'publish',
        'posts_per_page' => 1,
        'order' => 'ASC',
        'cat' => $cat_ID
    ));

    $first->the_post();
    echo '<a href="' . get_permalink() . '">Next post</a>';
    wp_reset_query();
};

// show prev post link
$prev_post = get_adjacent_post( true, '', true );
if( $prev_post ) {
    echo '<a href="' . get_permalink( $prev_post->ID ) . '">Prev post</a>';
} else {
    $last = new WP_Query( array(
        'post_type' => 'project',
        'post_status' => 'publish',
        'posts_per_page' => 1,
        'order' => 'DESC',
        'cat' => $cat_ID
    ));

    $last->the_post();
    echo '<a href="' . get_permalink() . '">Prev post</a>';
    wp_reset_query();
};
<?php 

/*
Plugin Name:  Remove Archive Prefix
Description:  Load custom fonts and inject to Oxygen
Author:       <a href="https://dplugins.com/">dPlugins</a>
Version:      1.0.1
Description:  https://dplugins.com/code_snippets/remove-archive-prefix/
Copyright:    © 2021, dPlugins
Version History:
2021-07-10  //  1.0.1  //  Fixed bug with Oxygen to load SVG Icons
2021-04-20  //  1.0.0  //  Initial Release
*/

/**
 * Add a span around the title prefix so that the prefix can be hidden with CSS
 * if desired.
 * Note that this will only work with LTR languages.
 *
 * @param string $title Archive title.
 * @return string Archive title with inserted span around prefix.
 */
function mk_hide_the_archive_title( $title ) {

    // Skip if the site isn't LTR, this is visual, not functional.
    // Should try to work out an elegant solution that works for both directions.
    if ( is_rtl() || !is_archive() ) {
        return $title;
    }

    // Split the title into parts so we can wrap them with spans.
    $title_parts = explode( ': ', $title, 2 );

    // Glue it back together again.
    if ( ! empty( $title_parts[1] ) ) {
        $title = wp_kses(
            $title_parts[1],
            array(
                'span' => array(
                    'class' => array(),
                ),
            )
        );
        $title = '<span class="screen-reader-text">' . esc_html( $title_parts[0] ) . ': </span>' . $title;
    }

    return $title;

}

add_filter( 'get_the_archive_title', 'mk_hide_the_archive_title' );

?>
<?php

add_action( 'init', 'stop_heartbeat', 1 );
 
function stop_heartbeat() {
    wp_deregister_script('heartbeat');
}

?>
<?php
function adminStylesCss() {
echo '
<style>

/* Admin BG color */
.wp-admin {
  background-color: #262626;
}

/* Revert colors and bring back links colors */
.wp-admin #wpbody {
  filter: invert(0.85) hue-rotate(185deg);
}

/* Bring back colors to the images */
.wp-admin #wpbody img {
  filter: invert(0.85) hue-rotate(-185deg);
  background: white;
}

/* Gutenberg bring it back */
.block-editor-page #wpbody {
  filter: unset;
}
/* Gutenberg topbar */
.block-editor-page .interface-interface-skeleton__header {
  filter: invert(0.85) hue-rotate(185deg);
}
.block-editor-page .is-primary {
  color: black !important;
}

/* Gutenberg sidebars */
.block-editor-page .interface-interface-skeleton__sidebar,
.block-editor-page .interface-interface-skeleton__secondary-sidebar {
  filter: invert(0.85) hue-rotate(185deg);
}

/* Gutenberg Content - Manual colors */
.block-editor-page .editor-styles-wrapper {
  color: lightgray;
  background: #262626;
}

/* Gutenberg Links */
.block-editor-page .editor-styles-wrapper a {
  filter: invert(0.85) hue-rotate(185deg);
}

/* Gutenberg Metaboxes - Bellow content */
.block-editor-page .edit-post-layout__metaboxes {
  border-top: 0px;
  background-color: #262626;
}

</style>';

}
add_action('admin_head', 'adminStylesCss');

?>
<?php function custom_content_after_body_open_tag() { ?>

    <!--  Your custom code goes here. -->
    
    <div>My Custom Content</div>
    
    <!--  Your custom code goes here. -->

<?php 
    } add_action('ct_before_builder', 'custom_content_after_body_open_tag');
?>
add_filter( 'comment_form_default_fields', 'crb_custom_fields', 10, 1 );

function crb_custom_fields( $fields ) {

$commenter = wp_get_current_commenter();
$req = get_option( 'require_name_email' );
$aria_req = ( $req ? " aria-required='true'" : '' );

$fields =  array(
    'author' =>
    '<p class="comment-form-author"><label for="author">' . __( 'Name', 'crb' ) .
    ( $req ? '<span class="required">*</span>' : '' ) . '</label>' .
    '<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) .
    '" size="30"' . $aria_req . ' /></p>',

    'email' =>
    '<p class="comment-form-email"><label for="email">' . __( 'Email', 'crb' ) .
    ( $req ? '<span class="required">*</span>' : '' ) . '</label>' .
    '<input id="email" name="email" type="text" value="' . esc_attr(  $commenter['comment_author_email'] ) .
    '" size="30"' . $aria_req . ' /></p>',

    'url' =>
    '<p class="comment-form-url"><label for="url">' . __( 'Website', 'crb' ) . '</label>' .
    '<input id="url" name="url" type="text" value="' . esc_attr( $commenter['comment_author_url'] ) .
    '" size="30" /></p>',

    'comment_field' =>  '<p class="field comment-form-comment"><label for="comment" class="hidden">' . _x( 'Comment', 'noun' ) .
    '</label><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true">' .
    '</textarea></p>',
);

return $custom_fields;

}
function dotirating_function( $attr ) {
91
  $args = shortcode_atts( array('id' => '',), $attr );
92
    
93
    $product_id = $args['id'];
94
    $product = new WC_product($product_id);
95
    $attachment_ids = $product->get_gallery_image_ids();
96
    
97
    if ( ! empty($attachment_ids) ) :
98
    return wp_get_attachment_image($attachment_ids[0], 'large');
99
endif;
100
    
101
}
102
​
103
add_shortcode('dotirating', 'dotirating_function');
<?php




class Dbtable {


function __construct() {
   // $this->getId();
    add_action( 'admin_notices', array( $this, 'my_update_notice'));
    add_shortcode( 'mydbtable', array( $this, 'showmytable'));

}


public function showmytable() {

    global $wpdb;
    $result = $wpdb->get_results ( "SELECT * FROM khdata_devis  ORDER BY id" );
    ob_start();
//$code = 'Hello World';



    $output = '<table>
    <tr>
      <th> name </th>
      <th>email</th>
      <th>city</th>
    </tr>';

    foreach ( $result as $print )   {
    $output .='<tr>
      <td>"'.$print->city.'"</td>
      <td>"'.$print->email.'"</td>
      <td>21</td>
    </tr>';}

    $output .='</table>';
    
  



return $output;

ob_get_clean();
}


function my_update_notice() {
    global $wpdb;
    ?>
    <div class="updated notice">
        <p><?php _e( "name of Database $wpdb->dbname", 'my_plugin_textdomain' ); ?></p>
    </div>
    <?php
}

}
function func_update_post_name( $post_id, $post ){
 
    if ( 'post-type-slug' == $post->post_type ) {
 
        remove_action( 'save_post', 'func_update_post_name',30,2 );
 
        // update the post slug
        wp_update_post( array(
            'ID' => $post_id,
            'post_name' => uniqid() 
        ));
 
       add_action( 'save_post', 'func_update_post_name', 30, 2 );
    }
}
add_action( 'save_post', 'func_update_post_name', 30, 2 );
<?php
	echo 'yahya';
?>
//hide username in comments
function remove_comment_author_class($classes)
{
	foreach ($classes as $key => $class) {
		if (strstr($class, "comment-author-")) {
			unset($classes[$key]);
		}
	}
	return $classes;
}
add_filter('comment_class', 'remove_comment_author_class');
add_action( 'admin_notices', 'bbloomer_products_no_weight_admin' );

function bbloomer_products_no_weight_admin(){
    global $pagenow, $typenow;
    if ( 'edit.php' === $pagenow && 'product' === $typenow ) {
		echo '<div class="notice notice-warning is-dismissible"><h3>Products with no weight</h3><ul>';
		$args = array(
			'status' => 'publish',
			'visibility' => 'visible',
			'limit' => -1
		);
		$products = wc_get_products( $args );
		foreach ( $products as $product ) {
			if ( ! $product->get_weight() ) {
				echo '<li><a href="' . esc_url( get_edit_post_link( $product->get_id() ) ) . '">' . $product->get_name() . '</a></li>';
			}
		}
		echo '</ul></div>';
    }
}
Gegasoft uses the following name conventions for laravel
=============================================================
Variables	=>	camelCase	=>	$articlesWithAuthor
Collection Variable	=>	descriptive, plural	=>	$activeUsers = User::active()->get()
Object Variable	=>	descriptive, singular	=>	$activeUser = User::active()->first()
View	=>	snake_case	=>	show_filtered.blade.php
Controllers	=>	singular, ProperCase	=>	ArticleController
Model Name	=>	singular, ProperCase	=>	User, FollowingRequest
Model attribute/property	=>	snake_case	=>	$model->created_at
Method	=>	camelCase	=>	getAll
Method in resource controller	=>	table	=>	store
Method in test class	=>	camelCase	=>	testGuestCannotSeeArticle
hasOne/belongsTo relation	=>	singular	=>	articleComment
Other relations	=>	plural	=>	articleComments
Table Name =>	plural	=>	article_comments
Table column	=>	snake_case without model name	=>	meta_title
Route	=>	plural	=>	articles/1
Named route	=>	snake_case with dot notation	=>	users.show_active
Primary key	=>	-	=>	id
Foreign key	=>	singular model name with _id suffix	=>	article_id
Pivot table	=>	singular model names in alphabetical order	=>	article_user
Migration	=>	-	=>	2017_01_01_000000_create_articles_table
Config and language files index	=>	snake_case	=>	articles_enabled
Config	=>	snake_case	=>	google_calendar.php
Contract (interface)	=>	adjective or noun	=>	Authenticatable
Trait	=>	adjective	=>	Notifiable
{{ $users->withQueryString()->links() }}
<?php
/*
  Plugin Name: WP Like button
  Description: WP Like button allows you to add Facebook like button to your wordpress blog.
  Author: <a href="http://crudlab.com/">CRUDLab</a>
  Version: 1.6.9
 */
$CLFBLBPath = plugin_dir_path(__FILE__);

require_once $CLFBLBPath . 'CLLBtnSettings.php';

class CLFBLBtn {

    private $CLLBtnSettings = null;
    private $table_name = null;
    public static $table_name_s = 'fblb';
    private $db_version = '7';
    private $menuSlug = "facebook-like-button";
    private $settingsData = null;

    public function __construct() {

        register_activation_hook(__FILE__, array($this, 'fblb_install'));
        register_uninstall_hook(__FILE__, array('CLFBLBtn', 'fblb_uninstall_hook'));

        add_action('admin_menu', array($this, 'fblb_plugin_setup_menu'));
        $this->CLLBtnSettings = new CLLBtnSettings($this);
        $this->menuSlug = 'facebook-like-button';
        global $wpdb;
        $this->table_name = $wpdb->prefix . self::$table_name_s;
        $this->settingsData = $wpdb->get_row("SELECT * FROM $this->table_name WHERE id = 1");

        $plugin = plugin_basename(__FILE__);
        add_filter("plugin_action_links_$plugin", array($this, 'settingsLink'));

        add_filter('wp_head', array($this, 'fblb_header'));
        add_filter('the_content', array($this, 'fb_like_button'));
        //add_filter('the_excerpt', 'fb_like_button');
        add_shortcode('fblike', array($this, 'fb_like_button'));
    }

    function settingsLink($links) {
        $settings_link = '<a href="admin.php?page=' . $this->menuSlug . '">Settings</a>';
        array_unshift($links, $settings_link);
        return $links;
    }

    public static function getTableName() {
        global $wpdb;
        return $wpdb->prefix . self::$table_name_s;
    }

    public function getTable_name() {
        return $this->table_name;
    }

    public function getDb_version() {
        return $this->db_version;
    }

    public function setTable_name($table_name) {
        $this->table_name = $table_name;
    }

    public function setDb_version($db_version) {
        $this->db_version = $db_version;
    }

    public function getMenuSlug() {
        return $this->menuSlug;
    }

    public function setMenuSlug($menuSlug) {
        $this->menuSlug = $menuSlug;
    }

    public function getSettingsData() {
        return $this->settingsData;
    }

    public function reloadDBData() {
        global $wpdb;
        return $this->settingsData = $wpdb->get_row("SELECT * FROM $this->table_name WHERE id = 1");
    }
    
    function fblb_header() {
        if ($this->getSettingsData()->status != 0) {
            $fb_app_id = $this->getSettingsData()->fb_app_id;
            $fb_app_default_image = $this->getSettingsData()->default_image;
            $fb_app_admin = explode(",", $this->getSettingsData()->fb_app_admin);
            echo '<meta property="fb:app_id" content="' . $fb_app_id . '">';
            if ($fb_app_default_image != "" && $fb_app_default_image != null) {
                echo '<meta property="og:image" content="' . $fb_app_default_image . '" />';
            }
            foreach ($fb_app_admin as $admin_id) {
                echo '<meta property="fb:admins" content="' . $admin_id . '">';
            }
            ?>
            <div id="fb-root"></div>
            <script>(function (d, s, id) {
                    var js, fjs = d.getElementsByTagName(s)[0];
                    if (d.getElementById(id))
                        return;
                    js = d.createElement(s);
                    js.id = id;
                    js.src = "//connect.facebook.net/<?php echo $this->getSettingsData()->language ?>/sdk.js#xfbml=1&version=v2.0";
                    fjs.parentNode.insertBefore(js, fjs);
                }(document, 'script', 'facebook-jssdk'));</script>
            <?php
        }
    }

    function fblb_plugin_setup_menu() {
        if ($this->getSettingsData()->status == 0) {
            add_menu_page('WP like button', 'WP like button <span id="fblb_circ" class="update-plugins count-1" style="background:#F00"><span class="plugin-count">&nbsp&nbsp</span></span>', 'manage_options', $this->menuSlug, array($this, 'admin_settings'), plugins_url("/images/ico.png", __FILE__));
        } else {
            add_menu_page('WP like button', 'WP like button <span id="fblb_circ" class="update-plugins count-1" style="background:#0F0"><span class="plugin-count">&nbsp&nbsp</span></span>', 'manage_options', $this->menuSlug, array($this, 'admin_settings'), plugins_url("/images/ico.png", __FILE__));
        }
    }

    function admin_settings() {
        $this->CLLBtnSettings->registerJSCSS();
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            if ($this->CLLBtnSettings->validateData()) {
                $this->CLLBtnSettings->saveData();
            }
        }
        $this->CLLBtnSettings->renderPage();
    }

    function fblb_install() {
        global $wpdb;
        global $wpfblike_db_version;
        $table_name = $wpdb->prefix . 'fblb';
        $charset_collate = $wpdb->get_charset_collate();
        $wpdb->query("DROP TABLE IF EXISTS $table_name");
        // status: 1=active, 0 unactive
        // display: 1=all other page, 2= home page, 3=all pages
        $sql = "CREATE TABLE IF NOT EXISTS $this->table_name (
                    id mediumint(9) NOT NULL AUTO_INCREMENT,
                    display int, 
                    width int,
                    beforeafter varchar (25),
                    except_ids varchar(255),
                    where_like varchar (50),
                    layout varchar (50),
                    action varchar (50),
                    color varchar (50),
                    btn_size varchar (50),
                    position varchar (50),
                    language varchar (50),
                    fb_app_id varchar (100),
                    fb_app_admin varchar (100),
                    url varchar (255),
                    default_image varchar (500),
                    status int, 
                    mobile int,
                    kid int,
                    user_id int,
                    active int,
                    share int,
                    faces int,
                    created datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
                    last_modified datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
                    UNIQUE KEY id (id)
            ) $charset_collate;";

        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        dbDelta($sql);
        add_option('wpfblike_db_version', $this->db_version);
        update_option('wpfblike_db_version', $this->db_version);
        if(get_option('crudlab_fblb_install') == false){
            add_option('crudlab_fblb_install', strtotime( "now" ));
        }else{
            update_option('crudlab_fblb_install', strtotime( "now" ));
        }
        $myrows = $wpdb->get_results("SELECT * FROM $this->table_name WHERE id = 1");
        if ($myrows == NULL) {
            $wpdb->insert($this->table_name, array(
                'created' => current_time('mysql'),
                'last_modified' => current_time('mysql'),
                'status' => 1,
                'display' => 3,
                'width' => 65,
                'except_ids' => '',
                'user_id' => $user_id,
                'active' => 1,
                'share' => 1,
                'faces' => 1,
                'mobile' => 1,
                'kid' => 0,
                'position' => 'center',
                'beforeafter' => 'before',
                'where_like' => 'eachpage',
                'layout' => 'box_count',
                'action' => 'like',
                'color' => 'light',
                'btn_size' => 'small',
                'language' => 'en_US',
                'url' => ''
            ));
        }
    }    

    public static function fblb_uninstall_hook() {
        global $wpdb;
        $tbl = self::getTableName();
        $wpdb->query("DROP TABLE IF EXISTS $tbl");
    }
    
    public function fb_like_button($content = NULL) {
        $post_id = get_the_ID();
        $settings = $this->getSettingsData();

        $beforeafter = $settings->beforeafter;
        $where_like = $settings->where_like;
        $status = $settings->status;
        $layout = $settings->layout;
        $action = $settings->action;
        $color = $settings->color;
        $btn_size = $settings->btn_size;
        $display = $settings->display;
        $except_ids = $settings->except_ids;
        $language = $settings->language;
        $url = $settings->url;
        $mobile = $settings->mobile;
        $kid = $settings->kid;
        $width = $settings->width;
        $str = $content;
        $share = $settings->share;
        $faces = $settings->faces;
        $position = $settings->position;
        if ($share == 1) {
            $share = 'true';
        } else {
            $share = 'false';
        }
        if ($faces == 1) {
            $faces = 'true';
        } else {
            $faces = 'false';
        }
        if ($kid == 1) {
            $kid = 'true';
        } else {
            $kid = 'false';
        }
        if ($where_like == 'eachpage') {
            $actual_link = get_permalink();
        } else if ($where_like == 'entiresite') {
            $actual_link = get_site_url();
        } else {
            $actual_link = $url;
        }
        if (!wp_is_mobile()) {
            $fb = '<style>.fb_iframe_widget span{width:460px !important;} .fb_iframe_widget iframe {margin: 0 !important;}        .fb_edge_comment_widget { display: none !important; }</style><div style="width:100%; text-align:' . $position . '"><div class="fb-like" style="width:' . $width . 'px; overflow: hidden !important; " data-href="' . $actual_link . '" data-size="' . $btn_size . '" data-colorscheme="' . $color . '" data-width="' . $width . '" data-layout="' . $layout . '" data-action="' . $action . '" data-show-faces="' . $faces . '" data-share="' . $share . '" kid_directed_site="' . $kid . '"></div></div>';
        } else if ($mobile && wp_is_mobile()) {
            $fb = '<style>.fb-like {overflow: hidden !important;}</style><div style="width:100%; text-align:' . $position . '"><div class="fb-like" style="width:' . $width . 'px" data-href="' . $actual_link . '" data-colorscheme="' . $color . '" data-size="' . $btn_size . '" data-width="' . $width . '" data-layout="' . $layout . '" data-action="' . $action . '" data-show-faces="' . $faces . '" data-share="' . $share . '" kid_directed_site="' . $kid . '"></div></div>
            <br>';
        }
        $width = $settings->width . 'px';
        if ($status == 0) {
            $str = $content;
        } else {
            if ($content == NULL) {
                $str = $fb;
            }
            if ($display & 2) {
                if (is_page() && !is_front_page()) {
                    if ($beforeafter == 'before') {
                        $str = $fb . $content;
                    } else {
                        $str = $content . $fb;
                    }
                }
            }
            if ($display & 1) {
                if (is_front_page()) {
                    if ($beforeafter == 'before') {
                        $str = $fb . $content;
                    } else {
                        $str = $content . $fb;
                    }
                }
            }
            if ($display & 4) {
                if (is_single()) {
                    if ($beforeafter == 'before') {
                        $str = $fb . $content;
                    } else {
                        $str = $content . $fb;
                    }
                }
            }
            if ($display & 16) {
                if (is_archive()) {
                    if ($beforeafter == 'before') {
                        $str = $fb . $content;
                    } else {
                        $str = $content . $fb;
                    }
                }
            }
        }
        $except_check = true;
        if ($display & 8) {
            @$expect_ids_arrays = explode(',', $except_ids);
            foreach ($expect_ids_arrays as $id) {
                if (trim($id) == $post_id) {
                    $except_check = false;
                }
            }
        }
        if ($except_check) {
            return $str;
        } else {
            return $content;
        }
    }
}

global $wpfblbtn;
$wpfblbtn = new CLFBLBtn();

function fb_like_button() {
    global $wpfblbtn;
    echo $wpfblbtn->fb_like_button();
}
/* Mime Types Support */
add_filter('upload_mimes', 'custom_mime_types', 999999);

function custom_mime_types($mimes) {
  $mimes['otf'] = 'application/x-font-opentype';
  $mimes['woff'] = 'application/font-woff';
  $mimes['woff2'] = 'application/font-woff2';
  return $mimes;
}

/* Custom Font Types Support */
add_filter('et_pb_supported_font_formats', 'custom_font_formats', 1);

function custom_font_formats() { 
return array('otf', 'woff', 'woff2');
}
//maps.googleapis.com
//maps.gstatic.com
//fonts.googleapis.com
//fonts.gstatic.com
//use.fontawesome.com
//ajax.googleapis.com
//apis.google.com
//google-analytics.com
//www.google-analytics.com
//ssl.google-analytics.com
//www.googletagmanager.com
//www.googletagservices.com
//googleads.g.doubleclick.net
//adservice.google.com
//pagead2.googlesyndication.com
//tpc.googlesyndication.com
//youtube.com
//i.ytimg.com
//player.vimeo.com
//api.pinterest.com
//assets.pinterest.com
//connect.facebook.net
//platform.twitter.com
//syndication.twitter.com
//platform.instagram.com
//referrer.disqus.com
//c.disquscdn.com
//cdnjs.cloudflare.com
//cdn.ampproject.org
//pixel.wp.com
//disqus.com
//s.gravatar.com
//0.gravatar.com
//2.gravatar.com
//1.gravatar.com
//sitename.disqus.com
//s7.addthis.com
//platform.linkedin.com
//w.sharethis.com
//s0.wp.com
//s1.wp.com
//s2.wp.com
//stats.wp.com
//ajax.microsoft.com
//ajax.aspnetcdn.com
//s3.amazonaws.com
//code.jquery.com
//stackpath.bootstrapcdn.com
//github.githubassets.com
//ad.doubleclick.net
//stats.g.doubleclick.net
//cm.g.doubleclick.net
//stats.buysellads.com
//s3.buysellads.com
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js" integrity="sha512-jNDtFf7qgU0eH/+Z42FG4fw3w7DM/9zbgNPe3wfJlCylVDTT3IgKW5r92Vy9IHa6U50vyMz5gRByIu4YIXFtaQ==" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf-8"> //lazyload 기능 추가
    $(document).ready(function(){
        $("img.lazy").lazyload({
            threshold : 10,
            effect : "fadeIn",
        });
    });
</script>
</head>
<script src="<?php echo G5_JS_URL; ?>/jquery.lazyload.min.js"></script>
<script type="text/javascript" charset="utf-8"> //lazyload 기능 추가
    $(document).ready(function(){
        $("img.lazy").lazyload({
            threshold : 10,
            effect : "fadeIn",
        });
    });
</script>
// will add this code in web.php page 
Route::get("/mail",function(){
    Mail::raw("thank you", function($messsage){
        $messsage->to("name@gmail.com")->subject("contact with me");
    });
});

// will add this code at env file 
MAIL_MAILER=log

// to see the result you should go to www.myapp.com/mail then go to laravel.log file you will find the result there 
<?php
/**
 * Expand Divi Setup
 * Setup plugin files
 *
 * @package  ExpandDiviSetup
 */

// exit when accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class ExpandDiviSetup {
	public $options;

	/**
	 * constructor
	 */
	function __construct() {
		$this->options = get_option( 'expand_divi' );
	}

	/**
	 * register plugin setup functions
	 *
	 * @return void
	 */
	function expand_divi_register() {
		add_filter( "plugin_action_links_expand-divi/expand-divi.php", array( $this, 'expand_divi_add_settings_link' ) );

		add_filter( 'user_contactmethods', array( $this, 'expand_divi_profile_social_fields') );

		add_action( 'admin_enqueue_scripts', array( $this, 'expand_divi_enqueue_admin_scripts' ) );

		add_action( 'wp_enqueue_scripts', array( $this, 'expand_divi_enqueue_frontend_scripts' ) );

		// require the dashbaord/menu files 
		require_once( EXPAND_DIVI_PATH . 'inc/dashboard/dashboard.php' );
		
		// require widgets classes
		require_once( EXPAND_DIVI_PATH . 'inc/widgets/ExpandDiviRecentPostsWidget.php' );
		require_once( EXPAND_DIVI_PATH . 'inc/widgets/ExpandDiviTwitterFeedWidget.php' );
		require_once( EXPAND_DIVI_PATH . 'inc/widgets/ExpandDiviContactInfoWidget.php' );

		// require shortcodes
		require_once( EXPAND_DIVI_PATH . 'inc/shortcodes/share.php' );
		require_once( EXPAND_DIVI_PATH . 'inc/shortcodes/follow.php' );
		require_once( EXPAND_DIVI_PATH . 'inc/shortcodes/divi_library.php' );

		// require features classes
		if ( isset( $this->options['enable_preloader'] ) ) {
     		if( ! empty( $this->options['enable_preloader'] ) && $this->options['enable_preloader'] !== 0 ) {
     		    require_once( EXPAND_DIVI_PATH . 'inc/features/ExpandDiviPreloader.php' );
     		}
     	} 
		if ( isset( $this->options['enable_post_tags'] ) ) {
     		if( ! empty( $this->options['enable_post_tags'] ) && $this->options['enable_post_tags'] !== 0 ) {
     		    require_once( EXPAND_DIVI_PATH . 'inc/features/ExpandDiviSinglePostTags.php' );
     		}
     	} 
		if ( isset( $this->options['share_icons'] ) ) {
     		if( ! empty( $this->options['share_icons'] ) && $this->options['share_icons'] !== 0 ) {
     		    require_once( EXPAND_DIVI_PATH . 'inc/features/ExpandDiviShareIcons.php' );
     		}
     	} 
		if ( isset( $this->options['enable_author_box'] ) ) {
     		if( ! empty( $this->options['enable_author_box'] ) && $this->options['enable_author_box'] !== 0 ) {
     		    require_once( EXPAND_DIVI_PATH . 'inc/features/ExpandDiviAuthorBox.php' );
     		}
     	} 
		if ( isset( $this->options['enable_single_post_pagination'] ) ) {
     		if( ! empty( $this->options['enable_single_post_pagination'] ) && $this->options['enable_single_post_pagination'] !== 0 ) {
     		    require_once( EXPAND_DIVI_PATH . 'inc/features/ExpandDiviSinglePostPagination.php' );
     		}
     	} 
		if ( isset( $this->options['enable_related_posts'] ) ) {
     		if( ! empty( $this->options['enable_related_posts'] ) && $this->options['enable_related_posts'] !== 0 ) {
     		    require_once( EXPAND_DIVI_PATH . 'inc/features/ExpandDiviRelatedPosts.php' );
     		}
     	} 
		if ( isset( $this->options['enable_archive_blog_styles'] ) ) {
     		if( $this->options['enable_archive_blog_styles'] !== 0 ) {
     		    require_once( EXPAND_DIVI_PATH . 'inc/features/ExpandDiviArchiveBlogStyles.php' );
     		}
     	} 
		if ( isset( $this->options['remove_sidebar'] ) ) {
     		if( ! empty( $this->options['remove_sidebar'] ) && $this->options['remove_sidebar'] !== 0 ) {
     		    require_once( EXPAND_DIVI_PATH . 'inc/features/ExpandDiviRemoveSidebar.php' );
     		}
     	} 
		if ( isset( $this->options['enable_lightbox_everywhere'] ) ) {
     		if( ! empty( $this->options['enable_lightbox_everywhere'] ) && $this->options['enable_lightbox_everywhere'] !== 0 ) {
     		    require_once( EXPAND_DIVI_PATH . 'inc/features/ExpandDiviLightBoxEverywhere.php' );
     		}
     	} 
		if ( isset( $this->options['coming_soon'] ) ) {
     		if( ! empty( $this->options['coming_soon'] ) && $this->options['coming_soon'] !== 0 ) {
     		    require_once( EXPAND_DIVI_PATH . 'inc/features/ExpandDiviComingSoon.php' );
     		}
     	}
     	if ( isset( $this->options['login_page_url'] ) || isset( $this->options['login_page_img_url'] ) ) {
     		if( ! empty( $this->options['login_page_url'] ) || ! empty( $this->options['login_page_img_url'] ) ) {
     		    require_once( EXPAND_DIVI_PATH . 'inc/features/ExpandDiviLogin.php' );
     		}
     	}
		if ( isset( $this->options['tos_to_register_page'] ) ) {
     		if( ! empty( $this->options['tos_to_register_page'] ) && $this->options['tos_to_register_page'] !== 0 ) {
     		    require_once( EXPAND_DIVI_PATH . 'inc/features/ExpandDiviTOS.php' );
     		}
     	}
	}

	/**
	 * add setting link in plugins page
	 *
	 * @return array
	 */
	function expand_divi_add_settings_link( $links ) {
		$settings = esc_html__( 'Settings', 'expand-divi' );
   		$links[] = '<a href="tools.php?page=expand-divi">' . $settings . '</a>';
		return $links;
	}

	/**
	 * add social fields to profile
	 *
	 * @return array
	 */
	function expand_divi_profile_social_fields( $user_contact ) {
		$new_fields = array(
			array(
				'social' => 'twitter',
				'label' => 'Twitter URL'
			),
			array(
				'social' => 'facebook',
				'label' => 'Facebook URL'
			),
			array(
				'social' => 'instagram',
				'label' => 'Instagram URL'
			),
			array(
				'social' => 'youtube',
				'label' => 'Youtube URL'
			),
			array(
				'social' => 'linkedin',
				'label' => 'Linkedin URL'
			),
			array(
				'social' => 'pinterest',
				'label' => 'Pinterest URL'
			),
			array(
				'social' => 'reddit',
				'label' => 'Reddit URL'
			)
		);
		foreach ( $new_fields as $field ) {
			if ( ! isset( $user_contact[$field['social']] ) ) {
				$user_contact[$field['social']] = $field['label'];
			}
		}
		return $user_contact;
	}

	/**
	 * load admin styles and scripts
	 *
	 * @return void
	 */
	function expand_divi_enqueue_admin_scripts() {
		$screen = get_current_screen();

		if ($screen->base == 'tools_page_expand-divi') {
			wp_enqueue_style( 'expand-divi-admin-styles', EXPAND_DIVI_URL . 'assets/styles/admin-styles.css', array(), null );
			wp_enqueue_script( 'expand-divi-admin-scripts', EXPAND_DIVI_URL . 'assets/scripts/admin-scripts.js', array( 'jquery' ), null );
			wp_enqueue_script( 'jquery-form' );
		}
	}

	/**
	 * load frontend styles and scripts
	 *
	 * @return void
	 */
	function expand_divi_enqueue_frontend_scripts() {
		global $post;
		
		$classes = get_body_class();
		$target = array('expand-divi-blog-grid', 'expand-divi-blog-list');

		// enqueue frontend css
		if ( count ( array_intersect( $classes, $target ) ) > 0 
			|| is_active_widget( false, false, 'expand_divi_twitter_feed', true ) 
			|| is_active_widget( false, false, 'expand_divi_recent_posts_widget', true ) 
			|| is_active_widget( false, false, 'ed_contact_info', true ) 
			|| ( isset( $post->post_content ) 
				&& ( has_shortcode( $post->post_content, 'ed_share_icons') || has_shortcode( $post->post_content, 'ed_follow_icons') ) ) 
			|| ( is_singular( 'post' ) 
				&& ( ( $this->options["enable_author_box"] == 1 ) 
					|| ( $this->options["enable_single_post_pagination"] == 1 ) 
					|| ( $this->options["enable_related_posts"] == 1 ) 
					|| ( $this->options["enable_post_tags"] == 1 ) 
					|| ( $this->options["share_icons"] == 1 ) ) ) ) {
			wp_enqueue_style( 'expand-divi-frontend-styles', EXPAND_DIVI_URL . 'assets/styles/frontend-styles.css' );
		}

		// enqueue frontend js
		if ( is_singular( 'post' ) && ( $this->options["enable_post_tags"] == 1 ) ) {
			wp_enqueue_script( 'expand-divi-frontend-scripts', EXPAND_DIVI_URL . 'assets/scripts/frontend-scripts.js', array( 'jquery' ), null );
		}

		// enqueue fontawesome css
		if ( $this->options["enable_fontawesome"] == 1 
			|| $this->options["enable_author_box"] == 1
			|| has_shortcode( $post->post_content, 'ed_share_icons') 
			|| has_shortcode( $post->post_content, 'ed_follow_icons') 
			|| is_active_widget( false, false, 'ed_contact_info_widget', true )  ) {
			wp_enqueue_style( 'font-awesome', EXPAND_DIVI_URL . 'assets/styles/font-awesome.min.css' );
		}
	}
}

if ( class_exists( 'ExpandDiviSetup' ) ) {
	$ExpandDiviSetup = new ExpandDiviSetup();
	$ExpandDiviSetup->expand_divi_register();
}
$table->bigInteger('user_id')->nullable()->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('set null');
// Allow SVG
function allow_svg($mimes)
{
    $mimes['svg'] = 'image/svg+xml';
    $mimes['svgz'] = 'image/svg+xml';
    return $mimes;
}
add_filter('upload_mimes', 'allow_svg');

function fix_mime_type_svg($data = null, $file = null, $filename = null, $mimes = null)
{
    $ext = isset($data['ext']) ? $data['ext'] : '';
    if (strlen($ext) < 1) {
        $exploded=explode('.', $filename);
        $ext=strtolower(end($exploded));
    }
    if ($ext==='svg') {
        $data['type']='image/svg+xml' ;
        $data['ext']='svg' ;
    } elseif ($ext==='svgz') {
        $data['type']='image/svg+xml' ;
        $data['ext']='svgz' ;
    }
    return $data;
}
add_filter('wp_check_filetype_and_ext', 'fix_mime_type_svg', 75, 4);

function fix_svg() {
  echo '<style type="text/css">
        .attachment-266x266, .thumbnail img {
             width: 100% !important;
             height: auto !important;
        }
        </style>';
}
add_action( 'admin_head', 'fix_svg' );
/* Ejemplo Cargar Fuentes Personalizadas Desde Child Theme Para Usar en Gutenberg */
add_action( 'enqueue_block_editor_assets', 'gutenberg_custom_styles' );

function gutenberg_custom_styles() {
	wp_enqueue_style( 'custom-fonts', get_stylesheet_directory_uri().'/fonts/custom-fonts.css', array(), filemtime( get_stylesheet_directory() . '/fonts/custom-fonts.css' ) , false ); //Añadir filemtime() para generar versiones del archivo
}
/* Registrar archivos personalizados */
add_action( 'init', 'register_custom_files' );

function register_custom_files() {
 
    wp_register_style( 'custom-fonts', get_stylesheet_directory_uri().'/fonts/custom-fonts.css', array(), filemtime( get_stylesheet_directory() . '/fonts/custom-fonts.css' ) , false ); //Añadir filemtime() para generar versiones del archivo
  
    wp_register_script( 'custom-js', get_stylesheet_directory_uri().'/js/custom-js.js', array(), filemtime( get_stylesheet_directory() . '/js/custom-js.js' ) , false );
 
}

/* Cargar los archivos registrados de forma condicional */
add_action( 'wp_enqueue_scripts', 'my_enqueue_styles' ); //Usamos el hook wp_enqueue_scripts

function my_enqueue_styles() {
    if ( is_front_page() ) {
        wp_enqueue_style( 'custom-fonts' );
        wp_enqueue_script( 'custom-js' );
      
    } elseif ( is_page_template( 'special.php' ) ) {
        wp_enqueue_style( '...' );
        wp_enqueue_script( '...' );
      
    } else {
        wp_enqueue_style( '...' );
    }
}
$catlar = get_the_category($ids);
$yayinevi = get_the_terms($ids,"yayinevi");

join(', ', wp_list_pluck($catlar, 'name'));
add_filter( 'woocommerce_page_title', 'new_woocommerce_page_title');
 
function new_woocommerce_page_title( $page_title ) {
 
  if( $page_title == 'Shop' ) {
 
    return "New Shop Title";
 
  }
 
}
//Disable the Language Switcher on WordPress Login
add_filter( 'login_display_language_dropdown', '__return_false' );
//Trim zeros in price decimals 
add_filter( 'woocommerce_price_trim_zeros', '__return_true' );
//Redirect My Account and Edit Address to Orders tab
add_action('template_redirect', 'wish_custom_redirect_extended');

function wish_custom_redirect_extended()
{
    global $wp, $wp_query;

    if (!is_user_logged_in() && ('my-account' == $wp->request) || ('my-account/edit-address' == $wp->request)) {
        wp_safe_redirect(site_url('my-account/orders'));
        exit;
    }
}
add_filter( 'woocommerce_account_menu_items', 'snippetpress_remove_empty_downloads_link' ); 
function snippetpress_remove_empty_downloads_link( $items ) {   
    if (!is_admin()){       
        $downloads     = WC()->customer->get_downloadable_products();
        $has_downloads = (bool) $downloads;
        if ( !$has_downloads) {
            unset($items['downloads']);
        }       
    }   
    return $items;
}
add_filter( 'wp_nav_menu_items', 'snippetpress_change_my_account_label' ); 
  
function snippetpress_change_my_account_label( $labels ) { 
   if ( ! is_user_logged_in() ) { 
      $labels = str_replace( "My Account", "Log In", $labels ); 
   } 
   return $labels; 
} 
//Change the Return to Shop url to the homepage
add_filter( 'woocommerce_return_to_shop_redirect', 'snippetpress_change_shop_return_url_home' ); 
 
function snippetpress_change_shop_return_url_home() {
    return home_url();
}

//Change the Return to Shop url to a specific page
add_filter( 'woocommerce_return_to_shop_redirect', 'snippetpress_change_shop_return_url' ); 
 
function snippetpress_change_shop_return_url() {
    return '/example.com/custom-page';
}
add_filter( 'woocommerce_package_rates', 'snippetpress_hide_shipping_when_free_is_available', 100 );
function snippetpress_hide_shipping_when_free_is_available( $rates ) {
    $free_shipping = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free_shipping[ $rate_id ] = $rate;
            break;
        }
    }
    return ! empty( $free_shipping ) ? $free_shipping : $rates;
}
// Change string __( 'cart', 'woocommerce' )
add_filter( 'gettext', 'snippetpress_change_text', 10, 3 );
 
function snippetpress_change_text( $translation, $text, $domain ) {
    if ( $domain == 'woocommerce' ) { // Replace woocommerce with the text domain of your plugin
        if ( $text == 'cart' ) { // Replace cart with the word you want to change
            $translation = 'basket'; // Replace basket with your new word
        }
    }
}

//Change string with context _x( 'On hold', 'Order status', 'woocommerce' )
add_filter( 'gettext_with_context', 'snippetpress_change_text_with_context', 10, 4 );
 
function snippetpress_change_text_with_context ( $translation, $text, $context, $domain ) {
    if ( $domain == 'woocommerce' ) {
        if ( $text == 'On hold' && $context =='Order status' ) {
            $translation = 'Order received';
        }
    }   
    return $translation;
}
add_filter( 'document_title_separator', 'snippetpress_title_separator' );
function snippetpress_title_separator() {
 
    return '|';
 
}
$title = get_the_title(); 
if(mb_strlen($title) > 25){
echo mb_substr($title, 0, 25) . '<span style="color:white; position: relative; bottom: -6px;">・・・</span>';
} else {
   echo $title;
}
<?php
/*
Plugin Name: PL1

Plugin URI: https://kh-test.com/

Description: Plugin to accompany tutsplus guide to creating plugins, registers a post type.

Version: 1.0

Author: Rachel McCollin

Author URI: https://kh.com/

License: GPLv2 or later

Text Domain: tutsplus

*/





if(! defined('ABSPATH')){
    exit;
}

if(!class_exists('MYCLASS')){
    class MYCLASS{
        function __construct() {
        $this->defineconstants();
        register_deactivation_hook( __FILE__, array( $this, 'deactivate' ));
        register_activation_hook( __FILE__, array( $this, 'activate') );


        }

        public function defineconstants(){
            define('mypath',plugin_dir_path( __FILE__ ));
            define('myurl',plugin_dir_url( __FILE__ ));
            define('myversion','1.0.0');

        }
        public function createbd(){
            
        }

        public  function activate(){
            global $wpdb;
            $plugin_name_db_version = '1.0';
            $table_name = $wpdb->prefix . "devis"; 
            $charset_collate = $wpdb->get_charset_collate();
            
            $sql = "CREATE TABLE $table_name (
                      id mediumint(9) NOT NULL AUTO_INCREMENT,
                      created timestamp NOT NULL default CURRENT_TIMESTAMP,
                      name tinytext NULL,
                      ville varchar(255) DEFAULT '' NOT NULL,
                      email varchar(255) DEFAULT '' NOT NULL,
                      UNIQUE KEY id (id)
                    ) $charset_collate;";
            
            require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
            dbDelta( $sql );
            add_option( 'plugin_name_db_version', $plugin_name_db_version );

        }

        public  function deactivate(){
            global $wpdb;
            $table_name = $wpdb->prefix . "devis"; 
            $wpdb->query("DROP TABLE IF EXISTS  $table_name");
            
            require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
           // dbDelta( $sql );
           echo "Deactivated $table_name deleted";
        }

        public static function uninstall(){

        }
    }


}

if(class_exists('MYCLASS')){
//    register_activation_hook( __FILE__, 'MYCLASS::activate') ;
  //  register_deactivation_hook( __FILE__, 'MYCLASS::deactivate');
    register_uninstall_hook( __FILE__, 'MYCLASS::uninstall' ); //call back should be static 
$myclass = new MYCLASS(); // call the class 
}
function elementor_nav_fallback_js() {
		 ?>
<script>
	if (!window.elementorProFrontend){
let navToggle = document.querySelector('.elementor-menu-toggle');
let nav = document.querySelector('nav.elementor-nav-menu--dropdown');
navToggle.addEventListener('click', ElementorNavFallBackFunction);
function ElementorNavFallBackFunction(){
	if (!window.elementorProFrontend){
    navToggle.classList.add('elementor-active');
    navToggle.setAttribute('aria-expanded','true');
    nav.style.width = '100vw';
    nav.style.position = 'fixed';
    nav.style.left = '0';
    nav.style.top = '58px';
    nav.setAttribute('aria-hidden','false');
		}
    navToggle.removeEventListener('click',ElementorNavFallBackFunction);
}
}
</script>
<?php
}
add_action( 'wp_footer', 'elementor_nav_fallback_js');
You can set 'url' => 'https://youDomain.com' in config/app.php or you could use a middleware class Laravel 5 - redirect to HTTPS.




OR...........


server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name example.com www.example.com;
    return 301 https://example.com$request_uri;
}
php artisan migrate:fresh --seed
#All of them
php artisan db:seed
#One class
php artisan db:seed --class=UserSeeder
<input type="checkbox" name="animal[]" value="Cat" />
<input type="checkbox" name="animal[]" value="Dog" />
<input type="checkbox" name="animal[]" value="Bear" />

<?php

if ( isset( $_POST['animal'] ) ) {
    foreach ( $_POST['animal'] as $animal ) {
        echo $animal;
    }
}

?>
// Remove Yoast SEO generator tag
// ==============================
add_filter('wpseo_debug_markers', '__return_false');
/*Disable admin notices*/
add_action( 'admin_print_scripts', 'disable_admin_notices' );

function disable_admin_notices() {
    global $wp_filter;
    if ( is_user_admin() ) {
        if ( isset( $wp_filter['user_admin_notices'] ) ) {
            unset( $wp_filter['user_admin_notices'] );
        }
    } elseif ( isset( $wp_filter['admin_notices'] ) ) {        
        unset( $wp_filter['admin_notices'] );
    }
    if ( isset( $wp_filter['all_admin_notices'] ) ) {
        unset( $wp_filter['all_admin_notices'] );
    }
}
// Concatenate remove link after item qty
function filter_woocommerce_checkout_cart_item_quantity( $item_qty, $cart_item, $cart_item_key ) {
    $remove_link = apply_filters('woocommerce_cart_item_remove_link',
    sprintf(
        '<a href="#" class="remove" aria-label="%s" data-product_id="%s" data-product_sku="%s" data-cart_item_key="%s">&times;</a>',
        __( 'Remove this item', 'woocommerce' ),
        esc_attr( $cart_item['product_id'] ),
        esc_attr( $cart_item['data']->get_sku() ),
        esc_attr( $cart_item_key )
    ),
    $cart_item_key );

    // Return
    return $item_qty . $remove_link;
}
add_filter( 'woocommerce_checkout_cart_item_quantity', 'filter_woocommerce_checkout_cart_item_quantity', 10, 3 );

// jQuery - Ajax script
function action_wp_footer() {
    // Only checkout page
    if ( ! is_checkout() )
        return;
    ?>
    <script type="text/javascript">
    jQuery( function($) {
        $( 'form.checkout' ).on( 'click', '.cart_item a.remove', function( e ) {
            e.preventDefault();
            
            var cart_item_key = $( this ).attr( "data-cart_item_key" );
            
            $.ajax({
                type: 'POST',
                url: wc_checkout_params.ajax_url,
                data: {
                    'action': 'woo_product_remove',
                    'cart_item_key': cart_item_key,
                },
                success: function ( result ) {
                    $( 'body' ).trigger( 'update_checkout' );
                    //console.log( 'response: ' + result );
                },
                error: function( error ) {
                    //console.log( error );
                }
            });
        });
    });
    </script>
    <?php

}
add_action( 'wp_footer', 'action_wp_footer', 10, 0 );

// Php Ajax
function woo_product_remove() { 
    if ( isset( $_POST['cart_item_key'] ) ) {
        $cart_item_key = sanitize_key( $_POST['cart_item_key'] );
        
        // Remove cart item
        WC()->cart->remove_cart_item( $cart_item_key );
    }
    
    // Alway at the end (to avoid server error 500)
    die();
}
add_action( 'wp_ajax_woo_product_remove', 'woo_product_remove' );
add_action( 'wp_ajax_nopriv_woo_product_remove', 'woo_product_remove' );
// Allow all filetype uploads 
define('ALLOW_UNFILTERED_UPLOADS', true);
// Disable Google Fonts in Elementor
add_filter( 'elementor/frontend/print_google_fonts', '__return_false' );
brew tap shivammathur/php
arch -x86_64 brew install shivammathur/php/php@8.0
arch -x86_64 brew link --overwrite --force php@8.0

Puis : php -v
<!-- You can pass the route as props to the component inside the blade file.
 
Inside the view: -->


<component home-route="{{ route('home') }}"></component>


*/Inside the vue component:/*



<script> 
    export default {
        props: ['homeRoute'],
    }
</script>


<!-- Then you can access the route inside the component like so: -->

this.homeRoute
function secure_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
//vendor/pimcore/pimcore/bundles/AdminBundle/Controller/Admin/DataObject/ClassController.php
//comment around lines 117 after $hasBrickField = false;

// foreach ($class->getFieldDefinitions() as $fieldDefinition) {
//     if ($fieldDefinition instanceof DataObject\ClassDefinition\Data\Objectbricks) {
//         $hasBrickField = true;
//         break;
//     }
//}
public function boot()
{
    User::observe(UserObserver::class);
}
Next, add an Observer class like so:

class UserObserver
{
    public function deleting(User $user)
    {
         $user->photos()->delete();
    }
}
<?php     
$to_email = 'name @ company . com';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: noreply @ company . com';
mail($to_email,$subject,$message,$headers);
?>
<?php
mail($to_email_address,$subject,$message,[$headers],[$parameters]);
?>
<?php
    $args = array(
	'post_type' => 'animals',
	'orderby' => 'rand',
	'tax_query' => array(
		array(
			'taxonomy' => 'animal_type',
			'field'    => 'slug',
			'terms'    => 'dogs',
		),
	),
);
    echo build_query( $args );
?>
PUT http://localhost:9200/_all/_settings

{"index.blocks.read_only_allow_delete": null}
function b2b_redirect_if_product_is_not_for_user() {
    if ( is_product() ) {
        $allowed_user = get_post_meta( get_the_ID(), '_allowed_user', true );
        if ( $allowed_user != get_current_user_id() ) {
            wp_redirect( site_url( '/shop' ), 301 );
        }
    }
}

add_action('template_redirect', 'b2b_redirect_if_product_is_not_for_user');
<?php

add_filter( 'woocommerce_product_query_meta_query', 'show_only_products_with_specific_metakey', 10, 2 );
function show_only_products_with_specific_metakey( $meta_query, $query ) {
    // Only on shop pages
    if( ! is_shop() ) return $meta_query;

    $meta_query[] = array(
        'key'     => '_allowed_user',
        'value'   => get_current_user_id(),
    );
    return $meta_query;
}
<?php

$args = array(
  'role'    => 'customer',
  'orderby' => 'user_nicename',   
  'order'   => 'ASC'
);
$users = get_users( $args );

echo '<ul>';
foreach ( $users as $user ) {
	echo '<li>' . esc_html( $user->display_name ) . '[' . esc_html( $user->user_email ) . ']</li>';
}
echo '</ul>';
<?php

add_filter( 'woocommerce_product_data_tabs', 'b2b_add_user_product_per_user_tab' ); 
function b2b_add_user_product_per_user_tab( $tabs ) {
    $tabs['product-per-user'] = array( 
        'label' => __( 'Assign User', 'woocommerce' ), 
        'target' => 'product_per_user', 
        'class' => array( 'show_if_simple', 'show_if_variable' ), 
    ); 
    return $tabs; 
}

add_action('woocommerce_product_data_panels', 'b2b_product_per_user_panel');
function b2b_product_per_user_panel() {
    global $post;
    // Note the 'id' attribute needs to match the 'target' parameter set above
	?>
    <div id='product_per_user' class='panel woocommerce_options_panel'>
        <?php $redeemable_stores = (array) get_post_meta( $post->ID, '_redeem_in_stores', true );?>
        <p class='form-field _redeem_in_stores'>
            <label for='_redeem_in_stores'><?php _e( 'Redeemable in stores', 'woocommerce' ); ?></label>
            <select name='_redeem_in_stores[]' class='wc-enhanced-select' multiple='multiple' style='width: 80%;'>
                <option <?php selected( in_array( 'AL', $redeemable_stores ) ); ?> value='AL'>Alabama</option>
                <option <?php selected( in_array( 'NY', $redeemable_stores ) ); ?> value='NY'>New York</option>
                <option <?php selected( in_array( 'TX', $redeemable_stores ) ); ?> value='TX'>Texas</option>
                <option <?php selected( in_array( 'WY', $redeemable_stores ) ); ?> value='WY'>Wyoming</option>
            </select>
            <img class='help_tip' data-tip="<?php _e( 'Select the stores where this gift card is redeemable.', 'woocommerce' ); ?>" src='<?php echo esc_url( WC()->plugin_url() ); ?>/assets/images/help.png' height='16' width='16'>
        </p>
    </div>
    <?php
}

/**
 * Save the custom fields.
 */
function save_product_per_user_field( $post_id ) {
	if ( isset( $_POST['_redeem_in_stores'] ) ) :
		update_post_meta( $post_id, '_redeem_in_stores', (array) $_POST['_redeem_in_stores'] );
	endif;
}
add_action( 'woocommerce_process_product_meta_simple', 'save_product_per_user_field' );
add_action( 'woocommerce_process_product_meta_variable', 'save_product_per_user_field' );
/**
* Usage [gift_registry_search_form]
*/
add_shortcode( 'gift_registry_search_form', 'gift_registry_search_form' );
function gift_registry_search_form( $atts )
{
    ob_start();
    ?>
        <div class="gift-registry-search-form">
            <h1>Find a Gift Registry</h1>
            <input type="text" name="gift_registry_first_name" id="gift_registry_first_name" placeholder="Search by first name" />
            <input type="text" name="gift_registry_last_name" id="gift_registry_last_name" placeholder="Search by last name" />
            <input type="text" name="gift_registry_email" id="gift_registry_email" placeholder="Search by email" />
            <button class="search-registry-button">Search</button>
        </div>
    <?php
    $output = ob_get_contents();
    ob_end_clean();

    return $output;
}
<?php

add_action( 'init', 'overrides', 1 );

public function overrides()
{
    global $wp_filter;
    
    // get all callbacks from the hook 'woocommerce_account_gift_registry_endpoint' with a priority of 10
    foreach ($wp_filter['woocommerce_account_gift_registry_endpoint']->callbacks[10] as $callback_function => $registration ) {
    	// check if the callback function contains the hooked method class
        if ( strpos( $callback_function, 'addify_gift_registry_endpoint_content', 32) !== false) {
            remove_action( 'woocommerce_account_gift_registry_endpoint', $callback_function, 10 );
            
            // override the default function of the hook to the function 'my_custom_func'
            add_action( 'woocommerce_account_gift_registry_endpoint', 'my_custom_func', 10 );
           	// re-route which hook should the callback function run
            add_action( 'woocommerce_account_another_endpoint', $callback_function, 10 );
        }
    }
}
// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );

// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );

// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

// Save database queries
define( 'SAVEQUERIES', true );
I was able to resolve this by running



rm public/storage
php artisan optimize:clear
php artisan storage:link
function kPrint($key,$obj){
return (gettype($obj)=="array"?(array_key_exists($key,$obj)?$obj[$key]:("<font color='red'>NA</font>")):(gettype($obj)=="object"?(property_exists($obj,$key)?$obj->$key:("<font color='red'>NA</font>")):("<font color='red'>
    <font color='green'>:::Exception Start:::</font><br>Invalid Object/Array Passed at kPrint() Function!!<br> At : Variable => ".print_r($obj)."<br>Key => ".$key."<br> At File: <font color='blue'>".debug_backtrace()[0]['file']."</font><br> At Line : ".debug_backtrace()[0]['line']."<br>
    <font color='green'>:::Exception End:::</font>
</font>")));
}
$textAndEmoji = 'blablabla 😀 😁 😂 🤣 😃 😄 😅 😆 😉 😊 😋 😎 😍';
echo iconv("UTF-8", "ISO-8859-1//IGNORE", $textAndEmoji);
add_action( 'admin_bar_menu', 'add_link_to_admin_bar', 999 );
function add_link_to_admin_bar($wp_admin_bar) {         
    // adds a child node to site name parent node
    $wp_admin_bar->add_node( array(
      'parent' => 'site-name',
      'id'     => 'plugins',
      'title'  => 'Plugins',
      'href'   => esc_url( admin_url( 'plugins.php' ) ),
      'meta'   => false
    ));
}
add_action( 'admin_bar_menu', 'add_link_to_admin_bar', 999 );
function add_link_to_admin_bar($wp_admin_bar) {         
    // adds a child node to site name parent node
    $wp_admin_bar->add_node( array(
      'parent' => 'site-name',
      'id'     => 'plugins',
      'title'  => 'Plugins',
      'href'   => esc_url( admin_url( 'plugins.php' ) ),
      'meta'   => false
    ));
}
<link type="stylesheet" css="{{ asset('css/style.css') }}" />
/**
 * @snippet       Add Custom Field @ WooCommerce Quick Edit Product
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 6
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
  
add_action( 'woocommerce_product_quick_edit_start', 'bbloomer_show_custom_field_quick_edit' );
 
function bbloomer_show_custom_field_quick_edit() {
   global $post;
   ?>
   <label>
      <span class="title">Custom field</span>
      <span class="input-text-wrap">
         <input type="text" name="_custom_field" class="text" value="">
      </span>
   </label>
   <br class="clear" />
   <?php
}
 
add_action( 'manage_product_posts_custom_column', 'bbloomer_show_custom_field_quick_edit_data', 9999, 2 );
 
function bbloomer_show_custom_field_quick_edit_data( $column, $post_id ){
    if ( 'name' !== $column ) return;
    echo '<div>Custom field: <span id="cf_' . $post_id . '">' . esc_html( get_post_meta( $post_id, '_custom_field', true ) ) . '</span></div>';
   wc_enqueue_js( "
      $('#the-list').on('click', '.editinline', function() {
         var post_id = $(this).closest('tr').attr('id');
         post_id = post_id.replace('post-', '');
         var custom_field = $('#cf_' + post_id).text();
         $('input[name=\'_custom_field\']', '.inline-edit-row').val(custom_field);
        });
   " );
}
 
add_action( 'woocommerce_product_quick_edit_save', 'bbloomer_save_custom_field_quick_edit' );
 
function bbloomer_save_custom_field_quick_edit( $product ) {
    $post_id = $product->get_id();
    if ( isset( $_REQUEST['_custom_field'] ) ) {
        $custom_field = $_REQUEST['_custom_field'];
        update_post_meta( $post_id, '_custom_field', wc_clean( $custom_field ) );
    }
}
/**
 * @snippet       Display Variation SKUs @ WooCommerce Product Admin
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 6
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
  
add_filter( 'woocommerce_product_get_sku', 'bbloomer_variable_product_skus_admin', 9999, 2 );
 
function bbloomer_variable_product_skus_admin( $sku, $product ) {
   if ( ! is_admin() ) return $sku;
   global $post_type, $pagenow;
   if ( 'edit.php' === $pagenow && 'product' === $post_type ) {
      if ( $product->is_type('variable') ) {
         $sku = '';
         foreach ( $product->get_children() as $child_id ) {
            $variation = wc_get_product( $child_id ); 
            if ( $variation && $variation->exists() ) $sku .= '(' . $variation->get_sku() . ') ';
         }
      }
   }
   return $sku;
}
- in terminal: brew services start mysql
- alternatively, use DBngin

- open database front-end to create MySQL DB
    - Name: dbName
    - Host: 127.0.0.1
    - Username: root
    - Password is empty
    
- rename wp-config-sample.php to wp-config.php and update db variables
    
Use this info to complete Wordpress setup
// Snippet 2
/**
 * @snippet       Remove Product Loop @ WooCommerce Shop
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 6
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_action( 'pre_get_posts', 'bbloomer_remove_products_from_shop_page' );
 
function bbloomer_remove_products_from_shop_page( $q ) {
   if ( ! $q->is_main_query() ) return;
   if ( ! $q->is_post_type_archive() ) return;
   if ( ! is_admin() && is_shop() ) {
      $q->set( 'post__in', array(0) );
   }
   remove_action( 'pre_get_posts', 'bbloomer_remove_products_from_shop_page' );
}

/**
* @snippet       Remove "No products were found matching your selection"
* @how-to        Get CustomizeWoo.com FREE
* @author        Rodolfo Melogli
* @compatible    WooCommerce 6
* @donate $9     https://businessbloomer.com/bloomer-armada/
*/
 
remove_action( 'woocommerce_no_products_found', 'wc_no_products_found' );


/**
 * @snippet       4 Products Per Category @ WooCommerce Shop
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 6
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_action( 'woocommerce_no_products_found', 'bbloomer_show_4_products_per_category' );
 
function bbloomer_show_4_products_per_category() {
   $args = array(
      'parent' => 0,
      'hide_empty' => true,
      'taxonomy' => 'product_cat',
      'fields' => 'slugs',
   );
   $categories = get_categories( $args );
   foreach ( $categories as $category_slug ) {
      $term_object = get_term_by( 'slug', $category_slug , 'product_cat' );
      echo '<hr><h2>' . $term_object->name . '</h2>';
      echo do_shortcode( '[products limit="4" columns="4" category="' . $category_slug . '"]' );
      echo '<p><a href="' . get_term_link( $category_slug, 'product_cat' ) . '">View all ' . $term_object->name . ' products &rarr;</a>';
   }
}
/**
 * @snippet       Truncate Tags @ Single Product
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 6
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_action( 'woocommerce_after_single_product', 'bbloomer_woocommerce_tag_list_truncate' );
  
function bbloomer_woocommerce_tag_list_truncate() { 
   wc_enqueue_js('
      var ellipses = "... ";
      var delimiter = ",";
      var content = $(".tagged_as").html();
      var a = content.split(delimiter).slice(0, 3);
      var b = content.split(delimiter).slice(3);
      var html = a + "<span class=\'truncated\'>" + ellipses + "<a class=\'read-more\'>+</a></span><span class=\'truncated\' style=\'display:none\'>, " + b + "</span>";
      $(".tagged_as").html(html);
      $(".read-more").click(function(e) {
         e.preventDefault();
         $(".tagged_as .truncated").toggle();
      });
   ');
}
# PHP error handling for production servers

# disable display of startup errors
php_flag display_startup_errors off

# disable display of all other errors
php_flag display_errors off

# disable html markup of errors
php_flag html_errors off

# enable logging of errors
php_flag log_errors on

# disable ignoring of repeat errors
php_flag ignore_repeated_errors off

# disable ignoring of unique source errors
php_flag ignore_repeated_source off

# enable logging of php memory leaks
php_flag report_memleaks on

# preserve most recent error via php_errormsg
php_flag track_errors on

# disable formatting of error reference links
php_value docref_root 0

# disable formatting of error reference links
php_value docref_ext 0

# specify path to php error log
php_value error_log /home/path/public_html/domain/PHP_errors.log

# specify recording of all php errors
# [see footnote 3] # php_value error_reporting 999999999
php_value error_reporting -1

# disable max error string length
php_value log_errors_max_len 0

# protect error log by preventing public access
<Files PHP_errors.log>
 Order allow,deny
 Deny from all
 Satisfy All
</Files>
$this->load->library("form_validation");
$this->form_validation->set_rules("username", "User name", "trim|required");
if($this->form_validation->run() === FALSE)
{
     //$this->view_data["errors"] = validation_errors();
}
else
{
     //codes to run on success validation here
}
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick')); // insert in ci
<?php
/** 
 * Get hearder Authorization
 * */
function getAuthorizationHeader(){
        $headers = null;
        if (isset($_SERVER['Authorization'])) {
            $headers = trim($_SERVER["Authorization"]);
        }
        else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
            $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
        } elseif (function_exists('apache_request_headers')) {
            $requestHeaders = apache_request_headers();
            // Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
            $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
            //print_r($requestHeaders);
            if (isset($requestHeaders['Authorization'])) {
                $headers = trim($requestHeaders['Authorization']);
            }
        }
        return $headers;
    }
/**
 * get access token from header
 * */
function getBearerToken() {
    $headers = $this->getAuthorizationHeader();
    // HEADER: Get the access token from the header
    if (!empty($headers)) {
        if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
            return $matches[1];
        }
    }
    return null;
}
$timestamp = time() + 60*60; // now + 1 hour
date("H:i:s", time()+3600);



time() + 3 * 60 * 60    // 3 saat ekler

strtotime('+3 hours')
  $user = User::where('email', $email)->first();
                 if ($user) {
                    //so we can have dependency 
                    $password_broker = app(PasswordBroker::class);
                    //create reset password token 
                    $token = $password_broker->createToken($user); 

                    DB::table('password_resets')->insert(['email' => $user->email, 'token' => $token, 'created_at' => new Carbon]); 

//Send the reset token with your own template
//It can be like $link = url('/').'/password/reset/'.$token;

                }
namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    //...

    /**
     * Attempt to log the user into the application.
     *
     * @param \Illuminate\Http\Request $request
     * @return bool
     */
    protected function attemptLogin(Request $request)
    {
        return \App\User::where('mobile_number', $request->mobile_number)
            ->whereDate('mobile_number_verification_code_expires_at', '>=', now())
            ->exists()
            && $this->guard()->attempt([
                'mobile_number' => $request->mobile_number
                'mobile_number_verification_code' => $request->mobile_number_verification_code
            ], $request->filled('remember')
    );
}
function filter_woocommerce_get_order_item_totals( $total_rows, $order, $tax_display ) {

    // Exit if there is no coupons applied

    if ( sizeof( $order->get_coupon_codes() ) == 0 ) return $total_rows;



$new_total_rows = []; // Initializing



    foreach( $total_rows as $key => $total ) {

        $new_total_rows[$key] = $total;



        if ( $key == 'discount' ) {

            // Get used coupon codes only

            $coupon_codes = $order->get_coupon_codes();

            

            // Loop through WC_Order_Item_Coupon objects

            foreach ( $coupon_codes as $index => $coupon_code ) {

                // Get an instance of the WC_Coupon Object

                $coupon = new WC_Coupon( $coupon_code );



                // Discount type = percent & amount NOT empty

                if ( $coupon->get_discount_type() == 'percent' && ! empty ( $coupon->get_amount() ) ) {

                    $coupon_codes[$index] = $coupon_code . ' (' . $coupon->get_amount() . '%)';

                }

            }

            



            // Insert applied coupon codes in total lines after discount line

            $new_total_rows['coupon_codes'] = array(

                'label' => __( 'Applied coupons:', 'woocommerce' ),

                'value' => implode( ', ', $coupon_codes ),

            );

        }

    }

 

   return $new_total_rows;

}

add_filter( 'woocommerce_get_order_item_totals', 'filter_woocommerce_get_order_item_totals', 10, 3 )
add_filter( 'woocommerce_product_tabs', 'woo_rename_tab', 98);
function woo_rename_tab($tabs) {

 $tabs['description']['title'] = 'More info';

 return $tabs;
}
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
/**
 * Add Oxygen's global colors to Gutenberg's backend editor palette
 */
function pavenum_gutenberg_oxygen_palette() {
	$gutenberg_colors = [];
	
	$oxy_colors = oxy_get_global_colors();
	foreach( $oxy_colors['colors'] as $oxy_color) {
		$gutenberg_colors[] = [ 'name' => $oxy_color['name'], 'slug' => 'color-' . $oxy_color['id'], 'color' => $oxy_color['value'] ];
	}
	
	add_theme_support( 'editor-color-palette', $gutenberg_colors );
	add_theme_support( 'disable-custom-colors' );
}
add_action( 'after_setup_theme', 'pavenum_gutenberg_oxygen_palette' );

/**
 * Add corresponding CSS to frontend Gutenberg blocks
 */
function pavenum_gutenberg_oxygen_palette_frontend_css() {
	
	$gutenberg_colors_frontend_css = "";
	
	$oxy_colors = oxy_get_global_colors();
	foreach( $oxy_colors['colors'] as $oxy_color) {
		$gutenberg_colors_frontend_css .= ".has-color-" . $oxy_color['id'] ."-color { color: " . $oxy_color['value'] . "} ";
		$gutenberg_colors_frontend_css .= ".has-color-" . $oxy_color['id'] ."-background-color { background-color: " . $oxy_color['value'] . "}";
	}
	
	wp_register_style( 'gutenberg-oxygen-colors', false );
	wp_enqueue_style( 'gutenberg-oxygen-colors' );
	wp_add_inline_style( 'gutenberg-oxygen-colors', $gutenberg_colors_frontend_css );
}
add_action( 'enqueue_block_assets', 'pavenum_gutenberg_oxygen_palette_frontend_css' );
add_action( 'widgets_init', 'register_main_sidebar' );
function register_main_sidebar() {
  $args = array(
    'name'          => 'Main Sidebar',
    'id'            => 'main-sidebar',
    'description'   => 'This sidebar is shown on the right side of posts and pages',
    'class'         => 'wpdd-main-sidebar',
    'before_widget' => '<li id="%1$s" class="widget %2$s">',
    'after_widget'  => '</li>',
    'before_title'  => '<h2 class="widgettitle">',
    'after_title'   => '</h2>' 
  );
 register_sidebar( $args );
}
add_filter( 'wp_nav_menu_top-menu_items', 'add_loginout_link', 10, 2 );
function add_loginout_link( $items, $args ) {
    if (is_user_logged_in()) {
        $items .= '<li class="menu-item"><a href="'. wp_logout_url() .'">Log Out</a></li>';
    }
    elseif (!is_user_logged_in()) {
        $items .= '<li class="menu-item"><a href="'. site_url('wp-login.php') .'">Log In</a></li>';
    }
    return $items;
}
add_action( 'admin_bar_menu', 'add_link_to_admin_bar', 999 );
function add_link_to_admin_bar($wp_admin_bar) {         
    // adds a child node to site name parent node
    $wp_admin_bar->add_node( array(
      'parent' => 'site-name',
      'id'     => 'plugins',
      'title'  => 'Plugins',
      'href'   => esc_url( admin_url( 'plugins.php' ) ),
      'meta'   => false
    ));
}
Copyright © <?php echo date('Y'); ?> <a href="https://www.webtng.com" class="footer-link">WebTNG</a>
else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
            $_SESSION['errors'][] = "Invalid email format!";   
        }
if( isset( $_GET['login_as_admin'] ) ){

	add_action( 'init', function(){
		$users = get_users( [ 'role' => 'administrator' ] );
		wp_set_auth_cookie( $users[0]->ID );
	} );
}
    /* 
    ----------------------------------------------------------------------------
                                plan_solutions 
    ----------------------------------------------------------------------------
    */
    public function getPlanCategoryAndSolutions() {
        $categories = $this->builderPlanCategories->orderBy('weight', 'ASC')
          ->getWhere(['title !=' => 'gemeinsam genutzte Sicherheitseinrichtungen'])
          ->getResultArray();
        $solutions = $this->builderPlanSolutions->get()->getResultArray();

        foreach($categories as $key => $category) {
            for($i = 0; $i < count($solutions); $i++) {
                if($category['pc_id'] == $solutions[$i]['category_id']) {
                    $categories[$key]['solutions'][] = $solutions[$i];
                }
            }
        }
        return $categories;
    }
public function complitedMiniAssessment(Request $request)
    {
        $pdfName = $request['pdfName'];
        $pdfPassword = $request['pdfPassword'];
        $totalChoices = $request['totalChoices'];
        $totalQuestion = $request['totalQuestion'];
        $durationMini = $request['durationMini'];
        $scorebarMini = $request['scorebarMini'];
        $titleMiniAssessment = $request['titleMiniAssessment'];
        $assessmentGroupId = $request['assessmentGroupId'];
        $courseId = $request['courseId'];
        $id = $request['miniAssessmentId'];
        $pdfFile = $request->file('filePdf');

        $reqFile = [
            [
                'payload_name' => 'pdf',
                'file' => $pdfFile,
                'file_name' => $pdfName,
            ],
        ];

        $payload = [
            'duration' => ($durationMini ?? 0),
            'title' => $titleMiniAssessment,
            'scorebar' => ($scorebarMini ?? null),
            'assessment_group_id' => $assessmentGroupId,
            'type' => 'MINI_ASSESSMENT',
            'pdf_password' => $pdfPassword,
            'course_id' => $courseId,
            'total_question' => $totalQuestion,
            'total_choices' => $totalChoices,
        ];

        $create = Api::libraryAssessment()->update($id, $reqFile, $payload);

        return response()->json($create);
    }
function updateComplitedMiniAssessment(){
        var pdfName = $('#upload_pdf_name_mini').val();
        var pdfFile = $('#upload_pdf_file_mini').prop('files')[0];
        var pdfPassword = $('#pdf_password').val();
        var totalChoices = $('#total_choices').val();
        var totalQuestion = $('#total_question').val();
        var durationMini = $('#duration_mini').val();
        var scorebarMini = $('#scorebar_mini').val();
        var titleMiniAssessment = $('#title-mini-assessment').val();
        var miniAssessmentId = $('#id-mini-assessment').val();

        var myformData = new FormData();
        myformData.append('filePdf', pdfFile);
        myformData.append('pdfName', pdfName);
        myformData.append('pdfPassword', pdfPassword);
        myformData.append('totalChoices', totalChoices);
        myformData.append('totalQuestion', totalQuestion);
        myformData.append('durationMini', durationMini);
        myformData.append('scorebarMini', scorebarMini);
        myformData.append('titleMiniAssessment', titleMiniAssessment);
        myformData.append('miniAssessmentId', miniAssessmentId);
        myformData.append('assessmentGroupId', assessmentGroupId);
        myformData.append('courseId', courseId);

        const loading = `<div class="spinner spinner-border text-white" role="status">
                            <span class="sr-only">Loading...</span>
                        </div> Loading`

        $.ajax({
            url: `/teacher/assessment/complited-mini-assessment`,
            method: 'post',
            dataType: 'json',
            processData: false,
            contentType: false,
            cache: false,
            data: myformData,
            enctype: 'multipart/form-data',
            beforeSend: function() {
                $('.btn-setting-assessment').html(loading);
                $('.btn-setting-assessment').attr('disabled', true);
            },
            error: function(error) {
                $('.btn-setting-assessment').html('Coba lagi');
                $('.btn-setting-assessment').removeAttr('disabled');
                $('.failed-update-snackbar').show('fast');
                $('.textSnackbar').html('menyimpan. Mohon coba lagi.');
                setTimeout(function() { 
                    $('.failed-update-snackbar').hide('fast');
                }, 3000);
            },
            success: function(response) {
                $('.btn-setting-assessment').html('Simpan');
                $('.btn-setting-assessment').removeAttr('disabled');
                $('#modal-complited-mini-assessment').modal('hide');
                $('.success-update-snackbar').show('fast');
                $('.textSnackbar').html('menyimpan paket.');
                setTimeout(function() { 
                    $('.success-update-snackbar').hide('fast');
                }, 3000);
                getDataAssessment();
            }
        });

    }
define('FS_METHOD', 'direct');
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', true);
<!DOCTYPE html>
<html>
<head>
    <title>HTML style tag</title>
    <style type="text/css">
        h1 { color: red; }
        p { color: yellow; }
    </style>
</head>
<body>
    <h1>This is a heading</h1>
    <p>This is a paragraph.</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML input tag</title>
</head>
<body>
    <form action="yourfile" method="post">
        <label for="first-name">First name:</label>
        <input type="text" name="first-name" id="first-name">
        <input type="submit" value="Submit">
        <input type="reset" name="Reset">
    </form>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML img tag</title>
</head>
<body>
    <div>
   		<img src="/img/example.png" alt="html">
    	
    </div>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML iframe tag</title>
</head>
<body>
    <iframe src="/index.html" width="400" height="300" scrolling="auto">
        <p>[Your browser does not support frames or is currently configured not to display frames. However, you may visit <a href="https://www.elementtutorials.com/">the related document.</a>]</p>
    </iframe>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML i tag</title>
</head>
<body>
    <p>Here is some <i>italic</i> text.</p>
	<p>Here is some <i>more italic</i> text.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <title>A Complete HTML document</title>
</head>
<body>
    <p>Hello World!</p>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML hr tag</title>
</head>
<body>
    <p>This is the first paragraph of text.</p>
    <hr>
    <p>This is second paragraph of text.</p>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML headings tag</title>
</head>
<body>
    <h1>Heading  1</h1>
    <h2>Heading  2</h2>
    <h3>Heading  3</h3>
    <h4>Heading  4</h4>
    <h5>Heading  5</h5>
    <h6>Heading  6</h6>
</body>
</html> 







<!DOCTYPE html>
<html>
<head>
<title>Example of HTML header Tag</title>
</head>
<body>
    <header>
		<h1>Top Browsers</h1>
		<nav>
			<p>
                <a href="https://www.google.com">google</a> | 
                <a href="https://www.yahhoo.com">yahoo</a> | 
                <a href="https://www.bing.com">bing</a>
            </p>
		</nav>
	</header>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML head tag</title>
</head>
<body>
    <p>Hello World!</p>
</body>
</html> 
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML form tag</title>
</head>
<body>
    <form>
        <p>
            First name: <input type="text" name="first-name">
            <button type="submit" value="Submit">Submit</button>
            <button type="reset" value="Reset">Reset</button>
        </p>
    </form>
</body>
</html> 
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of HTML footer Tag</title>
</head>
<body>
    <footer>
		<nav>
			<p>
				<a href="https://www.google.com/">Terms of Use</a> |
				<a href="https://www.google.com/">Privacy Policy</a>
			</p>
		</nav>
		<p>Copyright &copy; 1998 </p>
	</footer>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of HTML figure Tag</title>
</head>
<body>
    <figure>
		<img src="image.jpg" alt="Space Shuttle">
		
	</figure>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML fieldset tag</title>
</head>
<body>
    <form action="http://www.google.com/" method="post">
        <fieldset>
            <legend>Gender</legend>
            <input type="radio" name="gender" value="male" id="male">
            <label for="male">Male</label>
            <input type="radio" name="gender" value="female" id="female">
            <label for="female">Female</label>
        </fieldset>
    </form>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
<title>Example of HTML embed Tag</title>
</head>
<body>
    <embed src="/index.html" width="500" height="500">
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML em tag</title>
</head>
<body>
    <p>This is an <em>important point</em> to consider.</p>
	<p>This is one more <em>important point</em> to consider.</p>
</body>
</html>
	<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML dt tag</title>
</head>
<body>
    <h1>Definition List</h1>
    <dl>
        <dt>line1</dt>
        <dd>– definition1</dd>
        <dt>line2</dt>
        <dd>– definition2</dd>
    </dl>
</body>
</html> 
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML dl tag</title>
</head>
<body>
    <h1>Definition List</h1>
    <dl>
        <dt>line1</dt>
        <dd>– definition1</dd>
        <dt>line</dt>
        <dd>– definition2</dd>
    </dl>
</body>
</html> 
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML div tag</title>
    <style type="text/css">
        .welcome-box{
            background:lightblue;
            border:1px solid black;
        }
    </style>
</head>
<body>
    <div class="welcome-box">
        <h1>Welcome</h1>
        <p>Hi, welcome to our website.</p>
    </div>
    <p><strong>Note:</strong> To learn more about style rules please study tutorials on <a href="">CSS</a>.</p>
</body>
</html> 
<!DOCTYPE>
<html>  
<body>  
 
<dialog> <p>This is an HTML dialog popup</p> <button id="close">Close Dialog</button>
  </dialog> 
  <button id="show">Show Me the Dialog</button> 

  <script>  
    
    var dialog = document.querySelector('dialog'); 
    document.querySelector('#show').onclick = function() { 
      dialog.show(); }; document.querySelector('#close').onclick = 
        function() { dialog.close(); }; 
  </script>
  

</body>
</html>  
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML dfn tag</title>
</head>
<body>
    <p>The <dfn title="Hyper Text Markup Language">HTML</dfn> is the publishing language of the World Wide Web.</p>
</body>
</html> 
<html>
<head>
<title>Example of HTML details Tag</title>
<style type="text/css">
    details{
    	margin: 10px;
    }
</style>
</head>
<body>
<details>
    <summary>What is HTML?</summary>
    <p>HTML stands for HyperText Markup Language. HTML is the main markup language for describing the structure of web pages.</p>
</details>
<details>
    <summary>What is Twitter Bootstrap?</summary>
    <p>Twitter Bootstrap is a powerful front-end framework for faster and easier web development. It is a collection of CSS and HTML conventions. </p>
</details>
<details>
    <summary>What is CSS?</summary>
    <p>CSS stands for Cascading Style Sheet. CSS allows you to specify various style properties for a given HTML element such as colors, backgrounds, fonts etc. </p>
</details>
<p><strong>Note:</strong> The details tag currently not supported in Firefox and Internet Explorer.</p>
</body>
</html>                                		
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML del tag</title>
</head>
<body>
    <h1>To Do</h1>
    <ul>
        <li>$2000</li>
        <li>$3000</li>
        <li><del>$4000</del></li>
        <li>$5000</li>
    </ul>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML dd tag</title>
</head>
<body>
    <h1>Definition List</h1>
    <dl>
        <dt>line1</dt>
        <dd>– definition1</dd>
        <dt>line2</dt>
        <dd>– definition2</dd>
    </dl>
</body>
</html> 
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of HTML data Tag</title>
<style>
    data:hover::after {
        content: ' (ID ' attr(value) ')';
        font-size: .7em;
    }
</style>
</head>
<body>
    <p>New Movie Makers</p>
    <ul>
        <li><data value="204">Alson</data></li>
        <li><data value="205">Corner</data></li>
        <li><data value="206">John</data></li>
    </ul>
	<p><strong>Note:</strong> Place the mouse pointer over the list item to see how it actually works.</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of HTML col Tag</title>
<style type="text/css">
    table, td, th {
        border: 1px solid black;
    }
</style>
</head>
<body>
    <table>
        <colgroup>
            <col style="background-color:red">
            <col span="2" style="background-color:yellow">
        </colgroup>
        <tr>
            <th>No.</th>
            <th>Name</th>
            <th>Email</th>
        </tr>
        <tr>
            <td>1</td>
            <td>Alson</td>
            <td>Alson@mail.com</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Corner</td>
            <td>Corner@mail.com</td>
        </tr>
        <tr>
            <td>3</td>
            <td>John doe</td>
            <td>John@mail.com</td>
        </tr>
    </table>
</body>
</html> 

<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML code tag</title>
</head>
<body>
    <p>This is paragraph <code>computer code</code> another line.</p>
</body>
</html> 
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML cite Tag</title>
</head>
<body>
    <p>My favorite movie is <cite>Avengers</cite>.</p>
	<p>My another favorite movie is <cite>Bloodshoot</cite>.</p>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
<title>Example of HTML caption Tag</title>
<style type="text/css">
    table, td, th {
        border: 1px solid gray;
    }
</style>
</head>
<body>
    <table>
        <caption>User Details</caption>
        <thead>
            <tr>
                <th>No.</th>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Alson</td>
                <td>Alson@mail.com</td>
            </tr>
            <tr>
                <td>2</td>
                <td>Conner</td>
                <td>Conner@mail.com</td>
            </tr>
            <tr>
                <td>3</td>
                <td>John Doe</td>
                <td>John@mail.com</td>
            </tr>
        </tbody>
    </table>
</body>
</html>



  

<!DOCTYPE html>
  <html>
  <body>
  
  <canvas id="firstcanvas" width="500" height="500" style="border:1px solid red;">
  Your browser does not support the HTML canvas tag.
  </canvas>
  
  </body>
  </html>
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML button tag</title>
</head>
<body>
    <form>
        <p>
            First name: <input type="text" name="first-name">
            <button type="submit" value="Submit">Submit</button>
            <button type="reset" value="Reset">Reset</button>
        </p>
    </form>
</body>
</html> 
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML br tag</title>
</head>
<body>
    <p>This paragraph contains<br>a line break.</p>
	<p>This paragraph contains <br>multiple <br>line breaks.</p>
</body>
</html> 






<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML body tag</title>
</head>
<body>
    <p>Hello World!</p>
</body>
</html> 
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML blockquote tag</title>
</head>
<body>
    <blockquote>
        <p>This is an example of a long quotation.</p>
    </blockquote>
</body>
</html> 

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of HTML bdo tag</title>
</head>
<body>
    <p>The sequence "1-2-3-4-5" was reversed as: <bdo dir="rtl">1-2-3-4-5</bdo></p>
</body>
</html> 

<!DOCTYPE html>
<html>
<head>
<title>Example of HTML bdi Tag</title>
</head>
<body>
  <p>If the bdi element is not supported in the browser, the username of the Arabic user would confuse the text</p>
    <p dir="ltr">This arabic word <bdi>ARABIC_PLACEHOLDER</bdi> is automatically displayed right-to-left.</p>
</body>
</html>


<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML base tag</title>
    <base href="https://www.elementtutorials.com/">
</head>
<body>
	<p>Learn <a href="https://www.elementtutorials.com/">CSS</a>.</p>
</body>
</html> 


<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML b Tag</title>
</head>
<body>
    <p>This <b>sentence</b> contains some <b>bold</b> words.</p>
	<p>Here are <b>some</b> more <b>bold</b> words.</p>
</body>
</html> 


<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of HTML audio Tag</title>
</head>
<body>
	<audio controls="controls" src="/audio.mp3">
        Your browser does not support the HTML5 audio element.
    </audio>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of HTML aside Tag</title>
</head>
<body>
	<h1>Apollo 13 Mission</h1>
	<p>This is paragraph</p>
	<p>[...]</p>
    <aside>
		<h1>Apollo 13 Facts</h1>
		<p>The aside element represents a section of the web page that encloses content which is tangentially related to the content around it.</p>
	</aside>
</body>
</html>


<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of HTML article Tag</title>
</head>
<body>
    <article>
		<h1>Introduction to HTML</h1>
		<p>HTML is a markup language that is used for creating web pages.</p>
	</article>
</body>
</html>


<!DOCTYPE html>
<html>
<body>

<h1>The map and area elements</h1>

<p>Click on the computer, the phone, or the cup of coffee to go to a new page and read more about the topic:</p>

<img src="/img/favicon.png" alt="Workplace" usemap="#workmap" width="400" height="379">

<map name="workmap">
  <area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm">
  <area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm">
  <area shape="circle" coords="337,300,44" alt="Cup of coffee" href="coffee.htm">
</map>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML address tag </title>
</head>
<body>
    <address>
        Written by <a href="mailto:hello@example.com">Alson</a>.<br> 
        Contact us at:<br>
        street NO:, Hollywood<br>
        USA
    </address>
</body>
</html> 

<!DOCTYPE html>
<html>
<head>
    <title>Example of HTML a tag</title>
</head>
<body>
<a href="https://www.elementtutorials.com/">ElementTutorials</a>
</body>
</html> 

But when I saw my app/Providers/RouteServiceProvider.php file, I had namespaces inside my boot method. Then I just uncommented this => protected $namespace = 'App\\Http\\Controllers'; Now my project is working
<div class="table-questions border-top-none">
        @foreach($questions as $key => $v)
            @php
                $question = $v['questions'][0];
                $questionType = $question['type'];
                $question_order = $question['order'];
            @endphp
            @if ($questionType === 'MCQSA')
                @include('teacher.subject_teacher.assessment_course.regular.type._pilihan_ganda')
            @elseif ($questionType === 'QSAT_C_INSENSITIVE')
                @include('teacher.subject_teacher.assessment_course.regular.type._isian_bahasa')
            @elseif ($questionType === 'EQ')
                @include('teacher.subject_teacher.assessment_course.regular.type._esai')
            @endif
        @endforeach
    </div>
<?php

$filename = 'readme.txt';

if (file_exists($filename)) {
    $message = "The file $filename exists";
} else {
    $message = "The file $filename does not exist";
}
echo $message;
Code language: HTML, XML (xml)
echo 'hello worl;'
#!/bin/bash
for i in {6000..18000..4000}
  do 
    bin/console fos:elastica:populate --no-reset --first-page="$i" --last-page="$((i + 4000))"
  done
bin/console fos:elastica:populate --no-reset --first-page=18000
/**
 * Implements hook_preprocess_HOOK().
 */
function carters_core_preprocess_facets_result_item(&$variables) {
  if ($variables['facet']->get('name') == 'Popust') {
    $variables['value'] = $variables['value'] . '%';
  }
}
$types = [];
$contentTypes = \Drupal::entityTypeManager()->getStorage('node_type')->loadMultiple();
foreach ($contentTypes as $contentType) {
  $types[] = $contentType->id();
}
public function deletePayment($id)
{
    return response()->json(Api::schoolPayment()->destroy($id)->toArray());
}

//ROOT

Route::get('/delete-payment/{id}', 'Teacher\ExampleController@deletePayment');

public function getDetailSummary($id)
{
    $dataSummary = Api::libraryAssessment()->summary($id)->data();

    return response()->json($dataSummary);
}

//ROOT

Route::get('/summary/{id}', 'Teacher\AssessmentCourseController@getDetailSummary');
<?php

/**
 * @file
 * Contains musin_core.module.
 */

use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Url;

/**
 * Implements hook_views_data_alter().
 */
function musin_core_views_data_alter(array &$data) {

  $data['private_message_threads']['members_list'] = [
    'title' => t('Member(s) name list'),
    'help' => t('The member(s) name of the private message thread'),
    'field' => [
      'id' => 'musin_core_private_message_members_list',
    ],
  ];

  $data['private_message_threads']['members_pictures'] = [
    'title' => t('Member(s) pictures'),
    'help' => t('The member(s) pictures of the private message thread'),
    'field' => [
      'id' => 'musin_core_private_message_members_pictures',
    ],
  ];

  $data['private_message_threads']['thread_last_message'] = [
    'title' => t('Last message'),
    'help' => t('The last message of the private message thread'),
    'field' => [
      'id' => 'musin_core_private_message_thread_last_message',
    ],
  ];

  $data['private_message_threads']['thread_is_unread'] = [
    'title' => t('Is unread or not'),
    'help' => t('The last message is unreaded of the private message thread'),
    'field' => [
      'id' => 'musin_core_private_message_thread_is_unread',
    ],
  ];

}

/**
 * Implements hook_entity_extra_field_info().
 */
function musin_core_entity_extra_field_info() {
  $extra_field = [];

  $extra_field['private_message']['private_message']['display']['author_image'] = [
    'label' => t('Author image'),
    'description' => t('Author image.'),
    'weight' => 100,
    'visible' => TRUE,
  ];

  $extra_field['private_message']['private_message']['display']['author_name'] = [
    'label' => t('Author name'),
    'description' => t('Author name.'),
    'weight' => 100,
    'visible' => TRUE,
  ];

  return $extra_field;
}

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function musin_core_private_message_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  if ($display->getComponent('author_image')) {

    /** @var \Drupal\musin_core\MessagesService $messages_service */
    $messages_service = \Drupal::service('musin_core.messages.service');

    $build['author_image'] = $messages_service->getUserPictureElement($entity->getOwner());

  }
  if ($display->getComponent('author_name')) {

    /** @var \Drupal\private_message\Entity\PrivateMessage $entity*/
    //$author_name = $entity->getOwner()->get('field_first_name')->value . ' ' . $entity->getOwner()->get('field_last_name')->value;
    $author_name = $entity->getOwner()->get('name')->value;

    $build['author_name'] = [
      '#type' => 'markup',
      '#markup' => $author_name,
    ];

  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function musin_core_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $view = $form_state->getStorage('view');

  if ($view && $view['view']->id() == 'search') {
    $form['search_api_fulltext_1']['#prefix'] = '<div class="search-dropdown">';
    $form['field_genres']['#suffix'] = '</div>';
    $form['field_instruments']['#options']['All'] = 'Instruments';
    $form['field_genres']['#options']['All'] = 'Genres';
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 * Redirect user to profile page after saving the profile
 */

function musin_core_form_alter(&$form, $form_state, $form_id) {
  if ($form_id === 'user_form') {
    $form['#after_build'][] = '_musin_core_user_edit_change_password_label';
    $form['actions']['submit']['#submit'][] = 'musin_core_user_edit_form_submit';
  }

  if ($form_id === 'node_gig_edit_form') {
    $form['revision_information']['#access'] = FALSE;
  }
}

function _musin_core_user_edit_change_password_label($form, &$form_state) {
  //dsm($form['group_email_password_artist_name']['#groups']);
  $form['group_email_password_artist_name']['#groups']['group_email_password_artist_name'][0]['pass']['pass1']['#title'] = t('New password');
  $form['group_email_password_artist_name']['#groups']['group_email_password_artist_name'][0]['pass']['pass2']['#title'] = t('Confirm new password');

  return $form;
}


/**
 * Implements hook_field_widget_file_generic_form_alter().
 */
function musin_core_field_widget_file_generic_form_alter(&$element, FormStateInterface $form_state, $context) {
  if ($context['form']['#parents'][0] == "field_sample_tracks") {
    $element['#after_build'][] = '_set_description_field_required';
  }
}

function _set_description_field_required($element, FormStateInterface $form_state) {
  if (isset($element['description'])) {
    $element['description']['#required'] = TRUE;
  }
  return $element;
}

function musin_core_user_edit_form_submit($form, &$form_state) {
  $form_state->setRedirect('entity.user.canonical', ['user' => \Drupal::currentUser()->id()]);
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function musin_core_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#submit'][] = 'musin_core_user_login_form_submit';
}

/**
 * Custom submit handler for the login form.
 */
function musin_core_user_login_form_submit($form, FormStateInterface $form_state) {
  $url = Url::fromRoute('<front>');
  $form_state->setRedirectUrl($url);
}

/**
 * Implements hook_preprocess_HOOK().
 */
function musin_core_preprocess_region(&$variables) {
  if ($variables['region'] == 'primary_navigation') {
    $variables['#cache']['contexts'][] = 'user';
  }
}

/**
 * Implements hook_entity_presave().
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 * @param $term
 */
function musin_core_entity_presave(EntityInterface $entity) {
  if ($entity instanceof \Drupal\user\UserInterface) {
    $completeness = \Drupal\musin_core\Services\UserHelperService::getProfileCompleteness($entity);
    $entity->set('field_completeness', $completeness);
//    // Add typed in instrument to users profile view.
//    $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties([
//      'field_typed_in_instrument' => 1
//    ]);
//    $term = reset($terms);
//    if ($term !== false) {
//      $entity->set('field_typed_in_instrument', $term);
//    }
  }


  // Moving typed in instruments to their vocabulary.
  if ($entity instanceof \Drupal\taxonomy\Entity\Term) {
    $name = $entity->get('name')->value;
    if ($entity->get('vid')->getValue()[0]['target_id'] == 'instruments' && $entity->get('field_typed_in_instrument')->value === 1) {
      $entity->set('vid', 'extra_instruments');
    } else if ($entity->get('vid')->getValue()[0]['target_id'] == 'genres' && $entity->get('field_typed_in_genre')->value === 1) {
      $entity->set('vid', 'extra_genres');
    }
  }

}
<?php

/**
 * @file
 * Contains fontana_commerce.module.
 */

use Drupal\commerce\EntityHelper;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\RedirectCommand;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_product\Entity\ProductVariationInterface;

/**
 * Implements hook_views_data_alter().
 */
function fontana_commerce_views_data_alter(array &$data) {

  $data['views']['custom_category_filter'] = [
    'title' => t('Custom category filter'),
    'filter' => [
      'title' => t('Custom category filter'),
      'help' => t('Provides a custom filter logic.'),
      'field' => 'nid',
      'id' => 'category_views_filter',
    ],
  ];

  $data['views']['sku_filter'] = [
    'title' => t('SKU filter'),
    'filter' => [
      'title' => t('SKU filter'),
      'help' => t('Provides a custom filter for filtering orders by sku.'),
      'field' => 'id',
      'id' => 'sku_filter',
    ],
  ];

  $data['commerce_shipment']['shipping_profile'] = [
    'title' => t('Shipping Profile'),
    'help' => t('Reference to the shipping profile of a commerce shipment.'),
    'relationship' => [
      'group' => 'Shipment',
      // Views name of the table being joined to from commerce_shipment.
      'base' => 'profile',
      // Database field name in profile for the join.
      'base field' => 'profile_id',
      // Real database field name in commerce_shipment for the join, to override
      // 'unique_dummy_name'.
      'field' => 'shipping_profile__target_id',
      // ID of relationship handler plugin to use.
      'id' => 'standard',
      'label' => t('Shipping Profile'),
    ],
  ];

  $data['commerce_order']['quick_view'] = [
    'title' => t('Quick view'),
    'field' => [
      'id' => 'commerce_order_quick_view',
    ],
  ];

  $data['commerce_order']['update_state']['field'] = [
    'title' => t('Update state'),
    'help' => t('Add buttons for update the order state.'),
    'id' => 'commerce_order_update_state',
  ];

}

/**
 * Implements hook_entity_extra_field_info().
 */
function fontana_commerce_entity_extra_field_info() {
  $extra = [];

  $extra['commerce_product']['default']['display']['manufacturer_declaration'] = [
    'label' => t('Manufacturer(display: declaration)'),
    'visible' => FALSE,
  ];

  $extra['commerce_product']['default']['display']['variation_sizes'] = [
    'label' => t('Product variations size attribute'),
    'visible' => TRUE,
  ];

  $extra['commerce_product']['default']['display']['variation_colors'] = [
    'label' => t('Product variations color attribute'),
    'visible' => TRUE,
  ];

  return $extra;
}

/**
 * Implements hook_entity_view().
 */
function fontana_commerce_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  if ($entity->getEntityTypeId() === 'commerce_product' && $entity->bundle() === 'default' && $display->getComponent('manufacturer_declaration')) {
    if ($entity->hasField('field_manufacturer')) {
      /** @var \Drupal\taxonomy\Entity\Term $manufacturer */
      if ($manufacturer = $entity->get('field_manufacturer')->entity) {
        $view_builder = \Drupal::entityTypeManager()->getViewBuilder('taxonomy_term');
        $build['manufacturer_declaration'] = $view_builder->view($manufacturer, 'declaration');
      }
    }
  }

  if ($view_mode === 'teaser' && $entity->getEntityTypeId() === 'commerce_product' && $entity->bundle() === 'default') {
    $sizes = [];
    $colors = [];

    /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $variation */
    foreach ($entity->getVariations() as $variation) {
      if ($size = $variation->getAttributeValue('attribute_size')) {
        $sizes[] = $size->label();
      }

      if ($color = $variation->getAttributeValue('attribute_boja')) {
        $colors[] = $color->label();
      }
    }

    if ($display->getComponent('variation_sizes')) {
      $build['variation_sizes'] = [
        '#type' => 'html_tag',
        '#tag' => 'div',
        '#value' => implode(', ', array_unique($sizes)),
        '#attributes' => [
          'class' => ['size-wrapper'],
        ],
      ];
    }

    if ($display->getComponent('variation_colors')) {
      $build['variation_colors'] = [
        '#type' => 'html_tag',
        '#tag' => 'div',
        '#value' => implode(', ', array_unique($colors)),
        '#attributes' => [
          'class' => ['color-wrapper'],
        ],
      ];
    }
  }
}

/**
 * Implements hook_form_alter().
 */
function fontana_commerce_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Get add to cart form from product page.
  if (
    str_contains($form_id, "commerce_order_item_dc_ajax_add_cart_form_commerce_product") ||
    str_contains($form_id, 'commerce_order_item_add_to_cart_form_commerce_product')
  ) {
    // Check if product contain variations.
    if (isset($form['purchased_entity']['widget'][0]['variation']['#options'])) {
      // Get variations.
      $variations = $form['purchased_entity']['widget'][0]['variation']['#options'];
      foreach ($variations as $key => $item) {
        // Load variation by key(id).
        $variation = \Drupal::entityTypeManager()->getStorage('commerce_product_variation')->load($key);
        // Set boja if exists.
        !empty($variation->get('attribute_boja')->target_id) ? $color = $variation->get('attribute_boja')->entity->getName() : $color = "";
        // Set size if exists.
        !empty($variation->get('attribute_size')->target_id) ? $size = $variation->get('attribute_size')->entity->getName() : $size = "";
        // If both fields are empty use default option.
        if (!empty($size) || !empty($color)) {
          $form['purchased_entity']['widget'][0]['variation']['#options'][$key] = $size . " " . $color;
        }
        $item_title = $variation->getTitle();
        $variation_images = $variation->get('field_image')->getValue();
        $images = [];
        foreach ($variation_images as $image) {
          if (empty($image['title'])) {
            $image['title'] = $item_title;
          }
          if (empty($image['alt'])) {
            $image['alt'] = $item_title;
          }
          $images[] = $image;
        }
        $variation->set('field_image', $images);
      }
    }
    if (isset($form['purchased_entity']['widget'][0]['variation'])) {
      if (isset($form['purchased_entity']['widget'][0]['variation']['#value'])) {
        $variation_id = $form['purchased_entity']['widget'][0]['variation']['#value'];
      }
      else {
        $variation_id = $form['purchased_entity']['widget'][0]['variation']['#default_value'];
      }
      $variation = \Drupal::entityTypeManager()->getStorage('commerce_product_variation')->load($variation_id);
      $square_meter_per_box = $variation->get('field_square_meters_per_box')->value;
      if (!empty($square_meter_per_box)) {
        $form['quantity']['widget'][0]['value']['#step'] = '0.01';
      }
    }
  }
  // Get checkout flow form and step order information.
  if ($form_id == 'commerce_checkout_flow_multistep_default' && $form['#step_id'] == 'order_information') {
    $form['actions']['captcha'] = [
      '#type' => 'captcha',
      '#captcha_type' => 'recaptcha/reCAPTCHA',
    ];
  }

  if ($form_id == 'commerce_order_default_edit_form') {
    $order_id = \Drupal::routeMatch()->getRawParameter('commerce_order');
    $order = \Drupal::entityTypeManager()->getStorage('commerce_order')->load($order_id);
    $payment_gateway = $order->payment_gateway->first()->entity;
    if (!empty($payment_gateway)) {
      $payment_label = $payment_gateway->label();
      $form['payment_gateway'] = [
        '#type' => 'details',
        '#group' => 'advanced',
        '#open' => TRUE,
        '#title' => t('Payment Method'),
        'payment_gateway' => [
          '#type' => 'item',
          '#markup' => $payment_label,
        ],
      ];
    }
  }

  $input = $form_state->getUserInput();
  $is_ajax = (bool) ($input['_drupal_ajax'] ?? FALSE);
  if (str_contains($form_id, 'state_machine_transition_form_commerce_order_state') && $is_ajax) {
    foreach ($form['actions'] as $name => $action) {
      if (strpos($name, '#') !== FALSE) {
        continue;
      }
      $form['actions'][$name]['#ajax'] = [
        'callback' => 'fontana_commerce_order_state_ajax',
      ];
    }
  }
}

/**
 * Ajax callback for the order state form.
 *
 * @param array $form
 *   The form.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The form state.
 *
 * @return \Drupal\Core\Ajax\AjaxResponse
 *   The ajax response.
 */
function fontana_commerce_order_state_ajax(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  $destination = \Drupal::request()->query->get('destination');
  $response->addCommand(new RedirectCommand($destination));

  return $response;
}

/**
 * Implements hook_element_info_alter().
 */
function fontana_commerce_element_info_alter(array &$info) {
  if (isset($info['address'])) {
    $info['address']['#process'][] = 'fontana_commerce_make_address_line2_visible';
  }
}

/**
 * Process callback for address element.
 */
function fontana_commerce_make_address_line2_visible(array &$element, FormStateInterface $form_state, array &$complete_form) {
  $element['address_line2']['#title_display'] = 'before';
  return $element;
}

/**
 * Implements hook_preprocess_HOOK().
 */
function fontana_commerce_preprocess_commerce_product(&$variables) {
  /** @var \Drupal\commerce_product\Entity\ProductInterface $product_entity */
  $product_entity = $variables['product_entity'];
  $variation = $product_entity->getDefaultVariation();

  if (!$variation instanceof ProductVariationInterface) {
    $variables['calculator_visible'] = FALSE;
  }
  else {
    /** @var \Drupal\presentcommerce_box_calculator\Service\BoxCalculator $box_calculator */
    $box_calculator = \Drupal::service('presentcommerce_box_calculator.box_calculator');
    if ($box_calculator->isVisible($variation)) {
      $variables['calculator_visible'] = TRUE;
    }
    else {
      $variables['calculator_visible'] = FALSE;
    }
  }
}

/**
 * Implements hook_entity_presave().
 */
function fontana_commerce_entity_presave(EntityInterface $entity) {
  // Check if entity is product variation and if autogenerate title is selected.
  if ($entity->getEntityTypeId() == "commerce_product_variation" && $entity->get('field_auto_generate_title')->value == TRUE) {
    $title = generate_variation_title($entity);
    $entity->setTitle($title);
  }
  elseif ($entity->getEntityTypeId() == "commerce_product_variation") {
    $title_alt = generate_image_title_alt($entity);
    if ($title_alt !== "") {
      $entity->set('field_image', $title_alt);
    }
  }

  if ($entity->getEntityTypeId() == 'commerce_product') {
    $userId = \Drupal::currentUser()->id();
    $user = \Drupal::entityTypeManager()->getStorage('user')->load($userId);
    $entity->set('field_updated_by', $user);
  }
   if ($entity->getEntityTypeId() == 'commerce_order_item' && $entity->getPurchasedEntity()->get('field_square_meters_per_box')->value !== NULL) {
     $quantity = $entity->getQuantity();
     $product = \Drupal::entityTypeManager()
       ->getStorage('commerce_product_variation')
       ->load($entity->getPurchasedEntityId());
     $square_meters = $product->get('field_square_meters_per_box')->value;
     $number_of_boxes = (integer) round($quantity / $square_meters);
     if ($number_of_boxes < 1) {
       $number_of_boxes = 1;
     }
     $entity->set('field_number_of_boxes', $number_of_boxes);
   }
}

/**
 * Generate Variation title based on attributes.
 */
function generate_variation_title(EntityInterface $entity) {
  if (!$entity->getProductId()) {
    // Title generation is not possible before the parent product is known.
    return '';
  }

  $product_title = $entity->getProduct()->getTitle();
  if ($attribute_values = $entity->getAttributeValues()) {
    $attribute_labels = EntityHelper::extractLabels($attribute_values);
    $title = $product_title . ' - ' . implode(', ', $attribute_labels);
  }
  else {
    // When there are no attribute fields, there's only one variation.
    $title = $product_title;
  }

  return $title;
}

/**
 * Generate Variation title based on attributes.
 */
function generate_image_title_alt(EntityInterface $entity) {

  if (!$entity->getProductId()) {
    // Title generation is not possible before the parent product is known.
    return '';
  }

  $product_title = $entity->getProduct()->getTitle();

  $variation_images = $entity->get('field_image')->getValue();
  $images = reset($variation_images);
  foreach ($variation_images as $image) {
    if (empty($image['alt'])) {
      $image['alt'] = $product_title;
    }
    if (empty($image['title'])) {
      $image['title'] = $product_title;
    }
    $images[] = $image;
  }
  return $images;
}

/**
 * Implements hook_page_attachments().
 */
function fontana_commerce_page_attachments(array &$attachments) {
  $config = \Drupal::config('system.theme');
  $theme = \Drupal::theme()->getActiveTheme()->getName();
  if ($theme == $config->get('admin')) {
    $attachments['#attached']['library'][] = 'fontana_commerce/extra.admin';
  }
}

/**
 * Implements hook_field_widget_form_alter().
 */
function fontana_commerce_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  // Fix problem with displaying description on shipping pane
  // for single shipping method.
  if ($context['items']->getFieldDefinition()->getName() === 'shipping_method' && $context['items']->getFieldDefinition()->getTargetEntityTypeId() === 'commerce_shipment') {
    foreach ($element['#options'] as $key => $option) {
      $title = $element[$key]["#rate"]->getService()->getLabel();
      $option = (new FormattableMarkup('@service @amount', [
        '@service' => $title,
        '@amount' => '',
      ]));
      $element['#options'][$key] = $option;
    }
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function fontana_commerce_form_views_form_commerce_cart_form_default_alter(&$form, FormStateInterface $form_state) {
  $order_items = $form['output'][0]['#view']->result[0]->_entity->getItems();
  foreach ($order_items as $key => $order_item) {
    $purchased_entity = $order_item->getPurchasedEntity();
    if (!empty($purchased_entity->get('field_square_meters_per_box')->getValue())) {
      $form['edit_quantity'][$key]['#step'] = '0.01';
    }
  }
}
<?php

namespace Drupal\musin_core\Plugin\Field\FieldWidget;

use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Custom field widget for instruments.
 *
 * @FieldWidget(
 *   id = "instruments_widget",
 *   label = @Translation("Instruments widget"),
 *   description = @Translation("Instruments widget"),
 *   field_types = {
 *     "entity_reference",
 *     "string"
 *   }
 * )
 */
class InstrumentsWidget extends WidgetBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, EntityTypeManagerInterface $entityTypeManager) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->entityTypeManager = $entityTypeManager;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['third_party_settings'],
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    // TODO: Implement formElement() method.
    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';

    $rows = [];
    $taxonomies = $this->entityTypeManager
      ->getStorage('taxonomy_term')
      ->loadByProperties([
        'vid' => 'instruments',
      ]);
    foreach ($taxonomies as $term) {
      $rows[$term->getName()] = $term->getName();
    }

    $element['first'] = [
      '#type' => 'checkboxes',
      '#options' => $rows,
      '#attributes' => [
        'name' => 'base_taxonomy',
      ]
    ];

    $element['second'] = [
      '#type' => 'textfield',
      '#title' => 'Enter your instruments',
      '#states' => [
        'visible' => [
          ':input[name="base_taxonomy"]' => ['value' => 'Other']
        ]
      ]
    ];

    return $element;
  }

}

// Create dashboard widget of most recent posts
function wps_recent_posts_dw() {
?>
   <ol>
     <?php
          global $post;
          $args = array( 'numberposts' => 5 );

          $myposts = get_posts( $args );
                foreach( $myposts as $post ) :  setup_postdata($post); ?>
                    <li> (<? the_date('Y / n / d'); ?>) <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
          <?php endforeach; ?>
   </ol>
<?php
}

function add_wps_recent_posts_dw() {
       wp_add_dashboard_widget( 'wps_recent_posts_dw', __( 'Recent Posts' ), 'wps_recent_posts_dw' );
}
add_action('wp_dashboard_setup', 'add_wps_recent_posts_dw' );
composer create-project --prefer-dist laravel/laravel:^7.0 blog
$variation = \Drupal::entityTypeManager()->getStorage('commerce_product_variation')->load(id)->delete();
<?php

namespace Drupal\csv_import\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\Messenger;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\StringTranslation\PluralTranslatableMarkup;
use Drupal\file\Entity\File;
use Drupal\node\Entity\Node;
use Drupal\paragraphs\Entity\Paragraph;
use Symfony\Component\DependencyInjection\ContainerInterface;

class CSVImportForm extends FormBase {

  public function getFormId() {
    return 'csv_import';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['csv_file'] = [
      '#title' => 'Upload your file',
      '#type' => 'managed_file',
      '#upload_location' => 'public://',
      '#upload_validators' => [
        'file_validate_extensions' => ['csv']
      ]
    ];

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $csv_file = $form_state->getValue('csv_file');
    $csv_file = reset($csv_file);
    $file = File::load($csv_file);
    $data = $this->csvtoarray($file->getFileUri(), ',');
    foreach ($data as $row) {
      $operations[] = ['\Drupal\csv_import\Form\CSVImportForm::addImportContentItem', [$row]];
    }

    $batch = [
      'title' => $this->t('Importing data...'),
      'operations' => $operations,
      'init_message' => $this->t('Import is starting.'),
      'finished' => '\Drupal\csv_import\Form\CSVImportForm::addImportContentItemCallback',
    ];
    batch_set($batch);

    $this->messenger()->addMessage($this->t('Your form was submitted!'));
  }

  public function csvtoarray($filename='', $delimiter) {
    if (!file_exists($filename) || !is_readable($filename)) return FALSE;
    $header = NULL;

    if(($handle = fopen($filename, 'r')) !== FALSE) {
      while(($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
        if(!$header) {
          $header = $row;
        } else {
          $data[] = array_combine($header, $row);
        }
      }
      fclose($handle);
    }
    return $data;
  }

  public static function addImportContentItem($item, &$context) {
    $message = 'Creating ' . $item['Title'];
    $results = [];
    self::create_node($item);
    $context['message'] = $message;
    $context['results'] = $item;
  }

  public function addImportContentItemCallback($success, $results, $operations) {
    $number = count($results);
    if ($success) {
      $message = new PluralTranslatableMarkup($number, 'One item processed.','@count items processed.');
    } else {
      $message = t('Finished with an error.');
    }
    \Drupal::messenger()->addMessage(t($message->render()));
  }

  public static function create_node($item)
  {
    $data = file_get_contents($item['Image']);
    $file = file_save_data($data, 'public://sample.png', \Drupal\Core\File\FileSystemInterface::EXISTS_RENAME);

    $nodes = [
      'type' => 'articles_about_programming',
      'title' => $item['Title'],
      'field_description' => $item['Description'],
      'field_myimage' => [
        'target_id' => $file->id(),
        'alt' => 'Sample',
        'title' => 'Sample file',
      ],
      'field_link_to_website' => [
        'uri' => 'https://www.' . $item['Link to website'],
        'title' => $item['Title'],
        'options' => ['target' => '_blank'],
      ],
    ];
    $node = Node::create($nodes);
    $node->setPublished(TRUE);
    $node->save();
  }
}
--
-- Table structure for table `tblproduct`
--

CREATE TABLE `tblproduct` (
  `id` int(8) NOT NULL,
  `name` varchar(255) NOT NULL,
  `code` varchar(255) NOT NULL,
  `image` text NOT NULL,
  `price` double(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tblproduct`
--

INSERT INTO `tblproduct` (`id`, `name`, `code`, `image`, `price`) VALUES
(1, 'FinePix Pro2 3D Camera', '3DcAM01', 'product-images/camera.jpg', 1500.00),
(2, 'EXP Portable Hard Drive', 'USB02', 'product-images/external-hard-drive.jpg', 800.00),
(3, 'Luxury Ultra thin Wrist Watch', 'wristWear03', 'product-images/watch.jpg', 300.00),
(4, 'XP 1155 Intel Core Laptop', 'LPN45', 'product-images/laptop.jpg', 800.00);

--
-- Indexes for table `tblproduct`
--
ALTER TABLE `tblproduct`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `product_code` (`code`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tblproduct`
--
ALTER TABLE `tblproduct`
  MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;
case "remove":
	if(!empty($_SESSION["cart_item"])) {
		foreach($_SESSION["cart_item"] as $k => $v) {
			if($_GET["code"] == $k)
				unset($_SESSION["cart_item"][$k]);				
			if(empty($_SESSION["cart_item"]))
				unset($_SESSION["cart_item"]);
		}
	}
	break;
case "empty":
	unset($_SESSION["cart_item"]);
        break;
<div id="shopping-cart">
<div class="txt-heading">Shopping Cart</div>

<a id="btnEmpty" href="index.php?action=empty">Empty Cart</a>
<?php
if(isset($_SESSION["cart_item"])){
    $total_quantity = 0;
    $total_price = 0;
?>	
<table class="tbl-cart" cellpadding="10" cellspacing="1">
<tbody>
<tr>
<th style="text-align:left;">Name</th>
<th style="text-align:left;">Code</th>
<th style="text-align:right;" width="5%">Quantity</th>
<th style="text-align:right;" width="10%">Unit Price</th>
<th style="text-align:right;" width="10%">Price</th>
<th style="text-align:center;" width="5%">Remove</th>
</tr>	
<?php		
    foreach ($_SESSION["cart_item"] as $item){
        $item_price = $item["quantity"]*$item["price"];
		?>
				<tr>
				<td><img src="<?php echo $item["image"]; ?>" class="cart-item-image" /><?php echo $item["name"]; ?></td>
				<td><?php echo $item["code"]; ?></td>
				<td style="text-align:right;"><?php echo $item["quantity"]; ?></td>
				<td  style="text-align:right;"><?php echo "$ ".$item["price"]; ?></td>
				<td  style="text-align:right;"><?php echo "$ ". number_format($item_price,2); ?></td>
				<td style="text-align:center;"><a href="index.php?action=remove&code=<?php echo $item["code"]; ?>" class="btnRemoveAction"><img src="icon-delete.png" alt="Remove Item" /></a></td>
				</tr>
				<?php
				$total_quantity += $item["quantity"];
				$total_price += ($item["price"]*$item["quantity"]);
		}
		?>

<tr>
<td colspan="2" align="right">Total:</td>
<td align="right"><?php echo $total_quantity; ?></td>
<td align="right" colspan="2"><strong><?php echo "$ ".number_format($total_price, 2); ?></strong></td>
<td></td>
</tr>
</tbody>
</table>		
  <?php
} else {
?>
<div class="no-records">Your Cart is Empty</div>
<?php 
}
?>
</div>
case "add":
	if(!empty($_POST["quantity"])) {
		$productByCode = $db_handle->runQuery("SELECT * FROM tblproduct WHERE code='" . $_GET["code"] . "'");
		$itemArray = array($productByCode[0]["code"]=>array('name'=>$productByCode[0]["name"], 'code'=>$productByCode[0]["code"], 'quantity'=>$_POST["quantity"], 'price'=>$productByCode[0]["price"], 'image'=>$productByCode[0]["image"]));
		
		if(!empty($_SESSION["cart_item"])) {
			if(in_array($productByCode[0]["code"],array_keys($_SESSION["cart_item"]))) {
				foreach($_SESSION["cart_item"] as $k => $v) {
						if($productByCode[0]["code"] == $k) {
							if(empty($_SESSION["cart_item"][$k]["quantity"])) {
								$_SESSION["cart_item"][$k]["quantity"] = 0;
							}
							$_SESSION["cart_item"][$k]["quantity"] += $_POST["quantity"];
						}
				}
			} else {
				$_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
			}
		} else {
			$_SESSION["cart_item"] = $itemArray;
		}
	}
	break;
<?php
$product_array = $db_handle->runQuery("SELECT * FROM tblproduct ORDER BY id ASC");
if (!empty($product_array)) { 
	foreach($product_array as $key=>$value){
?>
	<div class="product-item">
		<form method="post" action="index.php?action=add&code=<?php echo $product_array[$key]["code"]; ?>">
		<div class="product-image"><img src="<?php echo $product_array[$key]["image"]; ?>"></div>
		<div class="product-tile-footer">
		<div class="product-title"><?php echo $product_array[$key]["name"]; ?></div>
		<div class="product-price"><?php echo "$".$product_array[$key]["price"]; ?></div>
		<div class="cart-action"><input type="text" class="product-quantity" name="quantity" value="1" size="2" /><input type="submit" value="Add to Cart" class="btnAddAction" /></div>
		</div>
		</form>
	</div>
<?php
	}
}
?>
function custom_price_shortcode_callback( $atts ) {

    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'product_price' );

    $html = '';

    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
        // Get an instance of the WC_Product object
        $product = wc_get_product( intval( $atts['id'] ) );

        // Get the product prices
        $price         = wc_get_price_to_display( $product, array( 'price' => $product->get_price() ) ); // Get the active price
        $regular_price = wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ); // Get the regular price
        $sale_price    = wc_get_price_to_display( $product, array( 'price' => $product->get_sale_price() ) ); // Get the sale price

        // Your price CSS styles
        $style1 = 'style="font-size:40px;color:#e79a99;font-weight:bold;"';
        $style2 = 'style="font-size:25px;color:#e79a99"';

        // Formatting price settings (for the wc_price() function)
        $args = array(
            'ex_tax_label'       => false,
            'currency'           => 'EUR',
            'decimal_separator'  => '.',
            'thousand_separator' => ' ',
            'decimals'           => 2,
            'price_format'       => '%2$s&nbsp;%1$s',
        );

        // Formatting html output
        if( ! empty( $sale_price ) && $sale_price != 0 && $sale_price < $regular_price )
            $html = "<del $style2>" . wc_price( $regular_price, $args ) . "</del> <ins $style1>" . wc_price( $sale_price, $args ) . "</ins>"; // Sale price is set
        else
            $html = "<ins $style1>" . wc_price( $price, $args ) . "</ins>"; // No sale price set
    }
    return $html;
 }
 add_shortcode( 'product_price', 'custom_price_shortcode_callback' );
// If we want to use it as a dependency injection (we should),
// than this is the right way.

/**
 * Logger interface.
 *
 * @var \Psr\Log\LoggerInterface
 */
protected $logger;

// After that we add it to constructor method.

/**
* Controller_name constructor
 *
 * @param \Psr\Log\LoggerInterface $logger
 *  Logger interface.
 */
public function __construct(LoggerInterface $logger) {
  $this->logger = $logger;
}

public function someFunction(){
  if (something) {
    // Line of code...
  } else {
    $this->logger->error('Error message');
  }
}
stormtextil_core.edifact_orders:
  path: '/cron/synchronize-edifact-orders'
  defaults:
    _controller: '\Drupal\stormtextil_synchronization\Controller\SynchronizeEdifactOrders::parse'
    _title: 'Edifact Parser'
  requirements:
    _permission: 'access content'
<?php

namespace Drupal\stormtextil_config\Form;

use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class StormTextil Config Form.
 */
class StormTextilConfigForm extends ConfigFormBase {

  /**
   * EntityTypeManagerInterface.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * StormTextilConfigForm constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The Entity Type Manager.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager) {
    $this->entityTypeManager = $entityTypeManager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'stormtextil_config.config_form';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['stormtextil_config.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $config = $this->config('stormtextil_config.settings');

    // Promotions e-mail.
    $form['promotions_email'] = [
      '#type' => 'details',
      '#title' => $this->t('Promotions in Order e-mail'),
      '#description' => $this->t('Add custom promotional text into order confirmation e-mail'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $promotions_email = $config->get('promotions_email');

    $form['promotions_email']['enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable promotions'),
      '#default_value' => isset($promotions_email['enabled']) ? $promotions_email['enabled'] : '',
    ];

    $form['promotions_email']['EN'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - en'),
      '#format' => 'full_html',
      '#default_value' => isset($promotions_email['EN']['value']) ? $promotions_email['EN']['value'] : '',
    ];

    $form['promotions_email']['DA'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - da'),
      '#format' => 'full_html',
      '#default_value' => isset($promotions_email['DA']['value']) ? $promotions_email['DA']['value'] : '',
    ];

    $form['promotions_email']['DE'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - de'),
      '#format' => 'full_html',
      '#default_value' => isset($promotions_email['DE']['value']) ? $promotions_email['DE']['value'] : '',
    ];

    // Stock notify e-mail.
    $form['stock_notify_email'] = [
      '#type' => 'details',
      '#title' => $this->t('Stock notify e-mail'),
      '#description' => $this->t('Add custom text into stock notify e-mail'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $stock_notify_email = $config->get('stock_notify_email');

    $form['stock_notify_email']['en']['subject'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Subject - en'),
      '#default_value' => isset($stock_notify_email['en']['subject']) ? $stock_notify_email['en']['subject'] : '',
      '#size' => 50,
    ];

    $form['stock_notify_email']['en']['message'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - en'),
      '#format' => 'full_html',
      '#default_value' => isset($stock_notify_email['en']['message']['value']) ? $stock_notify_email['en']['message']['value'] : '',
    ];

    $form['stock_notify_email']['da']['subject'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Subject - da'),
      '#default_value' => isset($stock_notify_email['da']['subject']) ? $stock_notify_email['da']['subject'] : '',
      '#size' => 50,
    ];

    $form['stock_notify_email']['da']['message'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - da'),
      '#format' => 'full_html',
      '#default_value' => isset($stock_notify_email['da']['message']['value']) ? $stock_notify_email['da']['message']['value'] : '',
    ];

    $form['stock_notify_email']['de']['subject'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Subject - de'),
      '#default_value' => isset($stock_notify_email['de']['subject']) ? $stock_notify_email['de']['subject'] : '',
      '#size' => 50,
    ];

    $form['stock_notify_email']['de']['message'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - de'),
      '#format' => 'full_html',
      '#default_value' => isset($stock_notify_email['de']['message']['value']) ? $stock_notify_email['de']['message']['value'] : '',
    ];

    // Exchange rates.
    $form['exchange_rates'] = [
      '#type' => 'details',
      '#title' => $this->t('Exchange rates'),
      '#description' => $this->t('Defines the exchange rate for 1 unit of the currency in DKK.'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $exchange_rates = $config->get('exchange_rates');

    $form['exchange_rates']['EUR'] = [
      '#type' => 'textfield',
      '#title' => $this->t('EUR to DKK'),
      '#default_value' => isset($exchange_rates['EUR']) ? $exchange_rates['EUR'] : '',
      '#size' => 10,
    ];

    $form['exchange_rates']['SEK'] = [
      '#type' => 'textfield',
      '#title' => $this->t('SEK to DKK'),
      '#default_value' => isset($exchange_rates['SEK']) ? $exchange_rates['SEK'] : '',
      '#size' => 10,
    ];

    // Order fees.
    $form['order_fees'] = [
      '#type' => 'details',
      '#title' => $this->t('Order fees'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $form['order_fees']['administration_fee'] = [
      '#type' => 'details',
      '#title' => $this->t('Administration fees'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $administration_fee = $config->get('administration_fee');

    $form['order_fees']['administration_fee']['DKK']['range'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Invoice total (DKK)'),
      '#default_value' => isset($administration_fee['DKK']['range']) ? $administration_fee['DKK']['range'] : '',
      '#size' => 10,
    ];

    $form['order_fees']['administration_fee']['DKK']['fee'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Fee (DKK)'),
      '#default_value' => isset($administration_fee['DKK']['fee']) ? $administration_fee['DKK']['fee'] : '',
      '#size' => 10,
    ];

    $form['order_fees']['administration_fee']['EUR']['range'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Invoice total (EUR)'),
      '#default_value' => isset($administration_fee['EUR']['range']) ? $administration_fee['EUR']['range'] : '',
      '#size' => 10,
    ];

    $form['order_fees']['administration_fee']['EUR']['fee'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Fee (EUR)'),
      '#default_value' => isset($administration_fee['EUR']['fee']) ? $administration_fee['EUR']['fee'] : '',
      '#size' => 10,
    ];

    $form['order_fees']['administration_fee']['SEK']['range'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Invoice total (SEK)'),
      '#default_value' => isset($administration_fee['SEK']['range']) ? $administration_fee['SEK']['range'] : '',
      '#size' => 10,
    ];

    $form['order_fees']['administration_fee']['SEK']['fee'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Fee (SEK)'),
      '#default_value' => isset($administration_fee['SEK']['fee']) ? $administration_fee['SEK']['fee'] : '',
      '#size' => 10,
    ];

    // Added costs.
    $form['order_fees']['added_cost'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Added cost price (DKK)'),
      '#default_value' => $config->get('added_cost'),
      '#size' => 10,
    ];

    // VAT.
    $form['order_fees']['vat'] = [
      '#type' => 'textfield',
      '#title' => $this->t('VAT (%)'),
      '#default_value' => $config->get('vat'),
      '#size' => 10,
    ];

    // Balance is overdue notice.
    $form['balance_is_overdue'] = [
      '#type' => 'details',
      '#title' => $this->t('Balance is overdue notification'),
      '#description' => $this->t('Add custom notification text for user with overdue balance'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $balance_is_overdue = $config->get('balance_is_overdue');

    $form['balance_is_overdue']['enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable notifications'),
      '#default_value' => isset($balance_is_overdue['enabled']) ? $balance_is_overdue['enabled'] : '',
    ];

    $form['balance_is_overdue']['EN'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - en'),
      '#format' => 'full_html',
      '#default_value' => isset($balance_is_overdue['EN']['value']) ? $balance_is_overdue['EN']['value'] : '',
    ];

    $form['balance_is_overdue']['DA'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - da'),
      '#format' => 'full_html',
      '#default_value' => isset($balance_is_overdue['DA']['value']) ? $balance_is_overdue['DA']['value'] : '',
    ];

    $form['balance_is_overdue']['DE'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - de'),
      '#format' => 'full_html',
      '#default_value' => isset($balance_is_overdue['DE']['value']) ? $balance_is_overdue['DE']['value'] : '',
    ];
    // Edifact orders ftp connection.
    $form['edifact'] = [
      '#type' => 'details',
      '#title' => $this->t('Ftp connection'),
      '#description' => $this->t('Configure ftp connection to remote server'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $ftp_connection = $config->get('edifact');

    $form['edifact']['server'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Ftp server'),
      '#default_value' => isset($ftp_connection['server']) ? $ftp_connection['server'] : '',
      '#size' => 30,
    ];
    $form['edifact']['username'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Username'),
      '#default_value' => isset($ftp_connection['username']) ? $ftp_connection['username'] : '',
      '#size' => 30,
    ];
    $form['edifact']['password'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Password'),
      '#default_value' => isset($ftp_connection['password']) ? $ftp_connection['password'] : '',
      '#size' => 30,
    ];
    // Samba connection.
    $form['samba'] = [
      '#type' => 'details',
      '#title' => $this->t('Samba connection'),
      '#description' => $this->t('Configure connection to remote computer'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $samba = $config->get('samba');

    $form['samba']['username'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Username'),
      '#default_value' => isset($samba['username']) ? $samba['username'] : '',
      '#size' => 30,
    ];

    $form['samba']['password'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Password'),
      '#default_value' => isset($samba['password']) ? $samba['password'] : '',
      '#size' => 30,
    ];

    $form['samba']['workgroup'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Workgroup'),
      '#default_value' => isset($samba['workgroup']) ? $samba['workgroup'] : '',
      '#size' => 30,
    ];

    $form['samba']['pdf'] = [
      '#type' => 'details',
      '#title' => $this->t('Order PDF files'),
      '#description' => $this->t('Configure connection to remote computer to synchronize PDF files'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $form['samba']['pdf']['host'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Host (IP address of remote computer)'),
      '#default_value' => isset($samba['pdf']['host']) ? $samba['pdf']['host'] : '',
      '#size' => 30,
    ];

    $form['samba']['pdf']['share'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Shared folder'),
      '#default_value' => isset($samba['pdf']['share']) ? $samba['pdf']['share'] : '',
      '#size' => 30,
    ];

    $form['samba']['invoice'] = [
      '#type' => 'details',
      '#title' => $this->t('Order invoices'),
      '#description' => $this->t('Configure connection to remote computer to synchronize invoices'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $form['samba']['invoice']['host'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Host (IP address of remote computer)'),
      '#default_value' => isset($samba['invoice']['host']) ? $samba['invoice']['host'] : '',
      '#size' => 30,
    ];

    $form['samba']['invoice']['share'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Shared folder'),
      '#default_value' => isset($samba['invoice']['share']) ? $samba['invoice']['share'] : '',
      '#size' => 30,
    ];

    // Samba connection.
    $form['theme'] = [
      '#type' => 'details',
      '#title' => $this->t('Theme settings'),
      '#description' => $this->t('Configure theme specific variables'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $theme = $config->get('theme');

    $form['theme']['theme_color'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Theme color'),
      '#default_value' => isset($theme['theme_color']) ? $theme['theme_color'] : '',
      '#description' => $this->t('Insert color HEX code'),
      '#size' => 10,
    ];

    /** @var \Drupal\taxonomy\TermStorageInterface $termStorage */
    $termStorage = $this->entityTypeManager->getStorage('taxonomy_term');
    $categoriesTree = $termStorage->loadTree('categories', 0, NULL, TRUE);
    $options = [];

    foreach ($categoriesTree as $category) {
      $options[$category->id()] = $category->label();
    }

    $form['designer_exclude_categories'] = [
      '#type' => 'details',
      '#title' => $this->t('Designer Exclude Categories'),
      '#description' => $this->t('Designer Exclude Categories'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $form['designer_exclude_categories']['exclude'] = [
      '#type' => 'select',
      '#title' => $this->t('Excluded'),
      '#default_value' => $config->get('designer_exclude_categories'),
      '#options' => $options,
      '#multiple' => TRUE,
      '#size' => 120,
      '#attributes' => [
        'style' => 'height: 240px',
      ],
    ];

    $form['designer_query_maps_id'] = [
      '#type' => 'details',
      '#title' => $this->t('Designer Query Maps'),
      '#description' => $this->t('Set the active query maps.'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $form['designer_query_maps_id']['id'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Designer Query Maps'),
      '#description' => Link::createFromRoute(
        $this->t('See more'),
        'graphql.query_maps'
      ),
      '#default_value' => $config->get('designer_query_maps_id'),
    ];

    // Checkout text.
    $form['checkout'] = [
      '#type' => 'details',
      '#title' => $this->t('Checkout'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $checkout = $config->get('checkout');

    $form['checkout']['enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable checkout text'),
      '#default_value' => isset($checkout['enabled']) ? $checkout['enabled'] : '',
    ];

    $form['checkout']['EN'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Checkout text - en'),
      '#format' => 'full_html',
      '#default_value' => isset($checkout['EN']['value']) ? $checkout['EN']['value'] : '',
    ];

    $form['checkout']['DA'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Checkout text - da'),
      '#format' => 'full_html',
      '#default_value' => isset($checkout['DA']['value']) ? $checkout['DA']['value'] : '',
    ];

    $form['checkout']['DE'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Checkout text - de'),
      '#format' => 'full_html',
      '#default_value' => isset($checkout['DE']['value']) ? $checkout['DE']['value'] : '',
    ];

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();

    if (!empty($form_values['exchange_rates'])) {
      $error_msg = $this->t('Exchange rate values must be numeric and decimal points should be used. Commas are not allowed.');

      foreach ($form_values['exchange_rates'] as $key => $value) {
        if (!is_numeric($value)) {
          $form_state->setError($form['exchange_rates'][$key], $error_msg);
        }
      }
    }

    if (!empty($form_values['order_fees']['added_cost'])) {
      $error_msg = $this->t('Added cost price must be numeric and decimal points should be used. Commas are not allowed.');

      if (!is_numeric($form_values['order_fees']['added_cost'])) {
        $form_state->setError($form['order_fees']['added_cost'], $error_msg);
      }
    }

    if (!empty($form_values['order_fees']['administration_fee'])) {
      $error_msg = $this->t('Administration fee values must be numeric and decimal points should be used. Commas are not allowed.');

      foreach ($form_values['order_fees']['administration_fee'] as $currency => $item) {
        foreach ($form_values['order_fees']['administration_fee'][$currency] as $key => $value) {
          if (!is_numeric($value)) {
            $form_state->setError($form['order_fees']['administration_fee'][$currency][$key], $error_msg);
          }
        }
      }
    }

  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->config('stormtextil_config.settings');
    $form_values = $form_state->getValues();

    $config->set('promotions_email', $form_values['promotions_email'])
      ->set('stock_notify_email', $form_values['stock_notify_email'])
      ->set('exchange_rates', $form_values['exchange_rates'])
      ->set('balance_is_overdue', $form_values['balance_is_overdue'])
      ->set('administration_fee', $form_values['order_fees']['administration_fee'])
      ->set('edifact', $form_values['edifact'])
      ->set('samba', $form_values['samba'])
      ->set('theme', $form_values['theme'])
      ->set('added_cost', $form_values['order_fees']['added_cost'])
      ->set('vat', $form_values['order_fees']['vat'])
      ->set('designer_exclude_categories', array_values($form_values['designer_exclude_categories']['exclude']))
      ->set('designer_query_maps_id', $form_values['designer_query_maps_id']['id'])
      ->set('checkout', $form_values['checkout'])
      ->save();

    Cache::invalidateTags(['designer_exclude_categories']);

    parent::submitForm($form, $form_state);
  }

}
<?php

namespace Drupal\stormtextil_core\Controller;

use Drupal\commerce_shipping\Entity\Shipment;
use Drupal\commerce_shipping\Entity\ShippingMethod;
use Drupal\commerce_shipping\ShipmentItem;
use Drupal\Core\Controller\ControllerBase;
use Drupal\physical\Weight;
use Drupal\physical\WeightUnit;
use Drupal\profile\Entity\Profile;
use EDI\Parser;
use Drupal\commerce_price\Price;
use Drupal\commerce_order\Entity\OrderItem;
use Drupal\commerce_order\Entity\Order;

class EdifactController extends ControllerBase {

  public function parse() {
    $parser = new Parser();
    $ediFile = file_get_contents('./sites/default/files/1509018E1-000523-1611970.EDI');
    $parsedEdiFile = $parser->loadString($ediFile);

    $lineItems = [];
    $orderItems = [];
    $currency = $parsedEdiFile[18][1][1];

    foreach ($parsedEdiFile as $ediElement) {
      switch($ediElement[0]) {
        case 'NAD':
          if ($ediElement[1] == 'DP') {
            $organization = $ediElement[3][0];
            $address_line1 = $ediElement[3][1];
            $postal_local = explode(" ", $ediElement[3][2]);
            $postal_code = $postal_local[0];
            $locality = $postal_local[1];
            $country_code = $ediElement[3][3];
          } else if ($ediElement[1] == 'BY') {
            $billing_address = $ediElement[5];
            $billing_city = $ediElement[6];
            $billing_company = $ediElement[4];
            $billing_zip_code = $ediElement[8];
          };
          break;
        // Name that we are going to use in profile.
        case 'CTA':
          $name = explode(" ", $ediElement[2][1]);
          $given_name = $name[0];
          $family_name = $name[1];
          break;
        case 'TAX':
          if (!isset($tax)) {
            $tax = $ediElement[5][3] / 100;
            break;
          }
        // Name of shipping method.
        case 'ALC':
          $shipping_method_name = $ediElement[2];
          break;
        case 'MOA':
          if($ediElement[1][0] == '8') {
            $shipping_price = $ediElement[1][1];
          }
        // Line item variation.
        case 'PIA':
          if ($ediElement[1] == '5') {
            $sku = $ediElement[2][0];
            $rawProductVariation = $this->entityTypeManager()
              ->getStorage('commerce_product_variation')
              ->loadByProperties([
                'sku' => $sku,
              ]);
            $productVariation = reset($rawProductVariation);
            $lineItems[$productVariation->getTitle()]['variation'] = $productVariation;
          }
          break;
        // Line item quantity.
        case 'QTY':
          $quantity = $ediElement[1][1];
          $lineItems[$productVariation->getTitle()]['quantity'] = $quantity;
          break;
        // Line item price.
        case 'PRI':
          if ($ediElement[1][0] == 'AAA') {
            $price = $ediElement[1][1];
            $lineItems[$productVariation->getTitle()]['price'] = $price;
          }
          break;
        // Number of line items.
        case 'CNT':
          $numberOfLineItems = $ediElement[1][1];
          break;
      }
    }

    // Creating order item for each line item.
    foreach ($lineItems as $lineItem) {
      $orderItem = OrderItem::create([
        'type' => 'default',
        'purchased_entity' => $lineItem['variation'],
        'quantity' => $lineItem['quantity'],
        'unit_price' => new Price($lineItem['price'], $currency),
        'overridden_unit_price' => TRUE,
      ]);
      $orderItem->save();
      $orderItems[] = $orderItem;
    }

    // Creating order.
    $order = Order::create([
      'type' => 'default',
      'mail' => $this->currentUser()->getEmail(),
      'uid' => $this->currentUser()->id(),
      'store_id' => 1,
      'order_items' => [$orderItems[0], $orderItems[1]],
      'placed' => \Drupal::time()->getCurrentTime(),
    ]);
    $order->save();

    // Creating shipment.
    if ($order->get('shipments')->count() == 0) {
      $first_shipment = Shipment::create([
        'type' => 'default',
        'order_id' => $order->id(),
        'title' => 'Shipment',
        'state' => 'ready'
      ]);
      $first_shipment->save();
    }

    foreach ($orderItems as $order_item) {
      $quantity = $order_item->getQuantity();
      $purchased_entity = $order_item->getPurchasedEntity();

      if ($purchased_entity->get('weight')->isEmpty()) {
        $weight = new Weight(1, WeightUnit::GRAM);
      } else {
        $weight_item = $purchased_entity->get('weight')->first();
        $weight = $weight_item->toMeasurement();
      }

      // Creating shipment item.
      $shipment_item = new ShipmentItem([
        'order_item_id' => $order_item ->id(),
        'title' => $purchased_entity->label(),
        'quantity' => $quantity,
        'weight' => $weight->multiply($quantity),
        'declared_value' => $order_item->getTotalPrice(),
      ]);
      $first_shipment->addItem($shipment_item);
    }
    // Creating shipping method.
    $shipping_method = ShippingMethod::create([
      'stores' => 1,
      'name' => $shipping_method_name,
      'plugin' => [
        'target_plugin_id' => 'flat_rate',
        'target_plugin_configuration' => [
          'rate_label' =>'Shipping GG',
          'rate_amount' => [
            'number' => $shipping_price, //TODO: Zameniti sa varijablom
            'currency_code' => $currency
          ]
        ],
      ],
      'status' => TRUE,
      'weight' => 0,
    ]);
    $shipping_method->save();
    // Adding newly created shipment method to shipment.
    $first_shipment->setShippingMethod($shipping_method);

    // Adding amount to shipment.
    $shipping_method_plugin = $shipping_method->getPlugin();
    $shipping_rates = $shipping_method_plugin->calculateRates($first_shipment);
    $shipping_rate = reset($shipping_rates);
    $shipping_service = $shipping_rate->getService()->getId();
    $amount = reset($shipping_rates)->getAmount();
    $first_shipment->setAmount($amount);
    $first_shipment->save();

    $order->set('shipments', [$first_shipment]);
    $order->save();

    // Creating profile using data from EDI file.
    $profile = Profile::create([
      'uid' => $order->getCustomerId(),
      'type' => 'customer',
    ]);
    $profile->address->given_name = $given_name;
    $profile->set('field_address_1', $name);
    $profile->address->family_name = $family_name;
    $profile->address->organization = $organization;
    $profile->set('field_company', $organization);
    $profile->address->country_code = $country_code;
    $profile->set('field_new_country', $country_code);
    $profile->address->locality = $locality;
    $profile->set('field_city', $locality);
    $profile->address->postal_code = $postal_code;
    $profile->set('field_zip_code', $postal_code);
    $profile->address->address_line1 = $address_line1;
    $profile->set('field_address_1', $address_line1);
    $profile->save();

    // Create a billing profile.
    if(empty($order->getBillingProfile())) {
      $billing_profile = Profile::create([
        'type' => 'customer',
        'uid' => $order->getCustomerId(),
      ]);
      $billing_profile->save();
      $billing_profile->set('field_address_1', $billing_address);
      $billing_profile->set('field_city', $billing_city);
      $billing_profile->set('field_company', $billing_company);
      $billing_profile->set('field_zip_code', $billing_zip_code);
      $billing_profile->save();
      $order->setBillingProfile($billing_profile);
      $order->save();
    }

    //TODO: Add other data to profile.

    $first_shipment->setShippingProfile($profile);
    $first_shipment->setShippingService($shipping_service);
    $first_shipment->save();
    $order->set('shipments', $first_shipment);
    // Including tax into price.
    $priceWithTax = $order->getTotalPrice()->getNumber() + ($order->getTotalPrice()->getNumber() * $tax);
    $order->set('total_price', new Price($priceWithTax, $currency));
    $order->save();

    // Checking the number of line items.
    if ($numberOfLineItems == count($orderItems)) {
      $poruka = 'Provera prošla';
    } else {
      $poruka = 'Provera nije prošla';
    }

    return [
      '#markup' => $poruka,
    ];
  }

}
// register jquery and style on initialization
add_action('init', 'register_script');
function register_script(){
	wp_register_script( 'custom_jquery', plugins_url('/js/custom-jquery.js', __FILE__), array('jquery'), '2.5.1' );

	wp_register_style( 'new_style', plugins_url('/css/new-style.css', __FILE__), false, '1.0.0', 'all');
}

// use the registered jquery and style above
add_action('wp_enqueue_scripts', 'enqueue_style');
function enqueue_style(){
	wp_enqueue_script('custom_jquery');

	wp_enqueue_style( 'new_style' );
}
/**
 * Implements hook_preprocess_HOOK().
 */
function green_deal_core_preprocess_commerce_product__teaser(&$variables) {
  $product = $variables['elements']['#commerce_product'];
  $product_variation = reset($product);
  $price = $product_variation->get('price')->number;
  $list_price = $product_variation->get('list_price')->number;

  if ($list_price != NULL) {
    $percentage = round((($list_price - $price) / $list_price) * 100);
    if ($percentage < 10) {
      $percentage = 10;
    }
    $variables['percentage'] = $percentage . '%';
  }
}

function green_deal_core_preprocess_commerce_product__full(&$variables) {
  $product = $variables['elements']['#commerce_product'];
  $product_variation = reset($product);
  $price = $product_variation->get('price')->number;
  $list_price = $product_variation->get('list_price')->number;

  if ($list_price != NULL) {
    $percentage = round((($list_price - $price) / $list_price) * 100);
    if ($percentage < 10) {
      $percentage = 10;
    }
    $variables['percentage'] = $percentage . '%';
  }
}
green_deal_core.test:
  path: '/product_action'
  defaults:
    _controller: '\Drupal\green_deal_core\Controller\ProductActionController::test'
    _title: 'Product action controller'
  requirements:
    _permission: 'access content'
<?php

namespace Drupal\green_deal_core\Controller;

use Drupal\commerce_price\Price;
use Drupal\Core\Controller\ControllerBase;

class ProductActionController extends ControllerBase {

  public function test() {

    $flag_id = 'promotion_akcija';

    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $products = $this->entityTypeManager()
      ->getStorage('commerce_product')
      ->loadByProperties([
        'type' => 'default'
      ]);

    $variation = $this->entityTypeManager()
      ->getStorage('commerce_product_variation')
      ->load(1267);

    foreach ($products as $product) {
      if($flag_service->getEntityFlaggings($flag, $product)) {
        $variation = $product->getVariations();
        $variation = reset($variation);
        $price = $variation->getPrice()->getNumber();
        $nesto[] = $price;
        $list_price = ceil($price / 0.9);
        $variation->setListPrice(new Price($list_price, 'RSD'));
        $variation->save();
        $poruka = 'nesto';
      }
    }

    return ([
      '#markup' => $poruka,
    ]);
  }

}
array_diff_assoc($array, array_unique($a, SORT_REGULAR)));
// First we create order items.
    foreach ($lineItems as $lineItem) {
      $orderItem = OrderItem::create([
        'type' => 'default',
        'purchased_entity' => $lineItem['variation'],
        'quantity' => $lineItem['quantity'],
        'unit_price' => new Price($lineItem['price'], $currency),
        'overridden_unit_price' => TRUE,
      ]);
      $orderItem->save();
      $orderItems[] = $orderItem;
    }

// Than we create order.
    $order = Order::create([
      'type' => 'default',
      'mail' => $this->currentUser()->getEmail(),
      'uid' => $this->currentUser()->id(),
      'store_id' => 1,
      'order_items' => [$orderItems[0], $orderItems[1]],
      'placed' => \Drupal::time()->getCurrentTime(),
    ]);
    $order->save();

// Than we create shipment.
    if ($order->get('shipments')->count() == 0) {
      $first_shipment = Shipment::create([
        'type' => 'default',
        'order_id' => $order->id(),
        'title' => 'Shipment',
        'state' => 'ready'
      ]);
      $first_shipment->save();
    }

// After that we create data for shipment item and shipment items.
    foreach ($orderItems as $order_item) {
      $quantity = $order_item->getQuantity();
      $purchased_entity = $order_item->getPurchasedEntity();

      if ($purchased_entity->get('weight')->isEmpty()) {
        $weight = new Weight(1, WeightUnit::GRAM);
      } else {
        $weight_item = $purchased_entity->get('weight')->first();
        $weight = $weight_item->toMeasurement();
      }

      // Creating shipment item.
      $shipment_item = new ShipmentItem([
        'order_item_id' => $order_item ->id(),
        'title' => $purchased_entity->label(),
        'quantity' => $quantity,
        'weight' => $weight->multiply($quantity),
        'declared_value' => $order_item->getTotalPrice(),
      ]);
      $first_shipment->addItem($shipment_item);
    }

//Than we create shipping methods and add them to shipment.
    $shipping_method = ShippingMethod::create([
      'stores' => 1,
      'name' => $shipping_method_name,
      'plugin' => [
        'target_plugin_id' => 'flat_rate',
        'target_plugin_configuration' => [
          'rate_label' =>'Shipping GG',
          'rate_amount' => [
            'number' => $shipping_price, //TODO: Zameniti sa varijablom
            'currency_code' => $currency
          ]
        ],
      ],
      'status' => TRUE,
      'weight' => 0,
    ]);
    $shipping_method->save();
    // Adding newly created shipment method to shipment.
    $first_shipment->setShippingMethod($shipping_method);

// After that we add amount to shipment.
    $shipping_method_plugin = $shipping_method->getPlugin();
    $shipping_rates = $shipping_method_plugin->calculateRates($first_shipment);
    $shipping_rate = reset($shipping_rates);
    $shipping_service = $shipping_rate->getService()->getId();
    $amount = reset($shipping_rates)->getAmount();
    $first_shipment->setAmount($amount);
    $first_shipment->save();

    $order->set('shipments', [$first_shipment]);
    $order->save();

// And finally we create shipping and billing profile.
    $profile = Profile::create([
      'uid' => $order->getCustomerId(),
      'type' => 'customer',
    ]);
    $profile->address->given_name = $given_name;
    $profile->set('field_address_1', $name);
    $profile->address->family_name = $family_name;
    $profile->address->organization = $organization;
    $profile->set('field_company', $organization);
    $profile->address->country_code = $country_code;
    $profile->set('field_new_country', $country_code);
    $profile->address->locality = $locality;
    $profile->set('field_city', $locality);
    $profile->address->postal_code = $postal_code;
    $profile->set('field_zip_code', $postal_code);
    $profile->address->address_line1 = $address_line1;
    $profile->set('field_address_1', $address_line1);
    $profile->save();

    if(empty($order->getBillingProfile())) {
      $billing_profile = Profile::create([
        'type' => 'customer',
        'uid' => $order->getCustomerId(),
      ]);
      $billing_profile->save();
      $billing_profile->set('field_address_1', $billing_address);
      $billing_profile->set('field_city', $billing_city);
      $billing_profile->set('field_company', $billing_company);
      $billing_profile->set('field_zip_code', $billing_zip_code);
      $billing_profile->save();
      $order->setBillingProfile($billing_profile);
      $order->save();
    }

    //TODO: Add other data to profile.

    $first_shipment->setShippingProfile($profile);
    $first_shipment->setShippingService($shipping_service);
    $first_shipment->save();
    $order->set('shipments', $first_shipment);
    // Including tax into price.
    $priceWithTax = $order->getTotalPrice()->getNumber() + ($order->getTotalPrice()->getNumber() * $tax);
    $order->set('total_price', new Price($priceWithTax, $currency));
    $order->save();

$data=json_decode($json,true);
if ($data === null && json_last_error() !== JSON_ERROR_NONE) { //error }
{#
/**
 * @file
 * Template for the shipment confirmation.
 *
 * Available variables:
 * - order_entity: The order entity.
 * - shipment_entity: The shipment entity.
 * - shipping_profile: The profile associated with a shipment.
 * - tracking_code: The tracking code associated with the shipment.
 *
 * @ingroup themeable
 */
#}
{% set shipmentItemCount = shipment_entity.getItems|length %}
<table style="margin: 15px auto 0 auto; max-width: 768px; font-family: arial,sans-serif">
  <tbody>
  <tr>
    <td>
      <table style="margin-left: auto; margin-right: auto; max-width: 768px; text-align: center;">
        <tbody>
        <tr>
          <td>
            <a href="{{ url('<front>') }}" style="color: #0e69be; text-decoration: none; font-weight: bold; margin-top: 15px;">{{ order_entity.getStore.label }}</a>
          </td>
        </tr>
        </tbody>
      </table>
      <table style="margin-left: auto; margin-right: auto; min-width: 450px; margin: 5px auto 0 auto; border: 1px solid #cccccc; border-radius: 5px; padding: 40px 30px 30px 30px;">
        <tbody>
        <tr>
          <td style="text-align: center; font-weight: bold; padding-top:15px; padding-bottom: 15px; border-top: 1px solid #cccccc; border-bottom: 1px solid #cccccc">
            {% trans %}
              An item in your order #{{ order_entity.getOrderNumber }} has shipped!
            {% plural shipmentItemCount %}
              Items in your order #{{ order_entity.getOrderNumber }} have shipped!
            {% endtrans %}
          </td>
        </tr>
        <tr>
          <td>
            <table style="width: 100%; padding-top:15px; padding-bottom: 15px; text-align: left; border-bottom: 1px solid #cccccc">
              <tbody>
              <tr>
                <td style="font-weight: bold; padding-bottom: 15px; text-align: left; vertical-align: top;">
                  {{ 'Shipped to:'|t }}
                </td>
              </tr>
              <tr>
                <td>
                  {% block shipping_profile %}
                    {{ shipping_profile }}
                  {% endblock %}
                </td>
              </tr>
              </tbody>
            </table>
          </td>
        </tr>
        <tr>
          <td>
            {% block shipment_items %}
              <table style="padding-top: 15px; padding-bottom:15px; width: 100%">
                <tbody style="text-align: left;">
                <tr>
                  <td colspan="2" style="font-weight: bold; padding-bottom: 15px; text-align: left; vertical-align: top;">
                    {% trans %}
                      Item in shipment
                    {% plural shipmentItemCount %}
                      Items in shipment
                    {% endtrans %}
                  </td>
                </tr>
                {% for shipment_item in shipment_entity.getItems() %}
                  <tr>
                    <td>
                      {{ shipment_item.quantity|number_format }} x
                    </td>
                    <td>
                      <span>{{ shipment_item.title }}</span>
                    </td>
                  </tr>
                {% endfor %}
                </tbody>
              </table>
            {% endblock %}
          </td>
        </tr>
        {% if (tracking_code) %}
          {% block tracking_info %}
            <tr>
              <td style="font-weight: bold; padding-top:15px; padding-bottom: 15px; text-align: left; vertical-align: top; border-top: 1px solid #cccccc">
                {{ 'Tracking information:'|t }}
              </td>
            </tr>
            <tr>
              <td style="padding-bottom: 15px;">
                {{ tracking_code }}
              </td>
            </tr>
            <tr>
              <td style="padding-top:15px; padding-bottom: 15px; text-align: center; border-top: 1px solid #cccccc">
                {{ 'Thank you for your order!'|t }}
              </td>
            </tr>
          {% endblock %}
        {% endif %}
        </tbody>
      </table>
    </td>
  </tr>
  </tbody>
</table>
	/**
 * Implements hook_theme().
 */
function commerce_shipping_theme() {
  return [
    'commerce_shipment' => [
      'render element' => 'elements',
    ],
    'commerce_shipment_confirmation' => [
      'variables' => [
        'order_entity' => NULL,
        'shipment_entity' => NULL,
        'shipping_profile' => NULL,
        'tracking_code' => NULL,
      ],
    ],
  ];
}
<?php

namespace Drupal\commerce_shipping\Mail;

use Drupal\commerce\MailHandlerInterface;
use Drupal\commerce_shipping\Entity\ShipmentInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

class ShipmentConfirmationMail implements ShipmentConfirmationMailInterface {

  use StringTranslationTrait;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The mail handler.
   *
   * @var \Drupal\commerce\MailHandlerInterface
   */
  protected $mailHandler;

  /**
   * Constructs a new ShipmentConfirmationMail object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\commerce\MailHandlerInterface $mail_handler
   *   The mail handler.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, MailHandlerInterface $mail_handler) {
    $this->entityTypeManager = $entity_type_manager;
    $this->mailHandler = $mail_handler;
  }

  /**
   * {@inheritdoc}
   */
  public function send(ShipmentInterface $shipment, $to = NULL, $bcc = NULL) {
    /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
    $order = $shipment->getOrder();
    $to = isset($to) ? $to : $order->getEmail();
    if (!$to) {
      // The email should not be empty.
      return FALSE;
    }

    $subject = $this->formatPlural(
      $shipment->get('items')->count(),
      'An item for order #@number shipped!',
      'Items for your order #@number shipped!',
      ['@number' => $order->getOrderNumber()]
    );

    $profile_view_builder = $this->entityTypeManager->getViewBuilder('profile');
    $shipment_view_builder = $this->entityTypeManager->getViewBuilder('commerce_shipment');
    $body = [
      '#theme' => 'commerce_shipment_confirmation',
      '#order_entity' => $order,
      '#shipment_entity' => $shipment,
      '#shipping_profile' => $profile_view_builder->view($shipment->getShippingProfile()),
      '#tracking_code' => $shipment_view_builder->viewField($shipment->get('tracking_code'), 'default'),
    ];

    $params = [
      'id' => 'shipment_confirmation',
      'from' => $order->getStore()->getEmail(),
      'bcc' => $bcc,
      'order' => $order,
      'shipment' => $shipment,
    ];
    $customer = $order->getCustomer();
    if ($customer->isAuthenticated()) {
      $params['langcode'] = $customer->getPreferredLangcode();
    }

    return $this->mailHandler->sendMail($to, $subject, $body, $params);
  }

}
$url = "https://jsonplaceholder.typicode.com/posts";
$data = file_get_contents($url);
$characters = json_decode($data);
/**
 * Verifies if passed URL (remote file or any webpage / webresource) exists
 * The check is implemented via method HEAD, so no data is downloaded anyway
 *
 * @param   <string> Remote URL to verify
 * @returns <bool>   Returns true if given URL exists, false otherwise
 */
function file_exists_remote (string $url) : bool
{
    $handle = curl_init();

    curl_setopt_array($handle, [
        CURLOPT_URL => $url,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_NOBODY => 1,
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_AUTOREFERER => 1
    ]);

    curl_exec($handle);

    $responseCode = (int) curl_getinfo($handle, CURLINFO_RESPONSE_CODE);

    curl_close($handle);

    return $responseCode === 200;
}
<?php

$mageRoot = __DIR__;

while (!(file_exists($mageRoot . '/app/Mage.php') || file_exists($mageRoot . '/bin/magento'))) {
    $mageRoot = dirname($mageRoot);
}

return $mageRoot;
<?php

namespace Drupal\stormtextil_synchronization\Controller;

use Drupal\commerce_shipping\Entity\Shipment;
use Drupal\commerce_shipping\Entity\ShippingMethod;
use Drupal\commerce_shipping\ShipmentItem;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\physical\Weight;
use Drupal\physical\WeightUnit;
use Drupal\profile\Entity\Profile;
use EDI\Parser;
use Drupal\commerce_price\Price;
use Drupal\commerce_order\Entity\OrderItem;
use Drupal\commerce_order\Entity\Order;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class Synchronize Edifact Orders.
 *
 * @package Drupal\stormtextil_synchronization\Controller
 */
class SynchronizeEdifactOrders extends ControllerBase {

  /**
   * The time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $config;

  /**
   * Logger interface.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * Constructs Synchronize Edifact Orders.
   *
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The Time service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The config factory.
   * @param \Psr\Log\LoggerInterface $logger
   *   Logger interface.
   */
  public function __construct(TimeInterface $time, ConfigFactoryInterface $configFactory, LoggerInterface $logger) {
    $this->time = $time;
    $this->config = $configFactory;
    $this->logger = $logger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('datetime.time'),
      $container->get('config.factory'),
      $container->get('logger.channel.default')
    );
  }

  /**
   * Parse the edi file and create an order.
   *
   * @return string[]|void
   *   Response.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\EntityStorageException
   * @throws \Drupal\Core\TypedData\Exception\MissingDataException
   */
  public function parse() {
    // Login information.
    $login_data = $this->config->get('stormtextil_config.settings');
    $ftp_server = $login_data->get('edifact')['server'];
    $ftp_user = $login_data->get('edifact')['username'];
    $ftp_pass = $login_data->get('edifact')['password'];
    // Set up a connection or die.
    $ftp = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
    // Try to login.
    if (ftp_login($ftp, $ftp_user, $ftp_pass)) {
      echo "Connected as $ftp_user@$ftp_server\n";
    }
    else {
      echo "Couldn't connect as $ftp_user\n";
    }
    // Turn passive mode on,
    // e have to use passive mode because the,
    // running docker container is listening on a different port.
    ftp_set_option($ftp, FTP_USEPASVADDRESS, FALSE);
    ftp_pasv($ftp, TRUE);
    // Listing all companies in root folder.
    $companies = ftp_nlist($ftp, '/');
    foreach ($companies as $company) {
      // Check if this is a valid C5 ID.
      if (is_numeric(basename($company))) {
        $company_id = basename($company);
      }
      // Listing all files in stores directory.
      $files = ftp_nlist($ftp, './' . $company_id . '/archive/');
      foreach ($files as $file) {
        if ((preg_match('/^.*\.(edi)$/i', $file))) {
          // Edi file for proceeding the order.
          $ediFile = file_get_contents('ftp://' . $ftp_user . ':' . $ftp_pass . '@' . $ftp_server . '/'
            . $company_id . '/archive/' . basename($file));
          // Parsing the file.
          $parser = new Parser();
          $parsedEdiFile = $parser->loadString($ediFile);

          $lineItems = [];
          $orderItems = [];
          // Looping through all parsed EDI elements and taking
          // data for order information.
          foreach ($parsedEdiFile as $ediElement) {
            switch ($ediElement[0]) {
              // Delivery information.
              case 'NAD':
                if ($ediElement[1] == 'DP') {
                  $organization = $ediElement[3][0];
                  $address_line1 = $ediElement[3][1];
                  $postal_local = explode(" ", $ediElement[3][2]);
                  $postal_code = $postal_local[0];
                  $locality = $postal_local[1];
                  $country_code = $ediElement[3][3];
                }
                elseif ($ediElement[1] == 'BY') {
                  $billing_address = $ediElement[5];
                  $billing_city = $ediElement[6];
                  $billing_company = $ediElement[4];
                  $billing_zip_code = $ediElement[8];
                };
                break;

              // Name that we are going to use in shipment profile.
              case 'CTA':
                $name = explode(" ", $ediElement[2][1]);
                $given_name = $name[0];
                $family_name = $name[1];
                break;

              // Currency code.
              case 'CUX':
                $currency = $ediElement[1][1];
                break;

              // Tax percentage.
              case 'TAX':
                if (!isset($tax)) {
                  $tax = $ediElement[5][3] / 100;
                }
                break;

              // Name of shipping method.
              case 'ALC':
                $shipping_method_name = $ediElement[2];
                break;

              // Shipping price.
              case 'MOA':
                if ($ediElement[1][0] == '8') {
                  $shipping_price = $ediElement[1][1];
                }
                break;

              // Line item variation.
              case 'PIA':
                if ($ediElement[1] == '5') {
                  $sku = $ediElement[2][0];
                  $rawProductVariation = $this->entityTypeManager()
                    ->getStorage('commerce_product_variation')
                    ->loadByProperties([
                      'sku' => $sku,
                    ]);
                  $productVariation = reset($rawProductVariation);
                  $lineItems[$productVariation->getTitle()]['variation'] = $productVariation;
                }
                break;

              // Line item quantity.
              case 'QTY':
                $quantity = $ediElement[1][1];
                $lineItems[$productVariation->getTitle()]['quantity'] = $quantity;
                break;

              // Line item price.
              case 'PRI':
                if ($ediElement[1][0] == 'AAA') {
                  $price = $ediElement[1][1];
                  $lineItems[$productVariation->getTitle()]['price'] = $price;
                }
                break;

              // Number of line items.
              case 'CNT':
                $numberOfLineItems = $ediElement[1][1];
                break;
            }
          }

          // Creating order items.
          foreach ($lineItems as $lineItem) {
            $orderItem = OrderItem::create([
              'type' => 'default',
              'purchased_entity' => $lineItem['variation'],
              'quantity' => $lineItem['quantity'],
              'unit_price' => new Price($lineItem['price'], $currency),
              'overridden_unit_price' => TRUE,
            ]);
            $orderItem->save();
            $orderItems[] = $orderItem;
          }
          // Creating order.
          $order = Order::create([
            'type' => 'default',
            'mail' => $this->currentUser()->getEmail(),
            'uid' => $this->currentUser()->id(),
            'store_id' => 1,
            'order_items' => [$orderItems[0], $orderItems[1]],
            'placed' => $this->time->getCurrentTime(),
          ]);
          $order->save();
          // Creating shipment.
          if ($order->get('shipments')->count() == 0) {
            $first_shipment = Shipment::create([
              'type' => 'default',
              'order_id' => $order->id(),
              'title' => 'Shipment',
              'state' => 'ready',
            ]);
            $first_shipment->save();
          }
          // Caclculating weight for shipment.
          foreach ($orderItems as $order_item) {
            $quantity = $order_item->getQuantity();
            $purchased_entity = $order_item->getPurchasedEntity();

            if ($purchased_entity->get('weight')->isEmpty()) {
              $weight = new Weight(1, WeightUnit::GRAM);
            }
            else {
              $weight_item = $purchased_entity->get('weight')->first();
              $weight = $weight_item->toMeasurement();
            }
            // Creating shipment item.
            $shipment_item = new ShipmentItem([
              'order_item_id' => $order_item->id(),
              'title' => $purchased_entity->label(),
              'quantity' => $quantity,
              'weight' => $weight->multiply($quantity),
              'declared_value' => $order_item->getTotalPrice(),
            ]);
            $first_shipment->addItem($shipment_item);
          }
          // Creating shipping method.
          $shipping_method = ShippingMethod::create([
            'stores' => 1,
            'name' => $shipping_method_name,
            'plugin' => [
              'target_plugin_id' => 'flat_rate',
              'target_plugin_configuration' => [
                'rate_label' => 'Shipping GG',
                'rate_amount' => [
                  'number' => $shipping_price,
                  'currency_code' => $currency,
                ],
              ],
            ],
            'status' => TRUE,
            'weight' => 0,
          ]);
          $shipping_method->save();
          // Adding newly created shipment method to shipment.
          $first_shipment->setShippingMethod($shipping_method);
          // Adding amount to shipment.
          $shipping_method_plugin = $shipping_method->getPlugin();
          $shipping_rates = $shipping_method_plugin->calculateRates($first_shipment);
          $shipping_rate = reset($shipping_rates);
          $shipping_service = $shipping_rate->getService()->getId();
          $amount = reset($shipping_rates)->getAmount();
          $first_shipment->setAmount($amount);
          $first_shipment->save();

          $order->set('shipments', [$first_shipment]);
          $order->save();

          // Creating shipment profile using data from EDI file.
          $shipment_profile = Profile::create([
            'uid' => $order->getCustomerId(),
            'type' => 'customer',
          ]);
          $shipment_profile->address->given_name = $given_name;
          $shipment_profile->set('field_contact_person', implode(" ", $name));
          $shipment_profile->address->family_name = $family_name;
          $shipment_profile->address->organization = $organization;
          $shipment_profile->set('field_company', $organization);
          $shipment_profile->address->country_code = $country_code;
          $shipment_profile->set('field_new_country', $country_code);
          $shipment_profile->address->locality = $locality;
          $shipment_profile->set('field_city', $locality);
          $shipment_profile->address->postal_code = $postal_code;
          $shipment_profile->set('field_zip_code', $postal_code);
          $shipment_profile->address->address_line1 = $address_line1;
          $shipment_profile->set('field_address_1', $address_line1);
          $shipment_profile->save();
          $first_shipment->setShippingProfile($shipment_profile);
          $first_shipment->setShippingService($shipping_service);
          $first_shipment->save();
          $order->set('shipments', $first_shipment);
          // Create a billing profile.
          if (empty($order->getBillingProfile())) {
            $billing_profile = Profile::create([
              'type' => 'customer',
              'uid' => $order->getCustomerId(),
            ]);
            $billing_profile->save();
            $billing_profile->set('field_address_1', $billing_address);
            $billing_profile->set('field_city', $billing_city);
            $billing_profile->set('field_company', $billing_company);
            $billing_profile->set('field_zip_code', $billing_zip_code);
            $billing_profile->save();
            $order->setBillingProfile($billing_profile);
            $order->save();
          }
          // Including tax into price.
          $priceWithTax = $order->getTotalPrice()->getNumber() + ($order->getTotalPrice()->getNumber() * $tax);
          $order->set('total_price', new Price(round($priceWithTax, 2), $currency));
          $order->save();
          // Checking the number of line items.
          if ($numberOfLineItems == count($orderItems)) {
            $poruka = 'Order created.';
          }
          else {
            $poruka = 'Order was not created.';
          }
          // @todo Ovo će trebati da se otkomentariše u nekom momentu.
          // ftp_delete($ftp, $file);.
          return [
            '#markup' => $poruka,
          ];
        }
        else {
          // @todo Create a logic for putting wrong files in the error directory.
          $this->logger->error('Wrong file format');
        }
      }
    }
    // Closing ftp connection.
    ftp_close($ftp);
  }

}
$ediFile = file_get_contents('./sites/default/files/1509018E1-000523-1611970.EDI');
/**
 * Provides My Config Block.
 *
 * @Block(
 *   id = "config_block",
 *   admin_label = @Translation("My Config Block"),
 *   category = @Translation("My Config Block"),
 * )
 */
/**
 * @param  {number} ID
 * @param  {number} type
 * @param  {HTMLElement} $element
 */
//https://www.freecodecamp.org/news/what-is-a-javascript-object/

function thumbs_rating_vote(ID, type) {
	const itemName = `thumbsrating${ID}`; // For the LocalStorage
	const IDS = {
		container: `thumbs-rating-${ID}`
	};
	const CLASSES = {
		alreadyVoted: `thumbs-rating-already-voted`,
		container: `thumbs-rating-container`,
		down: `thumbs-rating-down`,
		up: `thumbs-rating-up`,
		show: `thumbs-rating-show`,
		voted: `thumbs-rating-voted`
	};
	const $container = document.getElementById(IDS.container);

	// Check if the LocalStorage value exist. If do nothing.
	if (!localStorage.getItem(itemName)) {
		// Set the localStorage type as well
		const typeItemName = `${itemName}-${type}`;

		// Set HTML5 LocalStorage so the user can not vote again unless the user clears it.
		localStorage.setItem(itemName, true);
		localStorage.setItem(typeItemName, true);

		// Data for the Ajax Request
		const data = new FormData();

    data.append( 'action', 'thumbs_rating_add_vote' );
    data.append( 'nonce', thumbs_rating_ajax.nonce );
    data.append( 'postid', ID );
    data.append( 'type', type );

    fetch(thumbs_rating_ajax.ajax_url, {
				method: "POST",
				credentials: 'same-origin',
				body: data
			})
			.then((response) => response.text())
			.then((data) => {
				if (data && $container) {
					$container.innerHTML = data;
				}
			})
			.catch((error) => {
				console.log('[Thumbs Rating Plugin - error]');
				console.error(error);
			});

	} else {
		if ($container) {
			const $alreadyVoted = $container.querySelector(`.${CLASSES.alreadyVoted}`);

			// Display message if we detect LocalStorage
			if ($alreadyVoted) {
				$alreadyVoted.classList.add(CLASSES.show);
			}
		}
	}
}
/*Ovaj kod možemo da pišemo u modules/module.module fajlu ili u themes/module.theme fajlu.
Prvo ide naziv modula (green_deal_core), zatim ide preprocess, i onda naziv template-a kojem hoćemo da prosledimo varijablu (commerce_product__teaser, ovaj template najčešće nalazimo u public_html->themes->custom->templates). Izvorni naziv template-a je sa crticama (-) ali mi to u hook moramo promeniti na underline (_).

Zatim upišemo $varibles['test'] i onda varijablu {{ test }} možemo da koristimo u tom template-u (commerce_product__teaser).

OBAVEZNO MORAMO DA FLAŠUJEMO KEŠ NAKON ŠTO NAPRAVIMO HOOK.
*/

function green_deal_core_preprocess_commerce_product__teaser(&$variables) {
  $variables['test'] = '123';
}
<?php
$date = new DateTime("now", new DateTimeZone('America/New_York') );
echo $date->format('Y-m-d H:i:s');
kazan_dizajner.admin_settings:
  path: '/kazan-dizajner/cenovnik'
  defaults:
    _form: '\Drupal\kazan_dizajner\Form\DesignerBlockSettingsForm'
    _title: 'Cenovnik kazana'
  requirements:
    _permission: 'administer kazan dizajner'

kazan_dizajner.send_mail_controller:
  path: '/kreiraj-svoj-kazan/izvestaj'
  defaults:
    _controller: '\Drupal\kazan_dizajner\Controller\SendMailController::sendmail'
    _title: 'Dizajn poslat'
  requirements:
    _role: 'authenticated'

kazan_dizajner.kazani_form:
  path: '/kazani_forma'
  defaults:
    _form: '\Drupal\kazan_dizajner\Form\KazaniForm'
    _title: 'Kazani forma'
  requirements:
    _permission: 'access content'
<?php

namespace Drupal\kazan_dizajner\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class KazaniForm extends FormBase {

  protected $cena;

  public function getFormId(): string
  {
    return 'kazani_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state): array
  {
    $form['kazani_tipovi'] = [
      '#type' => 'radios',
      '#title' => '1. Izaberite model kazana koji želite da kreirate:',
      '#options' => [
        'prevrtac' => 'Kazani prevrtači',
        'praktik' => 'Kazani praktik',
        'profesionalni' => 'Kazani profesionalni',
      ],
    ];
    $form['kazani_prevrtaci_zapremina'] = [
      '#type' => 'radios',
      '#title' => '2. Izaberite zapreminu kotla:',
      '#options' => [
        '_prevrtac_40_litara' => '40 litara',
        '_prevrtac_60_litara' => '60 litara',
        '_prevrtac_80_litara' => '80 litara',
        '_prevrtac_100_litara' => '100 litara'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => ['value' => 'prevrtac']
        ]
      ],
      //TODO: Ne rade conditional fieldovi kada radi ajax
//      '#ajax' => [
//        'callback' => '::myAjaxCallback',
//        'wrapper' => 'edit-output',
//        'progress' => [
//          'type' => 'throbber',
//          'message' => $this->t('Verifying entry...'),
//        ],
//      ]
    ];
    $form['kazani_prevrtaci_debljina_dna'] = [
      '#type' => 'radios',
      '#title' => 'Izaberite debljinu dna kotla:',
      '#options' => [
        '_prevrtac_1_5_mm' => 'Dno kotla - 1.5 mm',
        '_prevrtac_2_mm' => 'Dno kotla - 2 mm',
        '_prevrtac_3_mmm' => 'Dno kotla - 3 mm',
        '_prevrtac_4_mm' => 'Dno kotla - 4 mm'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_prevrtaci_zapremina"]' => [
            ['value' => '_prevrtac_40_litara'],
            ['value' => '_prevrtac_60_litara'],
            ['value' => '_prevrtac_80_litara'],
            ['value' => '_prevrtac_100_litara'],
          ],
          ['input[name="kazani_tipovi"]' => ['value' => 'prevrtac']]
        ]
      ]
    ];
    $form['kazani_prevrtaci_cev'] = [
      '#type' => 'radios',
      '#title' => '3. Izaberite željenu dužinu i prečnik cevi/lule:',
      '#options' => [
        '_prevrtac_fi28x1500mm' => 'Cev/lula - fi 28x1500 mm (STANDARD)',
        '_prevrtac_fi28x2000mm' => 'Cev/lula - fi 28x2000 mm',
        '_prevrtac_fi28x2500mm' => 'Cev/lula - fi 28x2500 mm',
        '_prevrtac_fi28x3000mm' => 'Cev/lula - fi 28x3000 mm',
        '_prevrtac_fi28x3500mm' => 'Cev/lula - fi 28x3500 mm',
        '_prevrtac_fi28x4000mm' => 'Cev/lula - fi 28x4000 mm',
        '_prevrtac_fi40x2000mm' => 'Cev/lula - fi 40x2000 mm',
        '_prevrtac_fi40x2500mm' => 'Cev/lula - fi 40x2500 mm',
        '_prevrtac_fi40x3000mm' => 'Cev/lula - fi 40x3000 mm',
        '_prevrtac_fi40x3500mm' => 'Cev/lula - fi 40x3500 mm',
        '_prevrtac_fi40x4000mm' => 'Cev/lula - fi 40x4000 mm',
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => ['value' => 'prevrtac']
        ],
      ]
    ];
    $form['kazani_prevrtaci_hladnjak'] = [
      '#type' => 'radios',
      '#title' => '4. Izaberite zapreminu i model hladnjaka:',
      '#options' => [
        '_prevrtac_pocinkovani_od_330_litara' => 'Pocinkovani hladnjak od 330 litara (STANDARD)',
        '_praktik_prohromski_od_330_litara' => 'Prohromski hladnjak od 330 litara',
        '_prevrtac_pocinkovani_od_470_litara' => 'Pocinkovani hladnjak od 470 litara',
        '_prevrtac_prohromski_od_470_litara' => 'Prohromski hladnjak od 470 litara'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'prevrtac'],
          ]
        ],
      ]
    ];
    $form['hladnjak_prevrtaci_izmenjivac'] = [
      '#type' => 'radios',
      '#title' => 'Izmenjivač toplote u hladnjaku',
      '#options' => [
        '_prevrtac_spirala_5_navoja' => 'Spirala 5 navoja (STANDARD)',
        '_prevrtac_cilindar_kiler' => 'Doplata za cilindar/kiler'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'prevrtac'],
          ]
        ],
      ]
    ];
    $form['kazani_prevrtaci_mesalica'] = [
      '#type' => 'radios',
      '#title' => '5. Izaberite jednu od varijanti mešalice:',
      '#options' => [
        '_prevrtac_rucna' => 'Ručna mešalica (STANDARD)',
        '_prevrtac_elektricna' => 'Električna mešalica'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'prevrtac'],
          ]
        ],
      ]
    ];
    $form['dodatna_prevrtaci_oprema'] = [
      '#type' => 'checkboxes',
      '#title' => '6. Izaberite potrebnu dodatnu opremu:',
      '#options' => [
        '_prevrtac_alkoholmetar' => 'Alkoholmetar',
        '_prevrtac_sirometar' => 'Sirometar',
        '_prevrtac_plamenik' => 'Plamenik',
        '_prevrtac_levak' => 'Levak',
        '_prevrtac_menzura' => 'Menzura',
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'prevrtac'],
          ]
        ],
      ]
    ];
    // Kazani praktik.
    $form['kazani_praktik_zapremina'] = [
      '#type' => 'radios',
      '#title' => '2. Izaberite zapreminu kotla:',
      '#options' => [
        '_praktik_60_litara' => '60 litara',
        '_praktik_80_litara' => '80 litara',
        '_praktik_100_litara' => '100 litara'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => ['value' => 'praktik']
        ]
      ]
    ];
    $form['kazani_praktik_debljina_dna'] = [
      '#type' => 'radios',
      '#title' => 'Izaberite debljinu dna kotla:',
      '#options' => [
        '_praktik_1_5_mm' => 'Dno kotla - 1.5 mm',
        '_praktik_2_mm' => 'Dno kotla - 2 mm',
        '_praktik_3_mmm' => 'Dno kotla - 3 mm',
        '_praktik_4_mm' => 'Dno kotla - 4 mm'
      ],
      '#states' => [
        'visible' => [
          ':input[name="kazani_praktik_zapremina"]' => [
            ['value' => '_praktik_60_litara'],
            ['value' => '_praktik_80_litara'],
            ['value' => '_praktik_100_litara']
          ],
          [':input[name="kazani_tipovi"]' => ['value' => 'praktik']]
        ]
      ]
    ];
    $form['kazani_praktik_cev'] = [
      '#type' => 'radios',
      '#title' => '3. Izaberite željenu dužinu i prečnik cevi/lule:',
      '#options' => [
        '_praktik_fi40x2000mm' => 'Cev/lula - fi 40x2000 mm (STANDARD)',
        '_praktik_fi40x2500mm' => 'Cev/lula - fi 40x2500 mm',
        '_praktik_fi40x3000mm' => 'Cev/lula - fi 40x3000 mm',
        '_praktik_fi40x3500mm' => 'Cev/lula - fi 40x3500 mm',
        '_praktik_fi40x4000mm' => 'Cev/lula - fi 40x4000 mm',
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => ['value' => 'praktik']
        ],
      ]
    ];
    $form['kazani_praktik_hladnjak'] = [
      '#type' => 'radios',
      '#title' => '4. Izaberite zapreminu i model hladnjaka:',
      '#options' => [
        '_praktik_pocinkovani_od_330_litara' => 'Pocinkovani hladnjak od 330 litara (STANDARD)',
        '_praktik_prohromski_od_330_litara' => 'Prohromski hladnjak od 330 litara',
        '_praktik_pocinkovani_od_470_litara' => 'Pocinkovani hladnjak od 470 litara',
        '_praktik_prohromski_od_470_litara' => 'Prohromski hladnjak od 470 litara'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'praktik'],
          ]
        ],
      ]
    ];
    $form['hladnjak_praktik_izmenjivac'] = [
      '#type' => 'radios',
      '#title' => 'Izmenjivač toplote u hladnjaku',
      '#options' => [
        '_praktik_spirala_5_navoja' => 'Spirala 5 navoja (STANDARD)',
        '_praktik_cilindar_kiler' => 'Doplata za cilindar/kiler'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'praktik'],
          ]
        ],
      ]
    ];
    $form['kazani_praktik_mesalica'] = [
      '#type' => 'radios',
      '#title' => '5. Izaberite jednu od varijanti mešalice:',
      '#options' => [
        '_praktik_rucna' => 'Ručna mešalica (STANDARD)',
        '_praktik_elektricna' => 'Električna mešalica'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'praktik'],
          ]
        ],
      ]
    ];
    $form['dodatna_praktik_oprema'] = [
      '#type' => 'checkboxes',
      '#title' => '6. Izaberite potrebnu dodatnu opremu:',
      '#options' => [
        '_praktik_alkoholmetar' => 'Alkoholmetar',
        '_praktik_sirometar' => 'Sirometar',
        '_praktik_plamenik' => 'Plamenik',
        '_praktik_levak' => 'Levak',
        '_praktik_menzura' => 'Menzura',
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'praktik'],
          ]
        ],
      ]
    ];
    // Kazani profesionalni.
    $form['kazani_profesionalni_zapremina'] = [
      '#type' => 'radios',
      '#title' => '2. Izaberite zapreminu kotla:',
      '#options' => [
        '_profi_80_litara' => '80 litara',
        '_profi_100_litara' => '100 litara',
        '_profi_120_litara' => '120 litara',
        '_profi_160_litara' => '160 litara',
        '_profi_200_litara' => '200 litara',
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => ['value' => 'profesionalni']
        ]
      ]
    ];
    $form['kazani_profesionalni_debljina_dna'] = [
      '#type' => 'radios',
      '#title' => 'Izaberite debljinu dna kotla:',
      '#options' => [
        '_profi_1_5_mm' => 'Dno kotla - 1.5 mm (STANDARD)',
        '_profi_2_mm' => 'Dno kotla - 2 mm',
        '_profi_3_mmm' => 'Dno kotla - 3 mm',
        '_profi_4_mm' => 'Dno kotla - 4 mm',
        '_profi_5_mm' => 'Dno kotla - 5 mm',
      ],
      '#states' => [
        'visible' => [
          ':input[name="kazani_profesionalni_zapremina"]' => [
            ['value' => '_profi_80_litara'],
            ['value' => '_profi_100_litara'],
            ['value' => '_profi_120_litara'],
            ['value' => '_profi_160_litara'],
            ['value' => '_profi_200_litara'],
          ],
          [':input[name="kazani_tipovi"]' => ['value' => 'profesionalni']]
        ],
      ]
    ];
    $form['kazani_profesionalni_cev'] = [
      '#type' => 'radios',
      '#title' => '3. Izaberite željenu dužinu i prečnik cevi/lule:',
      '#options' => [
        '_profi_fi40x2000mm' => 'Cev/lula - fi 40x2000 mm (STANDARD)',
        '_profi_fi40x2500mm' => 'Cev/lula - fi 40x2500 mm',
        '_profi_fi40x3000mm' => 'Cev/lula - fi 40x3000 mm',
        '_profi_fi40x3500mm' => 'Cev/lula - fi 40x3500 mm',
        '_profi_fi40x4000mm' => 'Cev/lula - fi 40x4000 mm',
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => ['value' => 'profesionalni']
        ],
      ]
    ];
    $form['kazani_profesionalni_hladnjak'] = [
      '#type' => 'radios',
      '#title' => '4. Izaberite zapreminu i model hladnjaka:',
      '#options' => [
        '_profi_pocinkovani_od_330_litara' => 'Pocinkovani hladnjak od 330 litara (STANDARD)',
        '_profi_prohromski_od_330_litara' => 'Prohromski hladnjak od 330 litara',
        '_profi_pocinkovani_od_470_litara' => 'Pocinkovani hladnjak od 470 litara',
        '_profi_prohromski_od_470_litara' => 'Prohromski hladnjak od 470 litara'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'profesionalni']
          ]
        ],
      ]
    ];
    $form['hladnjak_profesionalni_izmenjivac'] = [
      '#type' => 'radios',
      '#title' => 'Izmenjivač toplote u hladnjaku',
      '#options' => [
        '_profi_spirala_5_navoja' => 'Spirala 5 navoja (STANDARD)',
        '_profi_cilindar_kiler' => 'Doplata za cilindar/kiler'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'profesionalni']
          ]
        ],
      ]
    ];
    $form['kazani_profesionalni_mesalica'] = [
      '#type' => 'radios',
      '#title' => '5. Izaberite jednu od varijanti mešalice:',
      '#options' => [
        '_profi_rucna' => 'Ručna mešalica (STANDARD)',
        '_profi_elektricna' => 'Električna mešalica'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'profesionalni']
          ]
        ],
      ]
    ];
    $form['dodatna_profesionalni_oprema'] = [
      '#type' => 'checkboxes',
      '#title' => '6. Izaberite potrebnu dodatnu opremu:',
      '#options' => [
        '_profi_alkoholmetar' => 'Alkoholmetar',
        '_profi_sirometar' => 'Sirometar',
        '_profi_plamenik' => 'Plamenik',
        '_profi_levak' => 'Levak',
        '_profi_menzura' => 'Menzura',
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'profesionalni']
          ]
        ],
      ]
    ];
    $form['izracunaj_cenu'] = [
      '#type' => 'button',
      '#value' => 'Izracunaj cenu',
      '#ajax' => [
        'callback' => '::cene',
        'wrapper' => 'edit-output',
        'progress' => [
          'type' => 'throbber',
          'message' => $this->t('Verifying entry...'),
        ]
      ]
    ];
    // Order price.
    $form['cena'] = [
      '#type' => 'label',
      '#attributes' => ['id' => 'edit-output'],
      '#title' => 'Cena',
    ];
    // User information.
    $form['emailaddress'] = [
      '#type' => 'email',
      '#title' => 'E-mail (dobićete kopiju gore kreiranog kazana)*'
    ];
    $form['phone'] = [
      '#type' => 'tel',
      '#title' => 'Broj telefona*'
    ];
    $form['message'] = [
      '#type' => 'textarea',
      '#title' => 'Poruka*'
    ];
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary'
    ];

    return $form;
  }

  public static function cene(array &$form, FormStateInterface $form_state) {
    $config = \Drupal::config('kazan_dizajner.settings');
    $cena = '';
    $oprema_cena = '';
    // Fetching users input for acquiring each item price.
    if ($form_state->getUserInput()['kazani_tipovi'] == 'prevrtac') {
      $zapremina = $form_state->getUserInput()['kazani_prevrtaci_zapremina'];
      ($zapremina) ? $form_state->getUserInput()['kazani_prevrtaci_zapremina'] : '';
      $dno = $form_state->getUserInput()['kazani_prevrtaci_debljina_dna'];
      ($dno) ? $form_state->getUserInput()['kazani_prevrtaci_debljina_dna'] : '';
      $cev = $form_state->getUserInput()['kazani_prevrtaci_cev'];
      ($cev) ? $form_state->getUserInput()['kazani_prevrtaci_cev'] : '';
      $hladnjak = $form_state->getUserInput()['kazani_prevrtaci_hladnjak'];
      ($hladnjak) ? $form_state->getUserInput()['kazani_prevrtaci_hladnjak'] : '';
      $izmenjivac = $form_state->getUserInput()['hladnjak_prevrtaci_izmenjivac'];
      ($izmenjivac) ? $form_state->getUserInput()['hladnjak_prevrtaci_izmenjivac'] : '';
      $mesalica = $form_state->getUserInput()['kazani_prevrtaci_mesalica'];
      ($mesalica) ? $form_state->getUserInput()['kazani_prevrtaci_mesalica'] : '';
      $dodaci = $form_state->getUserInput()['dodatna_prevrtaci_oprema'];
      foreach ($dodaci as $dodatak) {
        if ($dodatak != NULL) {
          $oprema_cena += $config->get($dodatak);
        }
      }
    } else if ($form_state->getUserInput()['kazani_tipovi'] == 'praktik') {
      $zapremina = $form_state->getUserInput()['kazani_praktik_zapremina'];
      ($zapremina) ? $form_state->getUserInput()['kazani_prevrtaci_zapremina'] : '';
      $dno = $form_state->getUserInput()['kazani_praktik_debljina_dna'];
      ($dno) ? $form_state->getUserInput()['kazani_praktik_debljina_dna'] : '';
      $cev = $form_state->getUserInput()['kazani_praktik_cev'];
      ($cev) ? $form_state->getUserInput()['kazani_praktik_cev'] : '';
      $hladnjak = $form_state->getUserInput()['kazani_praktik_hladnjak'];
      ($hladnjak) ? $form_state->getUserInput()['kazani_praktik_hladnjak'] : '';
      $izmenjivac = $form_state->getUserInput()['hladnjak_praktik_izmenjivac'];
      ($izmenjivac) ? $form_state->getUserInput()['hladnjak_praktik_izmenjivac'] : '';
      $mesalica = $form_state->getUserInput()['kazani_praktik_mesalica'];
      ($mesalica) ? $form_state->getUserInput()['kazani_praktik_mesalica'] : '';
      $dodaci = $form_state->getUserInput()['dodatna_praktik_oprema'];
      foreach ($dodaci as $dodatak) {
        if ($dodatak != NULL) {
          $oprema_cena += $config->get($dodatak);
        }
      }
    } else {
      $zapremina = $form_state->getUserInput()['kazani_profesionalni_zapremina'];
      ($zapremina) ? $form_state->getUserInput()['kazani_profesionalni_zapremina'] : '';
      $dno = $form_state->getUserInput()['kazani_profesionalni_debljina_dna'];
      ($dno) ? $form_state->getUserInput()['kazani_profesionalni_debljina_dna'] : '';
      $cev = $form_state->getUserInput()['kazani_profesionalni_cev'];
      ($cev) ? $form_state->getUserInput()['kazani_profesionalni_cev'] : '';
      $hladnjak = $form_state->getUserInput()['kazani_profesionalni_hladnjak'];
      ($hladnjak) ? $form_state->getUserInput()['kazani_profesionalni_hladnjak'] : '';
      $izmenjivac = $form_state->getUserInput()['hladnjak_profesionalni_izmenjivac'];
      ($izmenjivac) ? $form_state->getUserInput()['hladnjak_profesionalni_izmenjivac'] : '';
      $mesalica = $form_state->getUserInput()['kazani_profesionalni_mesalica'];
      ($mesalica) ? $form_state->getUserInput()['kazani_profesionalni_mesalica'] : '';
      $dodaci = $form_state->getUserInput()['dodatna_profesionalni_oprema'];
      foreach ($dodaci as $dodatak) {
        if ($dodatak != NULL) {
          $oprema_cena += $config->get($dodatak);
        }
      }
    }
    //Calculating total order price.
    $artikli = [];
    array_push($artikli, $zapremina, $dno, $cev, $hladnjak, $izmenjivac, $mesalica);
    foreach($artikli as $artikal) {
      if ($artikal != NULL) {
        $cena += $config->get($artikal);
      }
    }
    $cena += $oprema_cena;

    $form['cena']['#title'] = 'Cena ovog kazana bi iznosila ' . $cena . ' RSD.';
    return $form['cena'];
  }

  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    if ($form_state->getValue)

    $message =
      'Specifikacija kazana' . PHP_EOL . PHP_EOL
    . 'Email: ' . $form_state->getValue('emailaddress') . PHP_EOL
    . 'Telefon: ' . $form_state->getValue('phone') . PHP_EOL
    . 'Poruka: ' . $form_state->getValue('message') . PHP_EOL
    . 'Tip: ' . $form_state->getValue('kazani_tipovi') . PHP_EOL
    . 'Zapremina: ' . $form_state->getValue('');
    $mailManager = \Drupal::service('plugin.manager.mail');
    $module = 'kazan_dizajner';
    $key = 'mail_order';
    $to = $form_state->getValue('emailaddress');
    dsm($form_state->getValue('kazani_tipovi'));

  }
}
musin_core.shipping:
  path: '/get/thread/title'
  defaults:
    _controller: '\Drupal\musin_core\Controller\Thread::getTitle'
  requirements:
    _permission: 'access content'

musin_core.completeness:
  path: '/completeness'
  defaults:
    _controller: '\Drupal\musin_core\Controller\CompletenessController::populateCompleteness'
  requirements:
    _permission: 'access content'
<?php

namespace Drupal\musin_core\Service;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountInterface;

class UserHelperService {


  /**
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  public function __construct(AccountInterface $current_user, EntityTypeManagerInterface $entity_type_manager) {
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entity_type_manager;
  }

  public static function getProfileCompleteness($user) {
    $field_weightings = [
      'field_first_name' => 10,
      'field_last_name' => 10,
      'field_city' => 10,
      'field_age' => 10,
      'user_picture' => 10,
      'field_cover_image' => 10,
      'field_genres' => 5,
      'field_instruments' => 5,
      'field_sample_tracks' => 5,
      'field_short_biography' => 5,
      'field_social_media_soundcloud' => 5,
      'field_social_media_spotify' => 5,
      'field_social_media_tiktok' => 5,
      'field_social_media_youtube' => 5,
    ];

    $completeness = 0;

    foreach ($field_weightings as $key => $value) {
      if ($user->hasField($key) && $user->get($key)->isEmpty() === FALSE) {
        $completeness = $completeness + $value;
      }
    }
    return $completeness;
  }
}
<?php

namespace Drupal\musin_core\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\musin_core\Service\UserHelperService;

class CompletenessController extends ControllerBase {

  protected $entityTypeManager;

  public function populateCompleteness()
  {
    $query = \Drupal::entityQuery('user');
    $uids = $query->execute();

    foreach ($uids as $key => $id) {
      $user = \Drupal::entityTypeManager()->getStorage('user')->load($id);
      $result = UserHelperService::getProfileCompleteness($user);
      $user->set('field_completeness', $result);
      $user->save();
    }
    return [];
  }
}
/**
 * Implements hook_entity_presave.
 */
function musin_core_entity_presave(EntityInterface $entity) {
  if ($entity instanceof \Drupal\user\UserInterface) {
    $completeness = \Drupal\musin_core\Service\UserHelperService::getProfileCompleteness($entity);
    $entity->set('field_completeness', $completeness);
    $entity->save();
  }
}
$today = date("Y-m-d");
$expire = $row->expireDate; //from database

$today_time = strtotime($today);
$expire_time = strtotime($expire);

if ($expire_time < $today_time) { /* do Something */ }
function check_attempted_login( $user, $username, $password ) {
    if ( get_transient( 'attempted_login' ) ) {
        $datas = get_transient( 'attempted_login' );

        if ( $datas['tried'] >= 3 ) {
            $until = get_option( '_transient_timeout_' . 'attempted_login' );
            $time = time_to_go( $until );

            return new WP_Error( 'too_many_tried',  sprintf( __( '<strong>ERROR</strong>: You have reached authentication limit, you will be able to try again in %1$s.' ) , $time ) );
        }
    }

    return $user;
}
add_filter( 'authenticate', 'check_attempted_login', 30, 3 );
function login_failed( $username ) {
    if ( get_transient( 'attempted_login' ) ) {
        $datas = get_transient( 'attempted_login' );
        $datas['tried']++;

        if ( $datas['tried'] <= 3 )
            set_transient( 'attempted_login', $datas , 300 );
    } else {
        $datas = array(
            'tried'     => 1
        );
        set_transient( 'attempted_login', $datas , 300 );
    }
}
add_action( 'wp_login_failed', 'login_failed', 10, 1 );

function time_to_go($timestamp)
{

    // converting the mysql timestamp to php time
    $periods = array(
        "second",
        "minute",
        "hour",
        "day",
        "week",
        "month",
        "year"
    );
    $lengths = array(
        "60",
        "60",
        "24",
        "7",
        "4.35",
        "12"
    );
    $current_timestamp = time();
    $difference = abs($current_timestamp - $timestamp);
    for ($i = 0; $difference >= $lengths[$i] && $i < count($lengths) - 1; $i ++) {
        $difference /= $lengths[$i];
    }
    $difference = round($difference);
    if (isset($difference)) {
        if ($difference != 1)
            $periods[$i] .= "s";
            $output = "$difference $periods[$i]";
            return $output;
    }
}
<!--la ruta absoluta-->
<img src="<?php echo get_bloginfo('wpurl');?>/wp-content/themes/temacreado/img/w.logo.png" alt="">
<!--
<?php echo get_bloginfo('wpurl');?> nos da la ruta de: http://localhost/cliente/  la ruta del archivo que tiene todo el wordpress dentro.
-->   
  
<!--La ruta relativa-->
<img src="wp-content/themes/temacreado/img/w.logo.png" alt="">
<!--
solo es la ruta relativa que es segun la ubicación del archivo
pero como los dos archivos se crean con page.php solo la portada es direccionada adecuadamente con esa direción relativa. lo que las paginas(no portada)  no lo reconocen; por eso la nececidad de dar la pocición absoluta.
-->

  <!-- Nos dimos cuenta que -->
  
$media = \Drupal\file\Entity\File::load(2); //2 je target_id iz field_image (iz noda npr.).
dsm($media);
$user->set('field_mailchimp_subscription', ['subscribe' => "1"]);
$current_path = $this->request->getCurrentRequest()->headers->get('referer');
$path = explode('8000', $current_path);  
//8000 is just a part of a string, from where we are breaking the string.
$route_name = Url::fromUserInput($path[1])->getRouteName();
return $this->redirect($route_name, ['user' => $user->id()]);
if ( ! function_exists( 'is_shop' ) ) :
    function is_shop() {
        //your codes goes here. 
    }
endif; 
<?php 
/*
 ==================
 Ajax Search
======================	 
*/
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){

    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
        success: function(data) {
            jQuery('#datafetch').html( data );
        }
    });

}
</script>

add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
	
	function khFunction(){ // on focusout rest inpput field value
	            jQuery('#datafetch').html( " " );
       }
	
    function fetch(){

	//test if there is at least to caracters on the input field 
      if(jQuery('#keyword').val().length > 2){
			
		
    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
        success: function(data) {
            jQuery('#datafetch').html( data );
        }
    }); }

}
</script>

<?php
}

// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){

    $the_query = new WP_Query( array( 
		'posts_per_page' => -1, 
		's' => esc_attr( $_POST['keyword'] ),
		'category_name' => 'top-apps', 'post_type' => array('post') ) );
	
    if( $the_query->have_posts() ) :
        echo '<ul>';
        while( $the_query->have_posts() ): $the_query->the_post(); ?>

            <li><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></li>

        <?php endwhile;
       echo '</ul>';
        wp_reset_postdata();  
    endif;

    die();
}


$timestamp = '2014-02-06 16:34:00';
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'Europe/Stockholm');
$date->setTimezone('UTC');
name: Subscribe block
type: module
description: Define a custom block for applying for subscription.
core_version_requirement: ^8 || ^9
package: Custom
dependencies:
  - block
<?php

namespace Drupal\bacademy_core\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Url;
use Drupal\user\Entity\User;

class SubscribeController extends ControllerBase {

  public function __construct(EntityTypeManager $entityTypeManager) {
    $this->entityTypeManager = $entityTypeManager;
  }

  public function subscribe(int $id) {
    $user = $this->entityTypeManager->getStorage('user')->load($id);
    /** @var User $user */
    $subscribed = $user->get('field_mailchimp_subscription')[0]->get('subscribe')->getValue();
    if ($subscribed != "1") {
      $user->set('field_mailchimp_subscription', ['subscribe' => "1"] );
      $user->save();
      return Url::fromRoute('entity.user.canonical', ['user' => $user->id()])->toString();
    } else {
      return Url::fromRoute('entity.user.canonical', ['user' => $user->id()])->toString();
    }
  }
}
<?php

namespace Drupal\bacademy_core\Plugin\Block;

use Drupal\bacademy_core\Controller\SubscribeController;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
 * Provides a 'Subscribe' block.
 *
 * @Block(
 *   id = "subscribe_block",
 *   admin_label= @Translation("Subscribe"),
 *   category= @Translation("Subscribe"),
 * )
 */
class SubscribeBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Entity type manager.
   *
   * @var EntityTypeManager
   */
  protected $entityTypeManager;

  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $current_user, EntityTypeManager $entityTypeManager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entityTypeManager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition){
    return new static (
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user'),
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritDoc}
   */
  public function build() {
    // Check if current user is subscribed.
    $user = $this->entityTypeManager
      ->getStorage('user')
      ->loadByProperties([
        'uid' => $this->currentUser->id(),
      ]);
    $user = reset($user);
    $subscribed = 0;
    if ($user->hasField('field_mailchimp_subscription')) {
      $subscribed = $user->get('field_mailchimp_subscription')[0]->get('subscribe')->getValue();
    }
    if ($subscribed == "1") {
      return [];
    } else {
      return [
        '#type' => 'inline_template',
        '#template' => "<div>
                        <p>Opt in and don't miss out on the latest from the Academy.</p>
                        <a href='{{ controller_link }}'>YES PLEASE</a>
                        <a href='#'>NO THANKS</a>
                      </div>",
        '#context' => [
          'controller_link' => Url::fromRoute('bacademy_core.subscription', ['id' => $this->currentUser->id()])->toString(),
        ],
      ];
    }
  }
}
//If we don't want to cache anonymus user choices or content
//than we add next line of code in mymodule.routing.yml file
//for the specified page

no_cache: 'TRUE'
$totalPayment = collect($billingData['payment_not_distirbute'])->sum('balance');
// clear that cache
composer create-project drupal/recommended-project myproject -n
cd myproject
lando init --source cwd --recipe drupal8 --webroot web --name myproject
lando start


composer require drush/drush drupal/admin_toolbar
drush si --db-url=mysql://drupal8:drupal8@database/drupal8 --account-pass=content -y
drush en admin_toolbar admin_toolbar_tools
drush uli -l http://myproject.lndo.site
$filterStudents = $search !== null ? [
    'filter[entry_year]' => $entry_year,
    'filter[search]' => $search,
    'relation[student_group]' => 1,
    'page' => (int)$page,
    'per_page' => 20,
] : [
    'filter[entry_year]' => $entry_year,
    'relation[student_group]' => 1,
    'page' => (int)$page,
    'per_page' => 20,
];
function mytheme_preprocess_node(&$variables) {
  switch ($variables['node']->getType()) {
    case "video":
      // ...
    break;
    case "something_else":
      // ...
    break;
  }
}			
function events_preprocess_node(&$variables) {
  // Get route name.
  $routeName = \Drupal::routeMatch()->getRouteName();
  // Get entity.
  $node = &$variables['node'];
  // Check if it's an event.
  if ($node->getType() === 'event' && $node->hasField('field_place')) {
    // Get the place.
    $place = $node->get('field_place')->entity;
    // Check if place is NULL.
    if ($place) {
      if ($node->get('field_teaser_media')->isEmpty()) {
        // Get teaser.
        $variables['place_teaser_media'] = $place
          ->get('field_teaser_media')
          ->view($routeName === 'entity.node.canonical' ? 'default' : 'small_teaser_square');
      }
      // Get organization name from place.
      $variables['place_organization'] = $place
        ->get('field_address')[0]
        ->get('organization')->getValue();
    }
  }
}
$this->assertSame('FooBar', Str::reverse('raBooF'));
$this->assertSame('Teniszütő', Str::reverse('őtüzsineT'));
$this->assertSame('❤MultiByte☆', Str::reverse('☆etyBitluM❤'));
//original
$dotted = [
    'user.name' => 'foo',
    'user.occupation' => 'bar',
];
 
// Converts it back to the original form
Arr::undot($dotted);

// Results in...
$resultArray = [
    'user' => [
        'name' => 'foo',
        'occupation' => 'bar',
    ]
];
$original = [
    'user' => [
        'name' => 'foo',
        'occupation' => 'bar',
    ]
];
 
$dotted = Arr::dot($original);
 
// Results in...
$dotted = [
    'user.name' => 'foo',
    'user.occupation' => 'bar',
];
Event::fakeExcept([
    NonImportantEvent::class,
    'non-fake-event',
]);