Sindbad~EG File Manager

Current Path : /var/www/html/taet.readinessglobal.com/wp-content/plugins/o365-user-auth/
Upload File :
Current File : /var/www/html/taet.readinessglobal.com/wp-content/plugins/o365-user-auth/o365-user-auth.php

<?php defined('ABSPATH') or die('Access denied!');
/**
 * Plugin Name: Office 365 User Authentication Premium
 * Plugin URI:  https://wpintegrate.com/product/azure-ad-user-authentication-wordpress/
 * Version:     5.0.4
 * Author:      wpintegrate.com
 * Author URI:  http://www.wpintegrate.com/
 * Date:        April 5, 2020
 * Description: Supports mapping WPUser fields to Azure AD regular and custom fields, multi tenant support, block non admins from editing profile and Azure Group and WP Role association.
 * Text Domain: o365_user_auth
 * Requires at least: 5.0
 * Tested up to: 5.9.1
 * Domain Path: /lang
 */
//Code for azure user login on WordPres site
defined('ABSPATH') or die("No script kiddies please!");
define('AUTH_VERSION', 'v2.0');
define('GRAPH_VERSION', 'v1.0');
define('O365_USER_AUTH_WP_API_VERSION', 'v2');
define('O365_USER_AUTH_ACTIVATION', __FILE__);
define('O365_USER_AUTH_PATH', dirname(__FILE__) . '/');
define('O365_USER_AUTH_PLUGIN_URL', plugin_dir_url(__FILE__));
define('O365_USER_AUTH_PLUGIN_DIR', plugin_dir_path(__FILE__));
// define('O365_USER_AUTH_API_VERSION', '1.6');

/**
 * Define constent for Auth endpoint and auth versions
 */
$o365_settings = '';
if( is_multisite() ) {
	$o365_settings = get_site_option('o365_settings');
} 
if( ! empty($o365_settings['shared_settings']) && $o365_settings['shared_settings'] == "yes" ) {
	$o365_settings = get_site_option('o365_settings');
} else {
	$o365_settings = get_option('o365_settings');
}
if( ! empty( $o365_settings['o365_national_endpoints'] ) ) {
	define('AUTH_ENDPOINT', $o365_settings['o365_national_endpoints']);
} else {
	define('AUTH_ENDPOINT', 'https://login.microsoftonline.com');
}
if( ! empty( $o365_settings['o365_graph_endpoints'] ) ) {
	define('GRAPH_ENDPOINT', $o365_settings['o365_graph_endpoints']);
} else {
	define('GRAPH_ENDPOINT', 'https://graph.microsoft.com');
}
// Commented this code to use v2.0 as a default version for authorization
// if( ! empty( $o365_settings['o365_auth_version'] ) ) {
// 	define('AUTH_VERSION', $o365_settings['o365_auth_version']);
// } else {
// 	define('AUTH_VERSION', 'v2.0');
// }
require_once O365_USER_AUTH_PLUGIN_DIR . '/libraries/o365-user-auth-plugin-initializer.php';

require O365_USER_AUTH_PATH . '/inc/o365_user_auth_activation-hook.php';
register_activation_hook(__FILE__, 'o365_user_auth_register_activation_hook_check_multisite');
// Do not need it, keep tables, keept or delete tables based on settings!
require O365_USER_AUTH_PATH . '/inc/o365_user_auth_deactivation_hook.php';
register_deactivation_hook(__FILE__, 'o365_user_auth_register_deactivation_hook_check_multisite');
require_once O365_USER_AUTH_PLUGIN_DIR . '/libraries/o365-user-auth-settings.php';
require_once O365_USER_AUTH_PLUGIN_DIR . '/libraries/o365-user-auth-authorization-helper.php';
//Add user auth setting page in o365 base plugin
add_action('o365_user_auth_tab_title', 'o365_user_auth_tab_title_func');
add_action('o365_user_auth_html_content', 'o365_azure_login_setting_flows');
// TODO: Auto-load the (the exceptions at least)
require_once O365_USER_AUTH_PLUGIN_DIR . '/libraries/o365-user-auth/Authentication/JWT.php';
require_once O365_USER_AUTH_PLUGIN_DIR . '/libraries/o365-user-auth/Exceptions/BeforeValidException.php';
require_once O365_USER_AUTH_PLUGIN_DIR . '/libraries/o365-user-auth/Exceptions/ExpiredException.php';
require_once O365_USER_AUTH_PLUGIN_DIR . '/libraries/o365-user-auth/Exceptions/SignatureInvalidException.php';
require_once O365_USER_AUTH_PATH . '/libraries/o365-user-auth-graph-service-access-helper.php';
require_once O365_USER_AUTH_PATH . '/inc/o365_user_auth_class.php';
$settings = O365_USER_AUTH_Settings::loadSettingsFromJSON();

add_action("admin_head", 'o365_userauth_custom_js_func');
add_action('admin_notices', 'o365_userauth_update_notice');
/* Action commented because login form css is also adding from user auth class */
function o365_userauth_register_uninstall()
{
	delete_option('o365_userauth_lcode_flow');
	delete_option('o365_userauth_verify_auth_flow');
	delete_option('o365_ddl_id_flow');
}
//add_action("login_form", "o365_userauth_add_css_for_login_func");
function o365_userauth_add_css_for_login_func()
{
	$azure_login_setting_flow = o365_user_auth_get_settings();
	$azure_login_setting_flow = json_decode($azure_login_setting_flow);
	if (isset($azure_login_setting_flow->azure_login_css_text) && $azure_login_setting_flow->azure_login_css_text != "") {
		?>
		<style type="text/css">
			<?php echo $azure_login_setting_flow->azure_login_css_text; ?>
		</style>
		<?php
	}
}
/**
 * Use Custom Avatar if Provided
 * @author wpintegrate.com
 * @link https://www.wpintegrate.com
 *
 */
if (!function_exists('o365_userauth_set_gravatar_func')) {
	function o365_userauth_set_gravatar_func($avatar, $id_or_email, $size, $default, $alt)
	{
		if (is_user_logged_in()) {
			if (is_object($id_or_email)) {
				return true;
			}
			$custom_avatar = get_option($id_or_email . '_profile_image_url', "");
			$flow_profile_image = get_user_meta($id_or_email, "o365_azure_profile_image_url", true);
			if (isset($flow_profile_image) && $flow_profile_image != "" && $flow_profile_image != " ") {
				$return = '<img src="' . $flow_profile_image . '" width="' . $size . '" height="' . $size . '" alt="' . $alt . '" />';
			} else if (isset($custom_avatar) && $custom_avatar != "") {
				$return = '<img src="' . $custom_avatar . '" width="' . $size . '" height="' . $size . '" alt="' . $alt . '" />';
			} else if ($avatar) {
				$return = $avatar;
			} else {
				$return = '<img src="' . $default . '" width="' . $size . '" height="' . $size . '" alt="' . $alt . '" />';
			}
			return $return;
		}
	}
}
add_filter('get_avatar', 'o365_userauth_set_gravatar_func', 10, 5);

function o365_getpostdate_by_metavalue($val){
	global $wpdb;
	$result = array();
	$result = $wpdb->get_results("SELECT ID, post_date from {$wpdb->prefix}posts where ID IN ( SELECT post_id FROM {$wpdb->prefix}postmeta WHERE meta_value = '".$val."'  )", ARRAY_A);
	
	return $result;

}

add_action('init', 'o365_user_auth_set_profile_image_func');
function o365_user_auth_set_profile_image_func()
{
	if (is_user_logged_in()) {
		$user_id = get_current_user_id();
		$azure_user_id = get_user_meta($user_id, "aaduserobjectid", true);
		$user_tenant_id = get_user_meta($user_id, "usertenantid", true);
		$profile_image_content = get_option($user_id . '_profile_image_content', "");
		
		if (isset($azure_user_id) && $azure_user_id != "" && $profile_image_content != "") {
			if (!function_exists('is_plugin_active')) {
				include_once(ABSPATH . 'wp-admin/includes/plugin.php');
			}
			$azure_photo_content = o365UserAuthGraphServiceAccessHelper::getuserphoto($azure_user_id, $user_tenant_id);
			if (is_plugin_active('buddypress/bp-loader.php')) {
				o365UserAuthGraphServiceAccessHelper::upload_bpuser_photo($user_id, $azure_photo_content);
				update_user_meta($user_id, "o365_azure_profile_image_url", '');
			} else {
				$existing_profile_image = get_option($user_id . '_profile_image_url', "");

				/** Get image data to update if image older then 3 days */
				$filearr =  explode('uploads/', $existing_profile_image);
				
				$image_data = o365_getpostdate_by_metavalue( $filearr[1]);

				if( isset($image_data) && is_array($image_data) ){
					$image_date = $image_data[0]['post_date'];
					$attachmentid = $image_data[0]['ID'];
				}

				$now = time();
				$imagedate = strtotime($image_date);
				$datediff = $now - $imagedate;

				$nodays = round($datediff / (60 * 60 * 24));

				if( $nodays > 3 ){
					wp_delete_attachment( $attachmentid, true );
					$existing_profile_image = '';
				}
				/** Get image data to update if image older then 3 days  */

				if ($existing_profile_image == "") {
					$azure_image_metadata = o365UserAuthGraphServiceAccessHelper::getuserphoto_metadata($azure_user_id, $user_tenant_id);
					$azure_image_metadata = json_decode($azure_image_metadata);
					if (!isset($azure_image_metadata->{'@odata.mediaContentType'})) {
						$azure_image_metadata->{'@odata.mediaContentType'} = '';
					}
					$image_type = explode("/", $azure_image_metadata->{'@odata.mediaContentType'});
					if (isset($image_type[1])) {
						$filename = $user_id . "_profile_pic." . $image_type[1];
					} else {
						$filename = $user_id . "_profile_pic.jpeg";
					}
					$upload_dir = wp_upload_dir();
					$image_data = $azure_photo_content;
					if (wp_mkdir_p($upload_dir['path'])) {
						$file = $upload_dir['path'] . '/' . $filename;
					} else {
						$file = $upload_dir['basedir'] . '/' . $filename;
					}
					// Create the image  file on the server
					file_put_contents($file, $image_data);
					// Check image file type
					$wp_filetype = wp_check_filetype($filename, null);
					$attachment = array(
						'post_mime_type' => $wp_filetype['type'],
						'post_title'     => sanitize_file_name($filename),
						'post_content'   => '',
						'post_status'    => 'inherit'
					);
					// Create the attachment
					$attach_id = wp_insert_attachment($attachment, $file);
					// Include image.php
					require_once(ABSPATH . 'wp-admin/includes/image.php');
					// Define attachment metadata
					$attach_data = wp_generate_attachment_metadata($attach_id, $file);
					// Assign metadata to attachment
					wp_update_attachment_metadata($attach_id, $attach_data);
					update_option($user_id . '_profile_image_url', $upload_dir['url'] . '/' . $filename);
				}
			}
			delete_option($user_id . '_profile_image_content');
		}
	}
}
add_action("init", "o365_user_auth_check_edit_profile_feature");
function o365_user_auth_check_edit_profile_feature()
{
	$azure_login_setting_flow = o365_user_auth_get_settings();
	$user_mapping_data = json_decode($azure_login_setting_flow);
	if (isset($user_mapping_data->block_edit_profile)) {
		$user_profile_option = $user_mapping_data->block_edit_profile;
		//$user_profile_option = "";
		if ($user_profile_option == "ON") {
			if (!current_user_can('activate_plugins')) {
				function o365_user_auth_remove_profile_admin_bar()
				{
					global $wp_admin_bar;
					$wp_admin_bar->remove_menu('edit-profile', 'user-actions');
				}
				add_action('wp_before_admin_bar_render', 'o365_user_auth_remove_profile_admin_bar');
				function o365_user_auth_stop_access_profile()
				{
					if (defined('IS_PROFILE_PAGE') && IS_PROFILE_PAGE === true) {
						wp_die('Please contact your administrator to have your profile information changed.');
					}
					remove_menu_page('profile.php');
					remove_submenu_page('users.php', 'profile.php');
				}
				add_action('admin_init', 'o365_user_auth_stop_access_profile');
			}
		}
	}
}
/*Added option to restrict plugin*/
if (!function_exists('is_plugin_active')) {
	include_once(ABSPATH . 'wp-admin/includes/plugin.php');
}
if (is_plugin_active('o365-wp-restrict/o365-wp-restrict.php')) {
	$o365_userauth_verify_auth_flow = get_option('o365_userauth_verify_auth_flow', '');
	if ($o365_userauth_verify_auth_flow != 'false' && $o365_userauth_verify_auth_flow != '') {
		add_filter('o365_wp_restrict_auth_method', 'o365_userauth_online_restrict_auth_method');
	}
}
if (!function_exists('o365_userauth_online_restrict_auth_method')) {
	function o365_userauth_online_restrict_auth_method($opt)
	{
		$adb2c_opt = array('o365_user_auth' => 'Office 365');
		$opt = array_merge($adb2c_opt, $opt);
		return $opt;
	}
}
require O365_USER_AUTH_PATH . 'auto-update/plugin-update-checker.php';
$myUpdateChecker = Puc_v4_Factory_USERAUTH::buildUpdateCheckerUSERAUTH(
	'https://api.wpintegrate.com/plugins_update_api_conn.php',
	__FILE__, //Full path to the main plugin file or functions.php.
	'o365-user-auth'
);
/**********************************************************************************/
if( is_multisite() ) {
	$o365_settings = get_site_option('o365_settings');
	if( !empty($o365_settings['shared_settings']) ) {
		$shared_settings = $o365_settings['shared_settings'];
	}
	if( !empty($o365_settings['b2b_shared_settings']) ) {
		$b2b_shared_settings = $o365_settings['b2b_shared_settings'];
	}
}

if( is_multisite() && ( ! empty($shared_settings) && $shared_settings == "yes" ) && ( ! empty($b2b_shared_settings) && $b2b_shared_settings == 'yes' ) ) {
	$azure_access_token = get_site_option('o365_user_auth_access_token', '');
} else {
	$azure_access_token = get_option('o365_user_auth_access_token', '');
}

if ( empty($azure_access_token)) {
	global $pagenow;
	if ($pagenow == 'admin.php' || !empty($_REQUEST['page']) && $_REQUEST['page'] == 'o365_settings') {
		//$current_page_path = $pagenow . '?page=' . $_GET['page'];
		//if (admin_url('admin.php?page=o365_settings') == admin_url($current_page_path)) {
		$current_page_path = 'page=' . $_REQUEST['page'];
		if (admin_url('page=o365_settings') == admin_url($current_page_path)) {
			add_action('admin_init', 'o365_user_auth_access_token');
		}
	} else if (isset($_REQUEST['state']) && $_REQUEST['state'] == 'o365_user_auth_identifier' && isset($_REQUEST['code'])) {
		add_action('admin_init', 'o365_user_auth_access_token');
	}
} else {
	$O365_USER_AUTH = O365_USER_AUTH::getInstance($settings);
}

if (empty($azure_access_token)) {
	function o365_azure_show_error_notice_id_token_not_exist_func()
	{
		$class = 'notice notice-error';
		$message = __('Office 365 User Authentication Premium Plugin doesn\'t have an access token. <a href="' . admin_url('admin.php?page=o365_settings&bt=revoketoken') . '" >Click here</a>  to go to the token manager.', 'o365');

		printf('<div class="%1$s"><p>%2$s</p></div>', esc_attr($class), ($message));
	}
	if( is_multisite() && ( ! empty($b2b_shared_settings) && $b2b_shared_settings == 'yes' ) ) {
		add_action('network_admin_notices', 'o365_azure_show_error_notice_id_token_not_exist_func');
	} else {
		add_action('admin_notices', 'o365_azure_show_error_notice_id_token_not_exist_func');
	}
}

$expire_time = time() + 300;
$azure_token_expires = get_option('o365_user_auth_token_expires');
if ($expire_time > $azure_token_expires && !empty($azure_access_token)) {
	add_action('init', 'o365_user_auth_refresh_token');
}
/**********************************************************************************/

add_action('rest_api_init', "o365_wp_azure_token_register_func");
function o365_wp_azure_token_register_func()
{
	register_rest_route("wp/" . O365_USER_AUTH_WP_API_VERSION, '/azuretoken', array(
		array(
			'methods'  => WP_REST_Server::READABLE,
			'callback' => 'o365_user_auth_azure_token_data',
			'permission_callback' => function ($request) {
				return is_user_logged_in();
			}
		)
	));
}

/**
 * Call access token function behalf on other tenant
 */
$state = $_REQUEST['state'] ?? '';
$state = explode('__', $state);

if (!empty($state[1])) {
	add_action('init', 'o365_user_auth_access_token');
}
add_action('init', 'o365_user_auth_refresh_token');

/**
 * Delete settings on base plugin changed
 * Delete access token of main tenant, external users and all domain users
 */
add_action('delete_access_token_on_base_setting_changed', 'o365_user_auth_deleteAccessTokensOfAllUsersInUserAuth');

add_action('login_header', 'm365_localstorage_and_cookies_function');
add_action('admin_head', 'm365_localstorage_and_cookies_function');
add_action('wp_head', 'm365_localstorage_and_cookies_function');
function m365_localstorage_and_cookies_function() {
	//-------------------------------------------------------------------------------------------------------------------------------------------------------------------//
	// Support for React component with User auth
	//  React to WordPress
	$tenant_id =	o365_get_setting( 'tenant_id' );
	$application_id = o365_get_setting('client_id');
	$settings = O365_USER_AUTH_Settings::loadSettingsFromJSON();
	$O365_USER_AUTH = O365_USER_AUTH::getInstance($settings);
	
	?>
	<!-- React component code:START -->
	<script type="text/javascript">
		// Save the Logout url for logout url react component, office user and wordpress
		localStorage.setItem("wp_logout_url", "<?php echo htmlspecialchars_decode(wp_logout_url());?>");

		var hash = window.location.hash;
		var access_token = hash.slice(14).split('&')[0];

		if( access_token ) {
			localStorage.setItem('hello', JSON.stringify({"aad":{"access_token":access_token,"token_type":"Bearer","expires_in":3599,"scope":"user.readbasic.all+mail.send+files.read+Sites.Read.All+Sites.ReadWrite.All","state":"abcd","session_state":"8e81bfe0-9fe3-42a9-958d-ec5f4ededdfd","client_id":"<?php echo $application_id;?>","network":"aad","display":"page","callback":"_hellojs_b4zy50rh","redirect_uri":"<?php echo admin_url();?>","page_uri":"<?php echo admin_url();?>","expires":<?php echo time() + 3590;?>}}));

			<?php if( ! is_user_logged_in() ) { ?>
				location.href = '<?php echo $O365_USER_AUTH->get_login_url();?>';
			<?php }?>
		}

		// Hide the message if user is logged in office account on client dashboard page
		jQuery(window).load(() => {
			let aadAccessToken = JSON.parse(localStorage.getItem('hello'));
			if( aadAccessToken ) {
				if( aadAccessToken.aad ) {
					jQuery(".o365_user_auth_react").hide();
				}
			}
		});
	</script>
	<!-- React component code:END -->
	<?php
	// Support for React component with User auth
	//-------------------------------------------------------------------------------------------------------------------------------------------------------------------//

	
	$token_object =	get_option( 'msal_localstorage_token', '' );
	if( isset( $_SESSION['remove_mgt_session'] ) ) {
		$application_id = o365_get_setting('client_id');
		?>
		<script type="text/javascript">
			// Deleting all the cookies and localStorage when user logged out from Sharepoint template
			localStorage.clear();

			document.cookie = "msal.<?php echo $application_id;?>.idtoken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
			document.cookie = "msal.<?php echo $application_id;?>.error.description=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
			document.cookie = "msal.<?php echo $application_id;?>.client.info=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
		</script>
		<?php 
		unset($_SESSION['remove_mgt_session']);
	}
	// pprint_r($token_object);die();
	if( ! empty( $token_object )  && ! isset(json_decode($token_object['token_obj'])->error) ) {
		$antiforgery_id = $token_object['state'];
		$token = json_decode($token_object['token_obj']);
		$tenant_id =	o365_get_setting( 'tenant_id' );
		$application_id = o365_get_setting('client_id');
		$settings = O365_USER_AUTH_Settings::loadSettingsFromJSON();
		$o365_jwt =	get_option( 'msal_localstorage_o365_jwt_token', '' );
		if( empty($o365_jwt) ) {
			$o365_jwt = O365_USER_AUTH_AuthorizationHelper::validateIdToken(
				$token->id_token,
				$settings,
				$antiforgery_id
			);
		}
		
		?>

		<script type="text/javascript">
			//User auth to React
			localStorage.setItem('hello', JSON.stringify({"aad":{"access_token":"<?php echo $token->access_token;?>","token_type":"<?php echo $token->token_type;?>","expires_in":"<?php echo $token->expires_in;?>","scope":"<?php echo $token->scope;?>","state":"abcd","session_state":"8e81bfe0-9fe3-42a9-958d-ec5f4ededdfd","client_id":"<?php echo $application_id;?>","network":"aad","display":"page","callback":"_hellojs_b4zy50rh","redirect_uri":"<?php echo admin_url();?>","page_uri":"<?php echo admin_url();?>","expires":"<?php echo time() + 3590;?>"}}));
			
			// Microsoft Graph Toolkit login sessions: Start
			localStorage.setItem("msal.client.info", "<?php echo $token->client_info?>");
			localStorage.setItem("msal.<?php echo $application_id ?>.client.info", "<?php echo $token->client_info?>");
			localStorage.setItem("msal.idtoken", "<?php echo $token->id_token?>");
			localStorage.setItem("msal.<?php echo $application_id ?>.idtoken", "<?php echo $token->id_token?>");
			localStorage.setItem("msal.<?php echo $application_id ?>.idtoken", "<?php echo $token->id_token?>");
			
			localStorage.setItem(
				'{"authority":"https://login.microsoftonline.com/<?php echo $tenant_id ?>/","clientId":"<?php echo $application_id ?>","scopes":"<?php echo $application_id ?>","homeAccountIdentifier":""}', 
				'<?php echo $token_object['token_obj'] ?>'
			);
			
			// Microsoft Graph Toolkit login sessions: End

			/* MSAL Login sessions */
			// Authorize
			localStorage.setItem(
				"<?php echo $o365_jwt->oid.'.'.$tenant_id.'-login.windows.net-' . $tenant_id ?>",
				'{"authorityType":"MSSTS","clientInfo":"<?php echo $token->client_info;?>","homeAccountId":"<?php echo $o365_jwt->oid.'.'.$tenant_id;?>","environment":"login.windows.net","realm":"<?php echo $tenant_id ;?>","localAccountId":"<?php echo $o365_jwt->oid;?>","username":"<?php echo isset($o365_jwt->upn)?$o365_jwt->upn:'';?>","name":"<?php echo $o365_jwt->name;?>"}'
			);
			// ID token
			//userid.tenantid-login.windows.net-idtoken-clientid-tenantid
			localStorage.setItem(
				"<?php echo $o365_jwt->oid.'.'.$tenant_id.'-login.windows.net-idtoken-'. $application_id. '-' . $tenant_id ?>-",
				'{"credentialType":"IdToken","homeAccountId":"<?php echo $o365_jwt->oid.'.'.$tenant_id;?>","environment":"login.windows.net","clientId":"<?php echo $application_id ?>","secret":"<?php echo $token->id_token?>","realm":"<?php echo $tenant_id;?>"}'
			);

			// Accesstoken token
			localStorage.setItem(
				"<?php echo $o365_jwt->oid.'.'.$tenant_id.'-login.windows.net-accesstoken-'. $application_id. '-' . $tenant_id . '-mail.read openid profile sites.read.all sites.readwrite.all user.read email'; ?>",
				'{"homeAccountId":"<?php echo $o365_jwt->oid.'.'.$tenant_id;?>","credentialType":"AccessToken","secret":"<?php echo $token->access_token?>","cachedAt":"1597901345","expiresOn":"<?php echo (time() + (int)$token->expires_in);?>","extendedExpiresOn":"<?php echo (time() + (int)$token->expires_in);?>","environment":"login.windows.net","clientId":"<?php echo $application_id;?>","realm":"<?php echo $tenant_id;?>","target":"mail.read openid profile sites.read.all sites.readwrite.all user.read email"}'
			);

			// Refresh token
			localStorage.setItem(
				"<?php echo $o365_jwt->oid.'.'.$tenant_id.'-login.windows.net-refreshtoken-'. $application_id. '--'; ?>",
				'{"clientId":"<?php echo $application_id ?>","credentialType":"RefreshToken","environment":"login.windows.net","homeAccountId":"<?php echo $o365_jwt->oid.'.'.$tenant_id;?>","secret":"<?php echo $token->access_token?>"}'
			);
		</script>
		<?php 
	}
	delete_option( 'msal_localstorage_token' );
	delete_option( 'msal_localstorage_o365_jwt_token');
}

add_action( 'wp_ajax_nopriv_o365_calling_authentication_using_user_auth_with_mgt', 'o365_user_auth_action_wp_ajax_o365_calling_authentication_using_user_auth_with_mgt' );

add_action( 'show_user_profile', 'o365_create_azure_user_and_sharepoint_access_callback' );
add_action( 'edit_user_profile', 'o365_create_azure_user_and_sharepoint_access_callback' );

function o365_create_azure_user_and_sharepoint_access_callback( $user ) {
	?>
	<h3><?php esc_html_e( 'Create Azure user and provide SharePoint acess', 'crf' ); ?></h3>

	<table class="form-table">
		<tr>
			<td>
				<button id="o365_auzre_sharepoint" class="button button-primary" data-user-email="<?php echo $user->data->user_email ?>" data-user-id="<?php echo $user->ID ?>" >Run Flow</button>
				<p class="error" style="color:red;display:none;"></p>
				<p class="success" style="color:green;display:none;"></p>
			</td>
		</tr>
	</table>
	<script type="text/javascript">
		jQuery(document).ready(function($) {

			$(document).on("click", "#o365_auzre_sharepoint", function() {

				let user_id = $(this).data("user-id");
				let user_email = $(this).data("user-email");

				if( user_id ) {
					$.ajax({
						type: 'POST',
						url: "<?php echo admin_url('admin-ajax.php'); ?>",
						data: {
							'action': 'o365_auzre_user_and_sharepoint_access',
							'user_id': user_id,
							'user_email': user_email,
						},
						success: function (result) {
							if( result.success ) {
								$(".success").show();
								$(".success").html('Success');
							} else {
								$(".error").show();
								$(".error").html(result.data);
							}
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) { 
							$(".error").show();
							$(".error").html('Something went wrong!!');
						} 
					});
				} else {
					alert(`Invalid User: ${user_id}`);
				}
			});
		});
	</script>
	<?php
}

add_action('wp_ajax_o365_auzre_user_and_sharepoint_access','o365_auzre_user_and_sharepoint_access_callback');
function o365_auzre_user_and_sharepoint_access_callback() {
	if( isset($_POST['action']) && $_POST['action'] == 'o365_auzre_user_and_sharepoint_access' && ! empty($_POST['user_id']) && $_POST['user_id'] > 0 ) {
		$user_id = $_POST['user_id'];
		$user_email = $_POST['user_email'];
		$flow_url = 'https://prod-20.canadacentral.logic.azure.com:443/workflows/e7223a6e8b8d409488cc25516fade899/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=lowaz0jGF8mzt7LlNs1PW4gvopvHuH0OMaC6rFEOhHc';

		$flow_fields = array(
			"ID" => $user_id,
			"billing_first_name" => get_user_meta($user_id, "billing_first_name" , true),
			"billing_last_name" => get_user_meta($user_id, "billing_last_name" , true),
			"first_name" => get_user_meta($user_id, "first_name" , true),
			"last_name" => get_user_meta($user_id, "last_name" , true),
			"resend_invitation" => get_user_meta($user_id, "resend_invitation" , true),
			"user_email" => $user_email
		);
		$body = json_encode($flow_fields);

		$res = wp_remote_post(
			$flow_url,
			array(
				'method'      => 'POST',
				'headers'     => array('Content-Type' => 'application/json'),
				'body'        => $body
			)
		);

		if( is_wp_error( $res ) ) {
			$error_message = $res->get_error_message();
			wp_send_json_error( $error_message );
		} else {
			if(isset($res['response']['code']) && $res['response']['code'] == 202 ) {
				wp_send_json_success( true );
			}
		}
	}
	wp_send_json_error( 'Invalid User' );
}

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists