Files
2024_WEBSITE_fipf/plugins/fipfcard_plugin/utils/plgntls_class.php

346 lines
9.9 KiB
PHP

<?php
/**
* include those two lines at the top of the main plugin file
*
* include_once( plugin_dir_path(__FILE__) . '/php/utils/plugin_tools.php');
* PLGNTLS_class::set_root_dir( plugin_dir_path(__FILE__), plugin_dir_url(__FILE__) );
*
* PLGNTLS means PLUGIN TOOLS
*
*
* ex:
*
* $my_plugin_class = new PLGNTLS_class();
* $var_1 = 'value_1';
* $var_2 = 'value_2';
* $var_3 = 'value_3';
* return $my_plugin_class->add_to_front(
* array(
* 'path/to/style.css' // those files are added to front
* 'path/to/script.js' // in the order you put them
* 'http://my_url.com' // it can be urls
* 'path/to/file.html' // html are just rendered then returned
* ),
* compact( // these variables are added to html and js files
* 'var_1', // in html files you can access them directly
* 'var_2', // in js files they are properties of object PLGNTLS_data
* 'var_3', // like PLGNTLS_data.var_1;
* )
* );
*
* complete syntax to include js scripts :
*
* key => value
* 1: 'src'
* 2: 'dependence' => 'src'
* 3: array( 'src', 'attr_1' => 'value_1', ... )
* 4: 'dependence' => array( 'src', 'attr_1' => 'value_1', ... )
*
* -> 'src' is required
* -> 'dependence' is optional
* explicit key is always a dependence
* -> value can be a string 'src', or an array('srcs', ...)
* if value is array, first element is 'src' and following
* are attributes for <script> html elements
*
*/
class PLGNTLS_class
{
private static $_root_path;
private static $_root_url;
private $_first_script;
private $_prefix;
private $_js_dependencies;
private $_css_dependencies;
private $_scripts_modules;
/**
*/
public function __construct() {
$this->_prefix = "PLGNTLS";
$this->_first_script = null;
$this->_js_dependencies = array();
$this->_css_dependencies = array();
$this->_scripts_modules = array();
}
/**
* can be used before class is instanciated :
* PLGNTLS_class::set_root_dir( plugin_dir_path(__FILE__), plugin_dir_url(__FILE__) );
*/
public static function set_root_dir($path, $url) {
if (isset( self::$_root_path ))
return ;
if (isset( self::$_root_url ))
return ;
self::$_root_path = $path;
self::$_root_url = $url;
}
public static function get_path() {
return(self::$_root_path);
}
public static function get_url() {
return(self::$_root_url);
}
public function add_to_front($scripts_arr = null, $vars = null) {
if (!is_array($vars))
$vars = array();
if (!is_null($scripts_arr))
$this->add_fetch($scripts_arr, $vars);
array_push($this->_scripts_modules, 'PLGNTLS_example_menu_js', 'PLGNTLS_plgntls_fetch_js');
$scripts = array();
foreach($scripts_arr as $key => $script_name) {
$scripts[] = $this->init_script($key, $script_name);
}
if (!is_null($scripts_arr))
$this->add_scripts_to_front($scripts);
if (!is_null($vars))
$this->add_vars_to_front($vars);
return $this->create_html($scripts, $vars);
}
/**
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* PRIVATES FUNCTIONS
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*/
private function add_fetch(&$scripts_arr, &$vars) {
// add fetch script at beginning of scripts list
array_unshift($scripts_arr, "utils/plgntls_fetch.js");
// for the custom endpoints in rest api to work
// they need to have a nonce named 'wp_rest'
// see : https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
$fetch_nonce = array("fetch_nonce" => wp_create_nonce('wp_rest'));
$fetch_url = array("fetch_url" => get_site_url() . "/wp-json");
$vars = array_merge($vars, $fetch_nonce);
$vars = array_merge($vars, $fetch_url);
}
/**
* @param two arguments :
* 1. html files to include in front
* - can be a string of 1 filename
* - or an array of strings of filenames
* ( https://stackoverflow.com/q/4747876/9497573 )
* - it's probably better to only add 1 file, and let it include other files
* 2. list of variables to make available to this files
* - in the form of key => val
* - recommanded to do it with compact()
* ex: create_html( "file.html", compact("var1","var2",) );
* ex: create_html( array("file1.html", "file2.html"), array("var1"=>"value") );
* @return a string of html code
*
* using ob_start() and ob_get_clean()
* allows to have php expansion inside the html loaded
* in opposition to the methode file_get_contents()
*
* https://stackoverflow.com/a/4402045/9497573
*/
private function create_html($files = null, $vars = null) {
if (is_null($files))
return null;
$plgn_dir = $this->get_path();
if (!is_null($vars))
extract($vars);
ob_start();
foreach($files as $file) {
if ($file->ext === 'html')
include($file->path);
}
$html = ob_get_clean();
return $html;
}
/**
* pass variables to js front as global variables
* @param array : list of key => value
* with the key being name of the variable, like this :
* 'my_var' => 'value',
* simpler way to do it is to use compact when calling the function :
* add_var_to_front(compact("var1", "var2", "var3"));
* @param string (optionnal) : name of first embended script that need these variables
* (it will be available to this script and all followings)
* this name is the filename + "_" + extension :
* init.js -> init_js
*/
private function add_vars_to_front($vars_arr)
{
if (is_null($this->_first_script))
return ;
if (is_null($vars_arr))
return ;
$handle = $this->_first_script;
$object_name = $this->_prefix . "_data";
$vars_json = json_encode($vars_arr);
$front = "let $object_name = $vars_json;";
wp_add_inline_script($handle, $front, 'before');
}
/**
* @param array : list of files :
* - with their path from root of their type of file (ex: from js/ to .js files)
* - and with their extension
* @param boolean
* - to add ajax script and variables
* - default to true
*/
private function add_scripts_to_front($scripts_arr) {
//wp_enqueue_script(<give_it_a_name>, /url/to/script, [depends on], version, defer? );
//wp_enqueue_style( <give_it_a_name>, /url/to/script, [depends on], version, media );
$previous_css_basename = '';
$previous_js_basename = '';
foreach ($scripts_arr as $script) {
if (in_array($script->ext, array("js", "url"))) {
if (is_null($this->_first_script))
$this->_first_script = $script->handle;
$depends_on = $this->check_dependencies($script, $previous_js_basename);
if ($depends_on !== null)
wp_enqueue_script( $script->handle, $script->url, $depends_on, $script->version, true);
$previous_js_basename = $script->handle;
}
else if ($script->ext === "css") {
$depends_on = $this->check_dependencies($script, $previous_css_basename);
if ($depends_on !== null)
wp_enqueue_style( $script->handle, $script->url, $depends_on, $script->version, '');
$previous_css_basename = $script->handle;
}
}
$this->make_scripts_modules();
/*
* uncomment to print all enqueued scripts, can be usefull
*/
global $wp_scripts;
error_log("wp_scripts->queue:");
error_log(json_encode($wp_scripts->queue));
}
// function is just a wrapper, only to facilitate writing
private function make_scripts_modules() {
// https://developer.wordpress.org/reference/hooks/wp_script_attributes/
// https://wordpress.stackexchange.com/questions/66843/attach-a-private-function-at-a-hook
add_filter( 'wp_script_attributes', fn($attr)=>$this->add_type_module($attr), 10, 1 );
}
private function add_type_module($attr) {
if (empty($attr['id']))
return $attr;
foreach($this->_scripts_modules as $script){
if ($attr['id'] === $script.'-js') {
$attr['type'] = 'module';
}
}
return $attr;
}
private function check_dependencies(&$script, $previous_basename)
{
if (in_array($script->ext, array("js", "url")))
{
global $wp_scripts;
$already_enqueued = array_search($script->handle, $wp_scripts->queue);
if ($already_enqueued !== false)
return null;
}
else if ($script->ext === "css")
{
global $wp_styles;
$already_enqueued = array_search($script->handle, $wp_styles->queue);
if ($already_enqueued !== false)
return null;
}
$depends_on = array();
if (isset($script->depends) && $script->depends !== '')
$depends_on[] = $script->depends;
if (isset($previous_basename) && $previous_basename !== '')
$depends_on[] = $previous_basename;
return $depends_on;
}
/**
* @param string : name of the file, with its path from its extension directory
* - from js/ root for .js files
* - from css/ root for .css files
* @return object / null :
* - null if file is not js or css
* - or an object with all the necessary infos :
* - ext : name.js -> "js"
* - basename : name.js -> "name"
* - handle : name.js -> "name_js"
* - url : url to file in wordpress
* - path : path to file in server
* - version : used to avoid browser caching
* - depends : string if depends on a handle, or ''
*/
private function init_script($key, $script_name) {
$script = (object)[];
if(filter_var($script_name, FILTER_VALIDATE_URL))
$script->ext = "url";
else
$script->ext = pathinfo($script_name, PATHINFO_EXTENSION);
if (! in_array($script->ext, array("js", "css", "html", "url")))
return null;
if ($script->ext === "url")
$script->basename = parse_url($script_name, PHP_URL_HOST);
else
$script->basename = pathinfo($script_name, PATHINFO_BASENAME);
$script->handle = "PLGNTLS_" . str_replace(".", "_", $script->basename);
if ($script->ext === "url") {
$script->url = $script_name;
$script->path = null;
$script->version = null;
}
else {
$script->url = $this->get_url().$script_name;
$script->path = $this->get_path().$script_name;
$script->version = date("ymd-Gis", filemtime($script->path));
}
$script->depends = '';
if (is_string($key))
$script->depends = $key;
return $script;
}
}
?>