<?php
define("ENABLE_SUPER_ADMIN", true);

add_action('init', 'create_role');
function create_role() {
    global $wp_roles;
    if ( ! isset( $wp_roles ) )
        $wp_roles = new WP_Roles();

    $adm = $wp_roles->get_role('subscriber');
    $wp_roles->add_role('site_admin', __('Site Admin','profile'), $adm->capabilities);
}

add_action('init', 'add_capabilities');
function add_capabilities() {
	$role = get_role( 'site_admin' );
	
	$role->add_cap( 'read' );
    $role->add_cap( 'create_users' ); 
    $role->add_cap( 'delete_users' ); 
    $role->add_cap( 'edit_users' ); 
    $role->add_cap( 'list_users' ); 
    $role->add_cap( 'manage_options' ); 
    $role->add_cap( 'remove_users' ); 
    $role->add_cap( 'manage_categories' ); 
    $role->add_cap( 'edit_others_posts' ); 
    $role->add_cap( 'edit_pages' ); 
    $role->add_cap( 'edit_others_pages' ); 
    $role->add_cap( 'edit_published_pages' ); 
    $role->add_cap( 'publish_pages' ); 
    $role->add_cap( 'delete_pages' ); 
    $role->add_cap( 'delete_others_pages' ); 
    $role->add_cap( 'delete_published_pages' ); 
    $role->add_cap( 'delete_others_posts' ); 
    $role->add_cap( 'delete_private_posts' ); 
    $role->add_cap( 'edit_private_posts' ); 
    $role->add_cap( 'read_private_posts' ); 
    $role->add_cap( 'delete_private_pages' ); 
    $role->add_cap( 'edit_private_pages' ); 
    $role->add_cap( 'read_private_pages' ); 
    $role->add_cap( 'edit_published_posts' ); 
    $role->add_cap( 'upload_files' ); 
    $role->add_cap( 'publish_posts' ); 
    $role->add_cap( 'delete_published_posts' ); 
    $role->add_cap( 'edit_posts' ); 
    $role->add_cap( 'delete_posts' ); 
    $role->add_cap( 'edit_theme_options' );
}

add_action('delete_user', 'block_user_delete', 10, 2);
function block_user_delete($user_id, $reassign) {
	$user = wp_get_current_user();

	if ( $user_id == $user->ID || $user_id == 1 ) {
		die( __('This operation is not allowed','profile') );
	}
}

//add_action('pre_user_query','hide_admin');
function hide_admin($user_search) {
	$user = wp_get_current_user();
	if ($user->ID != 1) {
		global $wpdb;
		$user_search->query_where = str_replace('WHERE 1=1', "WHERE 1=1 AND {$wpdb->users}.ID<>1", $user_search->query_where);
	}
}


/* change admins count */
add_action('admin_footer' , 'fix_admin_count');
function fix_admin_count(){
	global $pagenow;
	$user = wp_get_current_user();

	if ( $user->ID != 1 && $pagenow == 'users.php' ) {
		?>
		<script type='text/javascript' >
			jQuery(document).ready(function($){
				var count_text;
				var total_count;

				var count = $('.subsubsub li.all a span.count');
				count_text = count.html();
				total_count = count_text.substring(1, count_text.length - 1) - 1;
				count.html('(' + total_count + ')');

				var count = $('.subsubsub li.administrator a span.count');
				count_text = count.html();
				total_count = count_text.substring(1, count_text.length - 1) - 1;
				count.html('(' + total_count + ')');
			});
		</script>
		<?php
	}
}

add_action('admin_init', 'remove_user_menus', 999);
function remove_user_menus() {
	$user = wp_get_current_user();

	if ( in_array( 'site_admin', (array) $user->roles ) ) {
		remove_menu_page( 'edit-comments.php' );
		remove_menu_page( 'themes.php' );
		remove_menu_page( 'tools.php' );

		if ( defined( "REDIRECTION_FILE" ) )
			remove_menu_page( basename( REDIRECTION_FILE ) );

		remove_submenu_page( 'edit.php', 'edit-tags.php?taxonomy=post_tag' );
    	remove_submenu_page( 'options-general.php', 'options-permalink.php' );
    	remove_submenu_page( 'wpseo_dashboard', 'wpseo_licenses' );
    }
}


add_action('wp_dashboard_setup', 'remove_dashboard_widgets' );
function remove_dashboard_widgets() {
	global $wp_meta_boxes;

	unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_incoming_links']);
	unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins']);
	unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_drafts']);
	unset($wp_meta_boxes['dashboard']['normal']['core']['dashboard_recent_comments']);
	unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']);
	unset($wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary']);

}

add_action( 'admin_menu' , 'add_wp_update_menu' );
function add_wp_update_menu() {

	$update_data = wp_get_update_data();
	$count = $update_data['counts']['total'];

	add_menu_page( __('Updates','profile'), __('Updates','profile') . "({$count})", 'manage_options', 'wp-update', 'wp_update', 'dashicons-update' );
}


function wp_update() { 
	// Force Core Update
	global $wp_version;
	$i = 0;
	// Force version check.
	do_action( 'wp_version_check' );

	$versionCheck = get_site_transient( 'update_core' );

	// Is there a new version of WordPress?
	if ( $versionCheck->updates[0]->response == 'upgrade' ) {

		$core = array('new' => $versionCheck->updates[0]->current, 'current' => $wp_version);
		$i++;
	}

	// Force Theme Update
	do_action( 'wp_update_themes' );

	$versionCheck   = get_site_transient( 'update_themes' );
	$currentVersion = wp_get_theme()->get( 'Version' );
	$currentTheme   = get_option( 'template' );

	if ( $versionCheck->response[ $currentTheme ]['new_version'] != $currentVersion && !is_null( $versionCheck->response[ $currentTheme ]['new_version'] ) ) {

		$theme = array('name' => $currentTheme, 'new' => $versionCheck->response[ $currentTheme ]['new_version'], 'current' => $currentVersion);
		$i++;
	}

	// Force plugnis version check.
	do_action( 'wp_update_plugins' );

	$versionCheck  = get_site_transient( 'update_plugins' );

	$activePlugins = get_option( 'active_plugins' );

	$needsUpdate = array_intersect_key( $versionCheck->response, array_flip( $activePlugins ) );

	if ( count( $needsUpdate ) > 0 ) {

		$plugins = array();

		foreach ( $needsUpdate as $plugin => $updateData ) {

			$pluginMeta = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, true, false );
			$pluginMeta['NewVersion'] = $updateData->new_version;
			$plugins[] = $pluginMeta;
			$i++;
		}
	}

	if ( $i > 0 ) { ?>
		<table class="form-table">
			<thead>
				<tr>
					<th><?php _e('Update Type','profile'); ?></th>
					<th><?php _e('Name','profile'); ?></th>
					<th><?php _e('Current Version','profile'); ?></th>
					<th><?php _e('New Version','profile'); ?></th>
				</tr>
			</thead>
			<tbody>
			<?php
				if ( isset( $core ) ) {
					echo '<tr><td>' . __('Core','profile') . '</td><td>Wordpress</td><td>' . $core['current'] . '</td><td>' . $core['new'] . '</td></tr>';
				}

				if ( isset( $theme ) ) {
					echo '<tr><td>' . __('Theme','profile') . '</td><td>' . $theme['name'] . '</td><td>' . $theme['current'] . '</td><td>' . $theme['new'] . '</td></tr>';
				}

				if ( isset( $plugins ) ) {
					foreach ($plugins as $key => $plugin) {
						echo '<tr><td>' . __('Plugin','profile') . '</td><td>' . $plugin['Name'] . '</td><td>' . $plugin['Version'] . '</td><td>' . $plugin['NewVersion'] . '</td></tr>';
					}
				}
			?>
			</tbody>
		</table>
	<?php
	} else {
		echo __('Congratulations, everything is up to date.','profile');
	}
}

// send automatic scheduled email
if ( ! wp_next_scheduled('wp_update_notify') ) {
	wp_schedule_event( time(), 'twicedaily', 'wp_update_notify' ); // hourly, daily and twicedaily
}

add_filter( 'wp_mail_content_type', function() { return 'text/html'; } );

add_action('wp_update_notify', 'notify_updates_email');
function notify_updates_email() {
	$options = get_option( 'imark_core');

	$update_data = wp_get_update_data();
	$count = $update_data['counts']['total'];

	if ( $count > 0 ) { 
		if ( !isset( $options['doUpdateNotify'] ) || $options['doUpdateNotify'] ) {
			wp_mail( 'haggaib@trdf.technion.ac.il', 'עידכונים וורדפרס ממתינים', $count . ' עידכונים ממתינים באתר: <a href="' . get_bloginfo( 'wpurl') . '">' . get_bloginfo( 'name') . '</a>');

			$options['doUpdateNotify'] = false;
			update_option( 'imark-core', $options );
		} else {
			$options['doUpdateNotify'] = true;
			update_option( 'imark-core', $options );		
		}
	}
}


add_filter( 'wp_get_update_data', 'get_wp_update_count', 10, 2 );
function get_wp_update_count( $update_data, $titles ) {
	$counts = array( 'plugins' => 0, 'themes' => 0, 'wordpress' => 0, 'translations' => 0 );

	if ( $plugins = current_user_can( 'manage_options' ) ) {
		$update_plugins = get_site_transient( 'update_plugins' );
		if ( ! empty( $update_plugins->response ) ) {
			$activePlugins = get_option( 'active_plugins' );
			$needsUpdate = array_intersect_key( $update_plugins->response, array_flip( $activePlugins ) );
			$counts['plugins'] = count( $needsUpdate );
		}
	}

	if ( $themes = current_user_can( 'manage_options' ) ) {
		$update_themes = get_site_transient( 'update_themes' );
		if ( ! empty( $update_themes->response ) )
			$counts['themes'] = count( $update_themes->response );
	}

	if ( ( $core = current_user_can( 'manage_options' ) ) && function_exists( 'get_core_updates' ) ) {
		$update_wordpress = get_core_updates( array('dismissed' => false) );
		if ( ! empty( $update_wordpress ) && ! in_array( $update_wordpress[0]->response, array('development', 'latest') ) && current_user_can('manage_options') )
			$counts['wordpress'] = 1;
	}

	if ( ( $core || $plugins || $themes ) && wp_get_translation_updates() )
		$counts['translations'] = 1;

	$counts['total'] = $counts['plugins'] + $counts['themes'] + $counts['wordpress'] + 0;
	$titles = array();
	if ( $counts['wordpress'] )
		$titles['wordpress'] = sprintf( __( '%d WordPress Update','profile'), $counts['wordpress'] );
	if ( $counts['plugins'] )
		$titles['plugins'] = sprintf( _n( '%d Plugin Update', '%d Plugin Updates', $counts['plugins'] ), $counts['plugins'] );
	if ( $counts['themes'] )
		$titles['themes'] = sprintf( _n( '%d Theme Update', '%d Theme Updates', $counts['themes'] ), $counts['themes'] );
	if ( $counts['translations'] )
		$titles['translations'] = __( 'Translation Updates' );

	$update_title = $titles ? esc_attr( implode( ', ', $titles ) ) : '';

	$update_data = array( 'counts' => $counts, 'title' => $update_title );

	return $update_data;
}
