<?php defined('ABSPATH') or die('Access denied!');
/**
 * Plugin Name: Office 365
 * Plugin URI:  https://wpintegrate.com/product/office-365-base-for-wordpress/
 * Version:     3.9
 * Author:      wpintegrate.com
 * Author URI:  http://www.wpintegrate.com/
 * Date:        April 5, 2020
 * Description: Share information between WordPress and Office 365 services using our suite of plugins.
 * Text Domain: o365
 * Domain Path: /lang
 * Requires at least: 5.0
 * Tested up to: 6.3.2
 */
$o365_license_key = '';
define('O365_PATH', dirname(__FILE__) . '/');
define('O365_URL', plugin_dir_url(__FILE__, '/'));
define('O365_VERSION', '3.9');
function o365_admin_notice_func()
{
	$azure_login_client_id = o365_get_setting("client_id");
	$azure_login_client_secret = o365_get_setting("client_secret");
	ob_start();
	if ($azure_login_client_id == "" && $azure_login_client_secret == "") {
	?>
		<div class="notice notice-warning">
			<p><?php _e('The plugin <em>Office 365</em>, currently needs to be configured now. <a style="text-decoration:none;" href="' . admin_url() . 'admin.php?page=o365_settings">Configure Settings</a> >> General tab.'); ?></p>
		</div>
	<?php
	}
	$return = ob_get_clean();
	echo $return;
}
add_action('admin_notices', 'o365_admin_notice_func');
add_action('admin_init', 'o365_register_plugin_main_styles', 0);
/**
 * Register style sheet.
 */
function o365_register_plugin_main_styles()
{
	wp_register_style('o365_main_style', O365_URL . "css/main_style.css");
	wp_enqueue_style('o365_main_style');

	wp_register_script('o365_settings_tab_panels_script', O365_URL . 'js/SpryTabbedPanels.js');
	wp_enqueue_script('o365_settings_tab_panels_script');

	wp_enqueue_style('connection-style', O365_URL . "css/o365_settings.css");
}
// Include Musest libraries so that all other portable actions, filters
// and shortcodes load automatically.
require O365_PATH . 'libraries/o365-wp-menu-manager.php';
require O365_PATH . 'libraries/o365-wp-plugin-initializer.php';
// Includes SQL codes to create tables, callback function of activation hook
require O365_PATH . 'inc/activation-hook.php';
register_activation_hook(__FILE__, 'o365_register_activation_hook_check_multisite');
// Do not need it, keep tables, keept or delete tables based on settings!
require O365_PATH . 'inc/deactivation_hook.php';
register_deactivation_hook(__FILE__, 'o365_register_deactivation_hook_check_multisite');
//  End of file

add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'o365_plugin_setting_links');
function o365_plugin_setting_links($links)
{
	$mylinks = array('<a href="' . admin_url('admin.php?page=o365_settings') . '">Settings</a>',);
	return array_merge($links, $mylinks);
}

add_action('profile_update', 'profile_update_fundv');
function profile_update_fundv($user_id)
{
	update_user_meta($user_id, "o365_user_modify_time", time());
}
require O365_PATH . 'auto-update/plugin-update-checker.php';
$myUpdateChecker = Puc_v4_Factory_O365BASE::buildUpdateCheckerO365BASE(
	'https://api.wpintegrate.com/plugins_update_api_conn.php',
	__FILE__, //Full path to the main plugin file or functions.php.
	'o365'
);
function o365_plugin_check_license_expiration()
{
	$pluginExpiryCheck = get_option('o365PluginExpiryCheck');
	$pluginExpiryCheck += 3600;

	if ($pluginExpiryCheck < time()) {
		$licenseKeyMeta = array(
			'o365_crm_view_lcode',
			'onedrive_search_lcode',
			'o365_outlook_search_lcode',
			'o365_sp_calendar_lcode',
			'o365_sp_search_lcode',
			'o365_sp_video_lcode',
			'o365_ms_booking_lcode',
			'o365_adb2c_lcode',
			'o365_userauth_lcode_flow',
			'o365_wpflow_forms_lcode',
			'o365_persons_lcode_flow'
		);
		//Delete all option for new options
		foreach ($licenseKeyMeta as $key => $singleKey) {
			delete_option($singleKey . "_expire", '');
			delete_option($singleKey . "_cancelled", '');
			delete_option($singleKey . "_free_trial_time_unit");
			delete_option($singleKey . "_post_date");
			delete_option($singleKey . "_free_trial_time_value");
		}

		foreach ($licenseKeyMeta as $key => $singleKey) {
			$licenseKey[$singleKey] = get_option($singleKey);
		}
		$licenseKey['action'] = 'plugin_expiry_check';

		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_URL => "https://api.wpintegrate.com/check_key_updates.php",
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => "",
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 30,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => "POST",
			CURLOPT_POSTFIELDS => http_build_query($licenseKey),
		));

		$response = curl_exec($curl);
		$err = curl_error($curl);

		curl_close($curl);

		if ($err) {
			//echo "cURL Error #:" . $err;
		} else {
			$response = json_decode($response);
			foreach ($response as $meta_key => $meta_value) {
				delete_option($meta_key);
				update_option($meta_key, $meta_value);
			}
			update_option('o365PluginExpiryCheck', time());
		}
	}
}
add_action('init', 'o365_plugin_check_license_expiration');


function o365_plugins_license_admin_notice_error()
{

	$licenseKeyMeta = array(
		'o365_wp_crm_display' => array(
			'lkey' => 'o365_crm_view_lcode',
			'name' => 'Office 365 Dynamics 365 CRM Display'
		),
		'o365_wp_onedrive_display' => array(
			'lkey' => 'onedrive_search_lcode',
			'name' => 'Office 365 OneDrive Display'
		),
		'o365_wp_outlook_display' => array(
			'lkey' => 'o365_outlook_search_lcode',
			'name' => 'Office 365 Outlook Display'
		),
		'o365_wp_sp_calendar_display' => array(
			'lkey' => 'o365_sp_calendar_lcode',
			'name' => 'Office 365 Sharepoint Calendar Display'
		),
		'o365_wp_sp_display' => array(
			'lkey' => 'o365_sp_search_lcode',
			'name' => 'Office 365 Sharepoint List, Documents and Search Display'
		),
		'o365_wp_sp_video_display' => array(
			'lkey' => 'o365_sp_video_lcode',
			'name' => 'Office 365 Video Display'
		),
		'o365_wp_ms_booking' => array(
			'lkey' => 'o365_ms_booking_lcode',
			'name' => 'Office 365 Microsoft Booking'
		),
		'o365_wp_azure_adb2c' => array(
			'lkey' => 'o365_adb2c_lcode',
			'name' => 'Azure AD B2C Authentication'
		),
		'o365_user_auth' => array(
			'lkey' => 'o365_userauth_lcode_flow',
			'name' => 'Office 365 User Authentication Premium'
		),
		'o365_wpflow_forms' => array(
			'lkey' => 'o365_wpflow_forms_lcode',
			'name' => 'Office 365 Wordpress Flow Forms'
		),
		'o365_wp_persons_display' => array(
			'lkey' => 'o365_persons_lcode_flow',
			'name' => 'Office 365 Persons Display'
		)
	);

	/*$licenseKeyMeta = array(
		'o365_wp_crm_display' => 'o365_crm_view_lcode',
		'o365_wp_onedrive_display' => 'onedrive_search_lcode',
		'o365_wp_outlook_display' => 'o365_outlook_search_lcode',
		'o365_wp_sp_calendar_display' => 'o365_sp_calendar_lcode',
		'o365_wp_sp_display' => 'o365_sp_search_lcode',
		'o365_wp_sp_video_display' => 'o365_sp_video_lcode',
		'o365_wp_ms_booking' => 'o365_ms_booking_lcode',
		'o365_wp_azure_adb2c' => 'o365_adb2c_lcode',
		'o365_user_auth' => 'o365_userauth_lcode_flow',
		'o365_wpflow_forms' => 'o365_wpflow_forms_lcode',
		'o365_wp_persons_display' => 'o365_persons_lcode_flow'
	);*/

	$wpintegrate = 'https://wpintegrate.com/my-account/subscriptions/';

	foreach ($licenseKeyMeta as $key => $singleKey) {
		//Check Plugin is activated
		include_once(ABSPATH . 'wp-admin/includes/plugin.php');
		$plugin_name = str_replace('_', '-', $key);
		if (is_plugin_active($plugin_name . '/' . $plugin_name . '.php')) {
			$license_expire = get_option($singleKey['lkey'] . "_expire", '');
			$license_cancelled = get_option($singleKey['lkey'] . "_cancelled", '');
			$free_trial_time_unit = get_option($singleKey['lkey'] . "_free_trial_time_unit");
			$free_trial_post_date = get_option($singleKey['lkey'] . "_post_date");
			$free_trial_time_value = get_option($singleKey['lkey'] . "_free_trial_time_value");

			if ($license_expire != "" && $license_expire < time()) {
				$class = 'update-nag notice notice-warning inline';
				$message = __($singleKey['name'] . ' License Expired.', 'o365');
				printf('<div class="%1$s"><span>%2$s <a href="%3$s">Renew License.</a> </span></div>', esc_attr($class), esc_html($message), esc_url($wpintegrate));
			} else if ($license_expire != "" && $license_expire < (time() - 432000)) {
				$class = 'update-nag notice notice-warning inline';
				$message = __($singleKey['name'] . ' License Expire soon.', 'o365');
				printf('<div class="%1$s"><span>%2$s <a href="%3$s">Extend Period.</a> </span></div>', esc_attr($class), esc_html($message), esc_url($wpintegrate));
			} else if ($license_cancelled != "") {
				$class = 'update-nag notice notice-warning inline';
				$message = __($singleKey['name'] . ' License Cancelled.', 'o365');
				printf('<div class="%1$s"><span>%2$s <a href="%3$s">Reactivate.</a> </span></div>', esc_attr($class), esc_html($message), esc_url($wpintegrate));
			}

			//Get free trial information
			if ($free_trial_time_value > 0 && $free_trial_time_value != '' && strtotime($free_trial_post_date) < time() && $license_cancelled == '') {
				$order_date = date("Y-m-d", strtotime($free_trial_post_date));
				if ($free_trial_time_unit == 'day') {
					$expire_date = date('Y-m-d', strtotime('+' . $free_trial_time_value . ' days', strtotime($order_date)));
				} elseif ($free_trial_time_unit == 'month') {
					$expire_date = date('Y-m-d', strtotime('+' . $free_trial_time_value . ' month', strtotime($order_date)));
				} elseif ($free_trial_time_unit == 'week') {
					$expire_date = date('Y-m-d', strtotime('+' . $free_trial_time_value . ' week', strtotime($order_date)));
				} elseif ($free_trial_time_unit == 'year') {
					$expire_date = date('Y-m-d', strtotime('+' . $free_trial_time_value . ' year', strtotime($order_date)));
				}
				$diff = abs(strtotime($expire_date) - strtotime(date("Y-m-d")));
				$days = floor($diff / (60 * 60 * 24));

				$message = __(str_replace("_", " ", $key) . ' Trial Period Ends in ' . $days . ' days', 'o365');
				printf('<div class="%1$s"><span>%2$s <a href="%3$s">Reactivate.</a> </span></div>', esc_attr($class), esc_html($message), esc_url($wpintegrate));
			}
		}
	}
}
add_action('admin_notices', 'o365_plugins_license_admin_notice_error');

add_action('init', 'o365_check_base_plugin_is_verified');
function o365_check_base_plugin_is_verified()
{

	if (!function_exists('is_plugin_active')) {
		require_once(ABSPATH . '/wp-admin/includes/plugin.php');
	}

	$office365ActivatedPlugins = array(
		'o365-powerbi' => array("file" => 'o365-powerbi.php'),
		'o365-user-auth' => array("file" => 'o365-user-auth.php'),
		'o365-powerapps' => array("file" => 'o365-powerapps.php'),
		'o365-wp-ms-search' => array("file" => 'o365-wp-ms-search.php'),
		'o365-wp-ms-booking' => array("file" => 'o365-wp-ms-booking.php'),
		'o365-wp-sp-display' => array("file" => 'o365-wp-sp-display.php'),
		'o365-office-add-ins' => array("file" => 'o365-office-add-ins.php'),
		'o365-wp-crm-display' => array("file" => 'o365-wp-crm-display.php'),
		'o365-wp-yammer-display' => array("file" => 'o365-wp-yammer-display.php'),
		"o365-user-authentication" => array("file" => "o365-user-auth-online.php"),
		'o365-wp-persons-display' => array("file" => 'o365-wp-persons-display.php'),
		'o365-wp-outlook-display' => array("file" => 'o365-wp-outlook-display.php'),
		'o365-wp-azure-adb2c' => array("file" => 'o365-adb2c-authentication.php'),
		'o365-wp-sp-video-display' => array("file" => 'o365-wp-sp-video-display.php'),
		'o365-wp-onedrive-display' => array("file" => 'o365-wp-onedrive-display.php'),
		'o365-user-multiple-roles' => array("file" => 'o365-user-multiple-roles.php'),
		'o365-wp-sp-calendar-display' => array("file" => 'o365-wp-sp-calendar-display.php'),
		//'o365-wp-static-site' => array("file" => 'o365-wp-static-site.php'),
		//'o365-wp-static-woocommerce-addon' => array("file" => 'o365-wp-static-woocommerce-addon.php'),
	);
	$o365_settings = get_site_option('o365_settings');
	if( is_multisite() && ( ! empty($o365_settings['shared_settings']) && $o365_settings['shared_settings'] == "yes" ) ) {
		$o365_base_verify = get_site_option('o365_base_plugin_is_verify');
	} else {
		$o365_base_verify = get_option('o365_base_plugin_is_verify');
	}

	if ($o365_base_verify == '0' || $o365_base_verify == 0) {
		foreach ($office365ActivatedPlugins as $plugin_folder => $plugin_file) {
			$plugin = $plugin_folder . '/' . $plugin_file['file'];
			deactivate_plugins($plugin);
		}
	}
}

function m365_enqueue_scripts_for_all_plugins() {
	// Conflicting with other display plugins
	// wp_register_script('jQuery-sp-display', 'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js', array('jquery'), true, true);
	wp_enqueue_script('script0', O365_URL . 'js/jquery.simplemodal.js', array('jquery'), true, true);

	wp_register_script('m365-moment', 'https://unpkg.com/moment@2.27.0/min/moment.min.js', array('jquery'), true, true);
	wp_register_script('m365-jquery-3.5.1', 'https://unpkg.com/jquery@3.5.1/dist/jquery.min.js', array('jquery'), true, true);
	wp_register_script('m365-fullcalendar-3.10.2', 'https://unpkg.com/fullcalendar@3.10.2/dist/fullcalendar.min.js', array('jquery'), true, true);
	wp_register_script('m365-locale-all', 'https://unpkg.com/fullcalendar@3.10.2/dist/locale-all.js', array('jquery'), true, true);
	
	// Microsoft Fabric
	wp_register_style('m365-fabric', 'https://cdn.jsdelivr.net/npm/office-ui-fabric-core@11.0.0/dist/css/fabric.min.css', array(), true, true);

	// Microsoft Graph Toolkit Js (mgt-loader)
	wp_register_script('mgt-loader', 'https://unpkg.com/@microsoft/mgt/dist/bundle/mgt-loader.js', array(), true, false);
}
add_action('wp_enqueue_scripts', 'm365_enqueue_scripts_for_all_plugins');

if( ! function_exists('pprint_r') ) {
	function pprint_r($content) {
		echo '<pre>';
		print_r($content);
		echo '</pre>';
	}
}

if( ! function_exists('pprint_r') ) {
	function pprint_rd($content) {
		echo '<pre>';
		print_r($content);
		echo '</pre>';
		die('die');
	}
}

/**
 *-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
 * Proxy Provider Code needs to be transfered in other plugin.
*/

class MicrosoftGraphToolKitProxyProvider{
	public static function MGTProxyProviderInit() {
		add_action('init', array( __CLASS__, 'o365MGTProxyCustomRewriteTag' ), 10, 0);
		add_action('init', array( __CLASS__, 'o365MGTProxyCustomRewriteRule' ), 10, 0);
		add_action("admin_init", array( __CLASS__, "o365CreateProxyProviderEndpoint") );
		add_shortcode( 'mgt-proxy-provider', array( __CLASS__, 'o365MGTProxyProviderCallback' ) );
		add_filter('page_template', array( __CLASS__, 'o365AssignSinglePageTemplateToEndpoint' ) );
	}

	public static function o365CreateProxyProviderEndpoint() {
		$mgt_proxy_endpoint_page  = get_option('mgt_proxy_endpoint_page', "");
		if (($mgt_proxy_endpoint_page == "") || ($mgt_proxy_endpoint_page > 0 && !get_post_status($mgt_proxy_endpoint_page))) {
			$o365_mgt_proxy_endpoint_page_array = array(
				'post_title'    => 'API',
				'post_name'		=> 'api',
				'post_content'  => '',
				'post_status'   => 'publish',
				'post_author'   => get_current_user_id(),
				'post_type'     => 'page',
			);
			// Insert the post into the database
			$event_page = wp_insert_post($o365_mgt_proxy_endpoint_page_array);
			if ($event_page > 0) {
				update_option('mgt_proxy_endpoint_page', $event_page);
			}
		} 
	}
	public static function o365MGTProxyCustomRewriteTag()
	{
		add_rewrite_tag('api', '([^&]+)');
		flush_rewrite_rules();
	}

	public static function o365MGTProxyCustomRewriteRule()
	{
		$mgt_proxy_endpoint_page  = get_option('mgt_proxy_endpoint_page', "");
		if( ! empty( $mgt_proxy_endpoint_page ) ) {
			add_rewrite_rule('^api/([^/]*)', 'index.php?page_id=' . $mgt_proxy_endpoint_page . '&api=$matches[1]', 'top');
		}
	}

	public static function o365AssignSinglePageTemplateToEndpoint($page_template)
	{

		$mgt_proxy_endpoint_page  = get_option('mgt_proxy_endpoint_page');
		if ($mgt_proxy_endpoint_page != "" && $mgt_proxy_endpoint_page > 0) {

			if (is_page($mgt_proxy_endpoint_page)) {

				if (file_exists(get_stylesheet_directory() . "/o365-display/o365/pages/mgt-proxy-endpoint.php")) {

					$page_template = get_stylesheet_directory() . "/o365-display/o365/pages/mgt-proxy-endpoint.php";
				} else {

					$page_template = dirname(__FILE__) . '/templates/pages/mgt-proxy-endpoint.php';
				}
			}

			return $page_template;
		}
	}

	public static function o365MGTProxyProviderCallback() {
		?>
		<script src="https://unpkg.com/@microsoft/mgt/dist/bundle/mgt-loader.js"></script>
		<script>
			mgt.Providers.globalProvider = new mgt.ProxyProvider("https://wpintegrate.net/api", async () => {});
		</script>
	
		<!-- MGT GET -->
		<p>MGT GET</p>
		<h1>All root sites and their drives are listed below:</h1>
		<mgt-get id="acc-sites-mgt" resource="/sites/root/sites?$expand=drives" version="v1.0" scopes="Sites.Read.All" max-pages="2">
			<!-- Default Template -->
			<template data-type="default">
				<div data-if="checkSitesSize(this.value) == 0">
					<p>You don't have any account assigned. Please contact to your sharepoint site administrator</p>
				</div>
				<div data-else>
					<div id="lftmenu" class="accounts" data-for="accounts in value">
						<!-- Checking accounts -->
						<div data-if="accounts.displayName" class="checkacc acc-check" innerHtml>
							<h3 data-ac-id="{{accounts.id}}" class="accountSites">{{ accounts.displayName }}</h3>
							<div id="drives" class="drives" data-for="drive in accounts.drives">
								<h6>{{drive.name}}</h6>
							</div>
						</div>
					</div>
				</div>
			</template>
	
			<!-- Loading Template -->
			<template data-type="loading">
				Fetching Sites folders...
			</template>
			
			<!-- Template: Show API errors -->
			<template data-type="error">
				<div data-if="this.code == 'accessDenied'">
					<p>Please make sure you have appropriate permissions to access this site. Contact to your site administrator for more info.</p>
				</div>
				<div data-else>
					{{this.message}}
				</div>
			</template>
	
		</mgt-get>
	
		<p>MGT PEOPLE</p>
		<mgt-people></mgt-people>
	
		<p>MGT AGENDA</p>
		<mgt-agenda></mgt-agenda>
	
		<p>MGT AGENDA EVENT QUERY</p>
		<mgt-agenda event-query="/me/events?orderby=start/dateTime"></mgt-agenda>
	
		<p>MGT PERSON CARD</p>
		<mgt-person-card person-query="me"></mgt-person-card>
		
		<p>MGT PEOPLE PICKER</p>
		<mgt-people-picker></mgt-people-picker>
	
		<P>MGT TASKS</P>
		<mgt-tasks></mgt-tasks>
	
		<P>MGT TOSO</P>
		<mgt-todo></mgt-todo>
		
		<script type="module">
			var sidePanelAccSites = document.querySelector('#acc-sites-mgt');
			sidePanelAccSites.addEventListener('templateRendered', (e) => {
				let templateType = e.detail.templateType;
				let dataContext = e.detail.context;
				let element = e.detail.element;
			});
			sidePanelAccSites.templateContext = {
				reloadPage: () => {
					setTimeout(() => {
					location.reload();
					}, 5000);
				},
				checkSitesSize: ( data ) => {
					if(data.length) {
						return true;
					} else {
						return false;
					}
				}
			}
		</script>
		<?php
	}
}

add_action( 'plugins_loaded', array('MicrosoftGraphToolKitProxyProvider','MGTProxyProviderInit') );