<?php

// Add Translation Option
load_theme_textdomain( 'wpbootstrap', TEMPLATEPATH.'/languages' );
$locale = get_locale();
$locale_file = TEMPLATEPATH . "/languages/$locale.php";
if ( is_readable( $locale_file ) ) require_once( $locale_file );

// Clean up the WordPress Head
if( !function_exists( "wp_bootstrap_head_cleanup" ) ) {
  function wp_bootstrap_head_cleanup() {
    // remove header links
    remove_action( 'wp_head', 'feed_links_extra', 3 );                    // Category Feeds
    remove_action( 'wp_head', 'feed_links', 2 );                          // Post and Comment Feeds
    remove_action( 'wp_head', 'rsd_link' );                               // EditURI link
    remove_action( 'wp_head', 'wlwmanifest_link' );                       // Windows Live Writer
    remove_action( 'wp_head', 'index_rel_link' );                         // index link
    remove_action( 'wp_head', 'parent_post_rel_link', 10, 0 );            // previous link
    remove_action( 'wp_head', 'start_post_rel_link', 10, 0 );             // start link
    remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 ); // Links for Adjacent Posts
    remove_action( 'wp_head', 'wp_generator' );                           // WP version
  }
}
// Launch operation cleanup
add_action( 'init', 'wp_bootstrap_head_cleanup' );

// remove WP version from RSS
if( !function_exists( "wp_bootstrap_rss_version" ) ) {
  function wp_bootstrap_rss_version() { return ''; }
}
add_filter( 'the_generator', 'wp_bootstrap_rss_version' );

// Remove the […] in a Read More link
if( !function_exists( "wp_bootstrap_excerpt_more" ) ) {
  function wp_bootstrap_excerpt_more( $more ) {
    global $post;
    //return '...  <a href="'. get_permalink($post->ID) . '" class="more-link" title="Read '.get_the_title($post->ID).'">'.__('Read more','wpbootstrap').'</a>';
  }
}
add_filter('excerpt_more', 'wp_bootstrap_excerpt_more');

function wpdocs_custom_excerpt_length( $length ) {
    return 60;
}
add_filter( 'excerpt_length', 'wpdocs_custom_excerpt_length', 999 );

// Add WP 3+ Functions & Theme Support
if( !function_exists( "wp_bootstrap_theme_support" ) ) {
  function wp_bootstrap_theme_support() {
    add_theme_support( 'post-thumbnails' );      // wp thumbnails (sizes handled in functions.php)
    set_post_thumbnail_size( 125, 125, true );   // default thumb size
    add_theme_support( 'custom-background' );  // wp custom background
    add_theme_support( 'automatic-feed-links' ); // rss

    // Add post format support - if these are not needed, comment them out
    add_theme_support( 'post-formats',      // post formats
      array(
        'aside',   // title less blurb
        'gallery', // gallery of images
        'link',    // quick link to other site
        'image',   // an image
        'quote',   // a quick quote
        'status',  // a Facebook like status update
        'video',   // video
        'audio',   // audio
        'chat'     // chat transcript
      )
    );

    add_theme_support( 'menus' );            // wp menus

    register_nav_menus(                      // wp3+ menus
      array(
        'main_nav' => 'The Main Menu',   // main nav in header
		'main_nav_sm' => 'Menu sm',
        //'footer_links' => 'Footer Links' // secondary nav in footer
      )
    );
  }
}
// launching this stuff after theme setup
add_action( 'after_setup_theme','wp_bootstrap_theme_support' );

function wp_bootstrap_main_nav() {
  // Display the WordPress menu if available
  wp_nav_menu(
    array(
      'menu' => 'main_nav', /* menu name */
      'menu_class' => 'navbar-nav d-flex align-items-center',
      'theme_location' => 'main_nav', /* where in the theme it's assigned */
      'container' => 'false', /* container class */
      'fallback_cb' => 'wp_bootstrap_main_nav_fallback', /* menu fallback */
      'walker' => new Bootstrap_walker()
    )
  );
}





// this is the fallback for header menu
function wp_bootstrap_main_nav_fallback() {
  /* you can put a default here if you like */
}

// this is the fallback for footer menu
function wp_bootstrap_footer_links_fallback() {
  /* you can put a default here if you like */
}

// Shortcodes
require_once('library/shortcodes.php');

// Admin Functions (commented out by default)
// require_once('library/admin.php');         // custom admin functions

// Custom Backend Footer
add_filter('admin_footer_text', 'wp_bootstrap_custom_admin_footer');
function wp_bootstrap_custom_admin_footer() {
	//echo '<span id="footer-thankyou">Developed by <a href="http://320press.com" target="_blank">320press</a></span>. Built using <a href="http://themble.com/bones" target="_blank">Bones</a>.';
}

// adding it to the admin area
add_filter('admin_footer_text', 'wp_bootstrap_custom_admin_footer');

// Set content width
if ( ! isset( $content_width ) ) $content_width = 580;

/************* THUMBNAIL SIZE OPTIONS *************/

// Thumbnail sizes
//add_image_size( 'wpbs-featured', 780, 300, true );
//add_image_size( 'wpbs-featured-home', 970, 311, true);
add_image_size( 'c_slider', 1500, 750, true);
add_image_size( 'slider', 1500, 1500, true);
add_image_size( 'c_large', 1200, 1200, true);
add_image_size( 'large', 1200, 1200, false);
add_image_size( 'c_medium', 600, 600, true);
add_image_size( 'c_small', 360, 360, true);
add_image_size( 'c_small_false', 360, 360, false);
add_image_size( 'c_medium_false', 600, 600, false);
/*
to add more sizes, simply copy a line from above
and change the dimensions & name. As long as you
upload a "featured image" as large as the biggest
set width or height, all the other sizes will be
auto-cropped.

To call a different size, simply change the text
inside the thumbnail function.

For example, to call the 300 x 300 sized image,
we would use the function:
<?php the_post_thumbnail( 'bones-thumb-300' ); ?>
for the 600 x 100 image:
<?php the_post_thumbnail( 'bones-thumb-600' ); ?>

You can change the names and dimensions to whatever
you like. Enjoy!
*/

/************* ACTIVE SIDEBARS ********************/

// Sidebars & Widgetizes Areas
function wp_bootstrap_register_sidebars() {
  register_sidebar(array(
  	'id' => 'sidebar1',
  	'name' => 'Main Sidebar',
  	'description' => 'Used on every page BUT the homepage page template.',
  	'before_widget' => '<div id="%1$s" class="widget %2$s">',
  	'after_widget' => '</div>',
  	'before_title' => '<h4 class="widgettitle">',
  	'after_title' => '</h4>',
  ));

  register_sidebar(array(
  	'id' => 'sidebar2',
  	'name' => 'Homepage Sidebar',
  	'description' => 'Used only on the homepage page template.',
  	'before_widget' => '<div id="%1$s" class="widget %2$s">',
  	'after_widget' => '</div>',
  	'before_title' => '<h4 class="widgettitle">',
  	'after_title' => '</h4>',
  ));

  register_sidebar(array(
    'id' => 'footer-manip',
    'name' => 'Footer Manipulateurs',
    'before_widget' => '',
    'after_widget' => '',
    'before_title' => '',
    'after_title' => '',
  ));

  register_sidebar(array(
    'id' => 'footer-app',
    'name' => 'Footer Applications',
    'before_widget' => '',
    'after_widget' => '',
    'before_title' => '',
    'after_title' => '',
  ));

    register_sidebar(array(
        'id' => 'footer-neoditech',
        'name' => 'Footer Neoditech',
        'before_widget' => '',
        'after_widget' => '',
        'before_title' => '',
        'after_title' => '',
    ));



  /*
  to add more sidebars or widgetized areas, just copy
  and edit the above sidebar code. In order to call
  your new sidebar just use the following code:

  Just change the name to whatever your new
  sidebar's id is, for example:

  To call the sidebar in your template, you can just copy
  the sidebar.php file and rename it to your sidebar's name.
  So using the above example, it would be:
  sidebar-sidebar2.php

  */
} // don't remove this bracket!
add_action( 'widgets_init', 'wp_bootstrap_register_sidebars' );

/************* COMMENT LAYOUT *********************/

// Comment Layout
function wp_bootstrap_comments($comment, $args, $depth) {
   $GLOBALS['comment'] = $comment; ?>
	<li <?php comment_class(); ?>>
		<article id="comment-<?php comment_ID(); ?>" class="clearfix">
			<div class="comment-author vcard clearfix">
				<div class="avatar col-sm-3">
					<?php echo get_avatar( $comment, $size='75' ); ?>
				</div>
				<div class="col-sm-9 comment-text">
					<?php printf('<h4>%s</h4>', get_comment_author_link()) ?>
					<?php edit_comment_link(__('Edit','wpbootstrap'),'<span class="edit-comment btn btn-sm btn-info"><i class="glyphicon-white glyphicon-pencil"></i>','</span>') ?>

                    <?php if ($comment->comment_approved == '0') : ?>
       					<div class="alert-message success">
          				<p><?php _e('Your comment is awaiting moderation.','wpbootstrap') ?></p>
          				</div>
					<?php endif; ?>

                    <?php comment_text() ?>

                    <time datetime="<?php echo comment_time('Y-m-j'); ?>"><a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ) ?>"><?php comment_time('F jS, Y'); ?> </a></time>

					<?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
                </div>
			</div>
		</article>
    <!-- </li> is added by wordpress automatically -->
<?php
} // don't remove this bracket!

// Display trackbacks/pings callback function
function list_pings($comment, $args, $depth) {
       $GLOBALS['comment'] = $comment;
?>
        <li id="comment-<?php comment_ID(); ?>"><i class="icon icon-share-alt"></i>&nbsp;<?php comment_author_link(); ?>
<?php

}

/************* SEARCH FORM LAYOUT *****************/

/****************** password protected post form *****/

add_filter( 'the_password_form', 'wp_bootstrap_custom_password_form' );

function wp_bootstrap_custom_password_form() {
	global $post;
	$label = 'pwbox-'.( empty( $post->ID ) ? rand() : $post->ID );
	$o = '<div class="clearfix"><form class="protected-post-form" action="' . get_option('siteurl') . '/wp-login.php?action=postpass" method="post">
	' . '<p>' . __( "This post is password protected. To view it please enter your password below:" ,'wpbootstrap') . '</p>' . '
	<label for="' . $label . '">' . __( "Password:" ,'wpbootstrap') . ' </label><div class="input-append"><input name="post_password" id="' . $label . '" type="password" size="20" /><input type="submit" name="Submit" class="btn btn-primary" value="' . esc_attr__( "Submit",'wpbootstrap' ) . '" /></div>
	</form></div>
	';
	return $o;
}

/*********** update standard wp tag cloud widget so it looks better ************/

add_filter( 'widget_tag_cloud_args', 'wp_bootstrap_my_widget_tag_cloud_args' );

function wp_bootstrap_my_widget_tag_cloud_args( $args ) {
	$args['number'] = 20; // show less tags
	$args['largest'] = 9.75; // make largest and smallest the same - i don't like the varying font-size look
	$args['smallest'] = 9.75;
	$args['unit'] = 'px';
	return $args;
}

// filter tag clould output so that it can be styled by CSS
function wp_bootstrap_add_tag_class( $taglinks ) {
    $tags = explode('</a>', $taglinks);
    $regex = "#(.*tag-link[-])(.*)(' title.*)#e";

    foreach( $tags as $tag ) {
    	$tagn[] = preg_replace($regex, "('$1$2 label tag-'.get_tag($2)->slug.'$3')", $tag );
    }

    $taglinks = implode('</a>', $tagn);

    return $taglinks;
}

add_action( 'wp_tag_cloud', 'wp_bootstrap_add_tag_class' );

add_filter( 'wp_tag_cloud','wp_bootstrap_wp_tag_cloud_filter', 10, 2) ;

function wp_bootstrap_wp_tag_cloud_filter( $return, $args )
{
  return '<div id="tag-cloud">' . $return . '</div>';
}

// Enable shortcodes in widgets
add_filter( 'widget_text', 'do_shortcode' );

// Disable jump in 'read more' link
function wp_bootstrap_remove_more_jump_link( $link ) {
	$offset = strpos($link, '#more-');
	if ( $offset ) {
		$end = strpos( $link, '"',$offset );
	}
	if ( $end ) {
		$link = substr_replace( $link, '', $offset, $end-$offset );
	}
	return $link;
}
add_filter( 'the_content_more_link', 'wp_bootstrap_remove_more_jump_link' );

// Remove height/width attributes on images so they can be responsive
add_filter( 'post_thumbnail_html', 'wp_bootstrap_remove_thumbnail_dimensions', 10 );
add_filter( 'image_send_to_editor', 'wp_bootstrap_remove_thumbnail_dimensions', 10 );

function wp_bootstrap_remove_thumbnail_dimensions( $html ) {
    $html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
    return $html;
}

// Add the Meta Box to the homepage template
/*function wp_bootstrap_add_homepage_meta_box() {
	global $post;

	// Only add homepage meta box if template being used is the homepage template
	// $post_id = isset($_GET['post']) ? $_GET['post'] : (isset($_POST['post_ID']) ? $_POST['post_ID'] : "");
	$post_id = $post->ID;
	$template_file = get_post_meta($post_id,'_wp_page_template',TRUE);

	if ( $template_file == 'page-homepage.php' ){
	    add_meta_box(
	        'homepage_meta_box', // $id
	        'Optional Homepage Tagline', // $title
	        'wp_bootstrap_show_homepage_meta_box', // $callback
	        'page', // $page
	        'normal', // $context
	        'high'); // $priority
    }
}*/

//add_action( 'add_meta_boxes', 'wp_bootstrap_add_homepage_meta_box' );

// Field Array
$prefix = 'custom_';
$custom_meta_fields = array(
    array(
        'label'=> 'Homepage tagline area',
        'desc'  => 'Displayed underneath page title. Only used on homepage template. HTML can be used.',
        'id'    => $prefix.'tagline',
        'type'  => 'textarea'
    )
);

// The Homepage Meta Box Callback
function wp_bootstrap_show_homepage_meta_box() {
  global $custom_meta_fields, $post;

  // Use nonce for verification
  wp_nonce_field( basename( __FILE__ ), 'wpbs_nonce' );

  // Begin the field table and loop
  echo '<table class="form-table">';

  foreach ( $custom_meta_fields as $field ) {
      // get value of this field if it exists for this post
      $meta = get_post_meta($post->ID, $field['id'], true);
      // begin a table row with
      echo '<tr> 
              <th><label for="'.$field['id'].'">'.$field['label'].'</label></th> 
              <td>';
              switch($field['type']) {
                  // text
                  case 'text':
                      echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.$meta.'" size="60" /> 
                          <br /><span class="description">'.$field['desc'].'</span>';
                  break;

                  // textarea
                  case 'textarea':
                      echo '<textarea name="'.$field['id'].'" id="'.$field['id'].'" cols="80" rows="4">'.$meta.'</textarea> 
                          <br /><span class="description">'.$field['desc'].'</span>';
                  break;
              } //end switch
      echo '</td></tr>';
  } // end foreach
  echo '</table>'; // end table
}

// Save the Data
function wp_bootstrap_save_homepage_meta( $post_id ) {

    global $custom_meta_fields;

    // verify nonce
    if ( !isset( $_POST['wpbs_nonce'] ) || !wp_verify_nonce($_POST['wpbs_nonce'], basename(__FILE__)) )
        return $post_id;

    // check autosave
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
        return $post_id;

    // check permissions
    if ( 'page' == $_POST['post_type'] ) {
        if ( !current_user_can( 'edit_page', $post_id ) )
            return $post_id;
        } elseif ( !current_user_can( 'edit_post', $post_id ) ) {
            return $post_id;
    }

    // loop through fields and save the data
    foreach ( $custom_meta_fields as $field ) {
        $old = get_post_meta( $post_id, $field['id'], true );
        $new = $_POST[$field['id']];

        if ($new && $new != $old) {
            update_post_meta( $post_id, $field['id'], $new );
        } elseif ( '' == $new && $old ) {
            delete_post_meta( $post_id, $field['id'], $old );
        }
    } // end foreach
}
add_action( 'save_post', 'wp_bootstrap_save_homepage_meta' );

// Add thumbnail class to thumbnail links
function wp_bootstrap_add_class_attachment_link( $html ) {
    $postid = get_the_ID();
    $html = str_replace( '<a','<a class="thumbnail"',$html );
    return $html;
}
add_filter( 'wp_get_attachment_link', 'wp_bootstrap_add_class_attachment_link', 10, 1 );

// Add lead class to first paragraph
function wp_bootstrap_first_paragraph( $content ){
    global $post;

    // if we're on the homepage, don't add the lead class to the first paragraph of text
    if( is_page_template( 'page-homepage.php' ) )
        return $content;
    else
        return preg_replace('/<p([^>]+)?>/', '<p$1 class="lead">', $content, 1);
}
//add_filter( 'the_content', 'wp_bootstrap_first_paragraph' );

// Menu output mods
class Bootstrap_walker extends Walker_Nav_Menu{

  function start_el(&$output, $object, $depth = 0, $args = Array(), $current_object_id = 0){

	 global $wp_query;
	 $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

	 $class_names = $value = '';

		// If the item has children, add the dropdown class for bootstrap
		if ( $args->has_children ) {
			$class_names = "dropdown depth_".$depth." ";
		}

		$classes = empty( $object->classes ) ? array() : (array) $object->classes;

		$class_names .= join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $object ) );
		$class_names = ' class="nav-item '. esc_attr( $class_names ) . '"';

   	$output .= $indent . '<li id="menu-item-'. $object->ID . '"' . $value . $class_names .'>';

   	$attributes  = ! empty( $object->attr_title ) ? ' title="'  . esc_attr( $object->attr_title ) .'"' : '';
   	$attributes .= ! empty( $object->target )     ? ' target="' . esc_attr( $object->target     ) .'"' : '';
   	$attributes .= ! empty( $object->xfn )        ? ' rel="'    . esc_attr( $object->xfn        ) .'"' : '';
   	$attributes .= ! empty( $object->url )        ? ' href="'   . esc_attr( $object->url        ) .'"' : '';

   	// if the item has children add these two attributes to the anchor tag
   	if ( $args->has_children) {
		  $attributes .= ' class="Xdropdown-toggle nav-link drop" Xdata-bs-toggle="dropdown"';
    }else{
        $attributes .= ' class="nav-link"';
    }

    $item_output = $args->before;
    $item_output .= '<a'. $attributes .'>';
    $item_output .= $args->link_before .apply_filters( 'the_title', $object->title, $object->ID );
    $item_output .= $args->link_after;

    // if the item has children add the caret just before closing the anchor tag
    if ( $args->has_children ) {
    	$item_output .= '<b class="caret"></b></a>';
    }
    else {
    	$item_output .= '</a>';
    }

    $item_output .= $args->after;

    $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $object, $depth, $args );
  } // end start_el function

  function start_lvl(&$output, $depth = 0, $args = Array()) {
    $indent = str_repeat("\t", $depth);
	if($depth==0){
		$output .= "\n$indent<ul class=\"dropdown-menu\">\n";
	}else{
		$output .= "\n$indent<ul class=\"dropdown-submenu\">\n";
	}
  }

	function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ){
    $id_field = $this->db_fields['id'];
    if ( is_object( $args[0] ) ) {
        $args[0]->has_children = ! empty( $children_elements[$element->$id_field] );
    }
    return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
  }
}


add_editor_style('editor-style.css');

function wp_bootstrap_add_active_class($classes, $item) {
	if( $item->menu_item_parent == 0 && in_array('current-menu-item', $classes) ) {
    $classes[] = "active";
	}

  return $classes;
}

// Add Twitter Bootstrap's standard 'active' class name to the active nav link item
add_filter('nav_menu_css_class', 'wp_bootstrap_add_active_class', 10, 2 );

// enqueue styles
if( !function_exists("wp_bootstrap_theme_styles") ) {
    function wp_bootstrap_theme_styles() {
        // This is the compiled css file from LESS - this means you compile the LESS file locally and put it in the appropriate directory if you want to make any changes to the master bootstrap.css.
        wp_register_style( 'wpbs', get_template_directory_uri() . '/library/dist/css/styles.f6413c85.min.css', array(), '1.0', 'all' );
        wp_enqueue_style( 'wpbs' );

        // For child themes
        wp_register_style( 'wpbs-style', get_stylesheet_directory_uri() . '/style.css', array(), '1.0', 'all' );
        wp_enqueue_style( 'wpbs-style' );
    }
}
//add_action( 'wp_enqueue_scripts', 'wp_bootstrap_theme_styles' );

// enqueue javascript
if( !function_exists( "wp_bootstrap_theme_js" ) ) {
  function wp_bootstrap_theme_js(){

    if ( !is_admin() ){
      if ( is_singular() AND comments_open() AND ( get_option( 'thread_comments' ) == 1) )
        wp_enqueue_script( 'comment-reply' );
    }

    // This is the full Bootstrap js distribution file. If you only use a few components that require the js files consider loading them individually instead
    wp_register_script( 'bootstrap',
      get_template_directory_uri() . '/bower_components/bootstrap/dist/js/bootstrap.js',
      array('jquery'),
      '1.2' );

    wp_register_script( 'wpbs-js',
      get_template_directory_uri() . '/library/dist/js/scripts.d1e3d952.min.js',
      array('bootstrap'),
      '1.2' );

    wp_register_script( 'modernizr',
      get_template_directory_uri() . '/bower_components/modernizer/modernizr.js',
      array('jquery'),
      '1.2' );

    //wp_enqueue_script( 'bootstrap' );
    //wp_enqueue_script( 'wpbs-js' );
    //wp_enqueue_script( 'modernizr' );

  }
}
//add_action( 'wp_enqueue_scripts', 'wp_bootstrap_theme_js' );

// Get <head> <title> to behave like other themes
function wp_bootstrap_wp_title( $title, $sep ) {
  global $paged, $page;

  if ( is_feed() ) {
    return $title;
  }

  // Add the site name.
  $title .= get_bloginfo( 'name' );

  // Add the site description for the home/front page.
  $site_description = get_bloginfo( 'description', 'display' );
  if ( $site_description && ( is_home() || is_front_page() ) ) {
    $title = "$title $sep $site_description";
  }

  // Add a page number if necessary.
  if ( $paged >= 2 || $page >= 2 ) {
    $title = "$title $sep " . sprintf( __( 'Page %s', 'wpbootstrap' ), max( $paged, $page ) );
  }

  return $title;
}
add_filter( 'wp_title', 'wp_bootstrap_wp_title', 10, 2 );

// Related Posts Function (call using wp_bootstrap_related_posts(); )
function wp_bootstrap_related_posts() {
  echo '<ul id="bones-related-posts">';
  global $post;
  $tags = wp_get_post_tags($post->ID);
  if($tags) {
    foreach($tags as $tag) { $tag_arr .= $tag->slug . ','; }
        $args = array(
          'tag' => $tag_arr,
          'numberposts' => 5, /* you can change this to show more */
          'post__not_in' => array($post->ID)
      );
        $related_posts = get_posts($args);
        if($related_posts) {
          foreach ($related_posts as $post) : setup_postdata($post); ?>
              <li class="related_post"><a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
          <?php endforeach; }
      else { ?>
            <li class="no_related_post">No Related Posts Yet!</li>
    <?php }
  }
  wp_reset_query();
  echo '</ul>';
}

// Numeric Page Navi (built into the theme by default)
function wp_bootstrap_page_navi($before = '', $after = '') {
  global $wpdb, $wp_query;
  $request = $wp_query->request;
  $posts_per_page = intval(get_query_var('posts_per_page'));
  $paged = intval(get_query_var('paged'));
  $numposts = $wp_query->found_posts;
  $max_page = $wp_query->max_num_pages;
  if ( $numposts <= $posts_per_page ) { return; }
  if(empty($paged) || $paged == 0) {
    $paged = 1;
  }
  $pages_to_show = 7;
  $pages_to_show_minus_1 = $pages_to_show-1;
  $half_page_start = floor($pages_to_show_minus_1/2);
  $half_page_end = ceil($pages_to_show_minus_1/2);
  $start_page = $paged - $half_page_start;
  if($start_page <= 0) {
    $start_page = 1;
  }
  $end_page = $paged + $half_page_end;
  if(($end_page - $start_page) != $pages_to_show_minus_1) {
    $end_page = $start_page + $pages_to_show_minus_1;
  }
  if($end_page > $max_page) {
    $start_page = $max_page - $pages_to_show_minus_1;
    $end_page = $max_page;
  }
  if($start_page <= 0) {
    $start_page = 1;
  }

  echo $before.'<ul class="pagination">'."";
  if ($paged > 1) {
    $first_page_text = "&laquo";
    //echo '<li class="prev page-item"><a class="page-link" href="'.get_pagenum_link().'" title="' . __('First','wpbootstrap') . '">'.$first_page_text.'</a></li>';
  }

  $prevposts = get_previous_posts_link( __('&laquo;','wpbootstrap') );
  if($prevposts) {
      //echo '<li>' . $prevposts  . '</li>';
       }
  else {
      //echo '<li class="disabled page-item"><a  class="page-link" href="#">' . __('&laquo;','wpbootstrap') . '</a></li>';
  }

  for($i = $start_page; $i  <= $end_page; $i++) {
    if($i == $paged) {
      echo '<li class="active page-item"><a  class="page-link" href="#">'.$i.'</a></li>';
    } else {
      echo '<li><a  class="page-link" href="'.get_pagenum_link($i).'">'.$i.'</a></li>';
    }
  }


  /*echo '<li class="page-item">';
  next_posts_link( __('&raquo;','wpbootstrap') );
  echo '</li>';*/
  if ($end_page < $max_page) {
    $last_page_text = "&raquo;";
    echo '<li class="next page-item"><a  class="page-link" href="'.get_pagenum_link($max_page).'" title="' . __('Last','wpbootstrap') . '">'.$last_page_text.'</a></li>';
  }
  echo '</ul>'.$after."";
}

// Remove <p> tags from around images
function wp_bootstrap_filter_ptags_on_images( $content ){
  return preg_replace( '/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content );
}
add_filter( 'the_content', 'wp_bootstrap_filter_ptags_on_images' );


          function add_custom_query_var($vars) {
              $vars[] = "page";

              return $vars;
          }

          add_filter('query_vars', 'add_custom_query_var');

function paginate($url, $link, $total, $current, $adj=3) {
// Initialisation des variables
$prev = $current - 1; // numéro de la page précédente
$next = $current + 1; // numéro de la page suivante
$penultimate = $total - 1; // numéro de l'avant-dernière page
$pagination = ''; // variable retour de la fonction : vide tant qu'il n'y a pas au moins 2 pages

if ($total > 12) {
  // Remplissage de la chaîne de caractères à retourner
  $pagination .= "<ul class=\"pagination\">\n";

  /* =================================
   *  Affichage du bouton [précédent]
   * ================================= */
  if ($current == 2) {
	  // la page courante est la 2, le bouton renvoie donc sur la page 1, remarquez qu'il est inutile de mettre $url{$link}1
	  $pagination .= "<li  class=\"page-item\"><a  class=\"page-link\" href=\"{$url}\">◄</a></li>";
  } elseif ($current > 2) {
	  // la page courante est supérieure à 2, le bouton renvoie sur la page dont le numéro est immédiatement inférieur
	  $pagination .= "<li  class=\"page-item\"><a  class=\"page-link\" href=\"{$url}{$link}{$prev}\">◄</a></li>";
  } else {
	  // dans tous les autres, cas la page est 1 : désactivation du bouton [précédent]
	  $pagination .= '<li class="inactive page-item"><a class="page-link">◄</a></li>';
  }

  /**
   * Début affichage des pages, l'exemple reprend le cas de 3 numéros de pages adjacents (par défaut) de chaque côté du numéro courant
   * - CAS 1 : il y a au plus 12 pages, insuffisant pour faire une troncature
   * - CAS 2 : il y a au moins 13 pages, on effectue la troncature pour afficher 11 numéros de pages au total
   */

  /* ===============================================
   *  CAS 1 : au plus 12 pages -> pas de troncature
   * =============================================== */
  if ($total < 7 + ($adj * 2)) {
	  // Ajout de la page 1 : on la traite en dehors de la boucle pour n'avoir que index.php au lieu de index.php?p=1 et ainsi éviter le duplicate content
	  $pagination .= ($current == 1) ? '<li class="active page-item"><a>1</a></li>' : "<li class=\"page-item\"><a href=\"{$url}\">1</a></li>"; // Opérateur ternaire : (condition) ? 'valeur si vrai' : 'valeur si fausse'

	  // Pour les pages restantes on utilise itère
	  for ($i=2; $i<=$total; $i++) {
		  if ($i == $current) {
			  // Le numéro de la page courante est mis en évidence (cf. CSS)
			  $pagination .= "<li class=\"active page-item \"><a class=\"page-link\">{$i}</a></li>";
		  } else {
			  // Les autres sont affichées normalement
			  $pagination .= "<li class=\"page-item\"><a  class=\"page-link\" href=\"{$url}{$link}{$i}\">{$i}</a></li>";
		  }
	  }
  }
  /* =========================================
   *  CAS 2 : au moins 13 pages -> troncature
   * ========================================= */
  else {
	  /**
	   * Troncature 1 : on se situe dans la partie proche des premières pages, on tronque donc la fin de la pagination.
	   * l'affichage sera de neuf numéros de pages à gauche ... deux à droite
	   * 1 2 3 4 5 6 7 8 9 … 16 17
	   */
	  if ($current < 2 + ($adj * 2)) {
		  // Affichage du numéro de page 1
		  $pagination .= ($current == 1) ? "<li class=\"active page-item\">1</li>" : "<li><a href=\"{$url}\">1</a></li>";

		  // puis des huit autres suivants
		  for ($i = 2; $i < 4 + ($adj * 2); $i++) {
			  if ($i == $current) {
				  $pagination .= "<li class=\"active page-item\"><span  class=\"page-link\">{$i}</span></li>";
			  } else {
				  $pagination .= "<li class=\"page-item\"><a  class=\"page-link\" href=\"{$url}{$link}{$i}\">{$i}</a></li>";
			  }
		  }

		  // ... pour marquer la troncature
		  $pagination .= '&hellip;';

		  // et enfin les deux derniers numéros
		  $pagination .= "<li class=\"page-item\"><a  class=\"page-link\" href=\"{$url}{$link}{$penultimate}\">{$penultimate}</a></li>";
		  $pagination .= "<li class=\"page-item\"><a  class=\"page-link\" href=\"{$url}{$link}{$total}\">{$total}</a></li>";
	  }
	  /**
	   * Troncature 2 : on se situe dans la partie centrale de notre pagination, on tronque donc le début et la fin de la pagination.
	   * l'affichage sera deux numéros de pages à gauche ... sept au centre ... deux à droite
	   * 1 2 … 5 6 7 8 9 10 11 … 16 17
	   */
	  elseif ( (($adj * 2) + 1 < $current) && ($current < $total - ($adj * 2)) ) {
		  // Affichage des numéros 1 et 2
		  $pagination .= "<li class=\"page-item\"><a  class=\"page-link\" href=\"{$url}\">1</a></li>";
		  $pagination .= "<li class=\"page-item\"><a  class=\"page-link\" href=\"{$url}{$link}2\">2</a></li>";
		  $pagination .= '&hellip;';

		  // les pages du milieu : les trois précédant la page courante, la page courante, puis les trois lui succédant
		  for ($i = $current - $adj; $i <= $current + $adj; $i++) {
			  if ($i == $current) {
				  $pagination .= "<li class=\"active page-item\">{$i}</li>";
			  } else {
				  $pagination .= "<li class=\"page-item\"><a  class=\"page-link\" href=\"{$url}{$link}{$i}\">{$i}</a></li>";
			  }
		  }

		  $pagination .= '&hellip;';

		  // et les deux derniers numéros
		  $pagination .= "<li class=\"page-item\"><a  class=\"page-link\" href=\"{$url}{$link}{$penultimate}\">{$penultimate}</a></li>";
		  $pagination .= "<li class=\"page-item\"><a  class=\"page-link\" href=\"{$url}{$link}{$total}\">{$total}</a></li>";
	  }
	  /**
	   * Troncature 3 : on se situe dans la partie de droite, on tronque donc le début de la pagination.
	   * l'affichage sera deux numéros de pages à gauche ... neuf à droite
	   * 1 2 … 9 10 11 12 13 14 15 16 17
	   */
	  else {
		  // Affichage des numéros 1 et 2
		  $pagination .= "<li class=\"page-item\"><a  class=\"page-link\" href=\"{$url}\">1</a>";
		  $pagination .= "<li class=\"page-item\"><a  class=\"page-link\" href=\"{$url}{$link}2\">2</a></li>";
		  $pagination .= '&hellip;';

		  // puis des neuf derniers numéros
		  for ($i = $total - (2 + ($adj * 2)); $i <= $total; $i++) {
			  if ($i == $current) {
				  $pagination .= "<li class=\"active page-item\">{$i}</li>";
			  } else {
				  $pagination .= "<li class=\"page-item\"><a  class=\"page-link\" href=\"{$url}{$link}{$i}\">{$i}</a></li>";
			  }
		  }
	  }
  }

  /* ===============================
   *  Affichage du bouton [suivant]
   * =============================== */
  if ($current == $total)
	  $pagination .= "<li class=\"inactive page-item\"><a  class=\"page-link\">►</a></li>\n";
  else
	  $pagination .= "<li class=\" page-item\"><a  class=\"page-link\" href=\"{$url}{$link}{$next}\">►</a>\n";

  // Fermeture de la <div> d'affichage
  $pagination .= "</ul\n";
}

return ($pagination);
}

function compte_les_posts_d_une_categorie($cat_id) {
$resultat=get_post_count_by_single_cat($cat_id);
return $resultat;
}





function load_wp_media_files() {
wp_enqueue_media();
}
add_action( 'admin_enqueue_scripts', 'load_wp_media_files' );

/* Autoriser les fichiers SVG */
function wpc_mime_types($mimes) {
	$mimes['svg'] = 'image/svg+xml';
	return $mimes;
}
add_filter('upload_mimes', 'wpc_mime_types');



//[panneau]
function panneau_func(){
	$pane_main_img = get_field('pane_main_img');
	$panes = get_field('panes');

	//smartphones
	$pane_content .= '
	<div class="row visible-sm visible-xs">
		<div class="col-xs-12 text-center">
			<img src="'.$pane_main_img['sizes']['large'].'" alt="" class="img-responsive">
		</div>
	';
	foreach($panes as $pane){
		$txt = $pane['pane_txt'];
		$pane_content .= '<div class="col-xs-12 padded post_content">
			'.$txt.'
		</div>';
	}
	$pane_content .= '</div>';


	//lg & md
	$pane_content .= '<div class="row panes row-eq-height hidden-sm hidden-xs">';
	$nb=1;
	foreach($panes as $pane){
		$img = $pane['pane_img'];
		$txt = $pane['pane_txt'];
		$title = $pane['pane_title'];
		$pane_content .= '
		<div class="col-md-4  pane nopadding wow fadeInUp" data-wow-duration="1s" data-wow-delay="0.'.$nb.'s">
			<img src="'.$img['sizes']['large'].'" alt="" class="img-responsive">
			<div class="pane_title padded">
				<div class="pane_title_txt">
					<span class=""><i class="icon-click white"></i></span>
					<h3>'.$title.'</h3>
					
				</div>
			</div>
			<div class="pane_hover padded white">
			<h3>'.$title.'</h3>
			'.$txt.'
			</div>
		</div>
		';
	$nb++;
	}
	$pane_content .= '</div>';



return $pane_content;
}
add_shortcode( 'panneau', 'panneau_func' );


function getLivePictures($count = 8){
	/** Instagram **/
	// https://www.instagram.com/liguecontrelecancervendee/?hl=fr`
    //17841400592706632
    $accessToken = '6444939764.1677ed0.dd0319db01444519b150b455ac96f57c';
	$parameters = array(
		//'client_id' => $clientId,
		'access_token' => $accessToken,
		'count' => $count,
	);
	$queryString = array();
	foreach ($parameters as $key => $value) {
		$queryString[] = $key.'='.rawurlencode($value);
	}

	$url = sprintf('https://api.instagram.com/v1/users/self/media/recent/?%s', implode('&', $queryString));
	var_dump($url);
	$curl_handle = curl_init();
	curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
	//curl_setopt($curl_handle, CURLOPT_USERPWD, $apiKey . ':' . $secretKey);
	curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array(
		'Content-Type: application/json'
	));
	curl_setopt($curl_handle, CURLOPT_URL, $url);
	curl_setopt($curl_handle, CURLOPT_POST, 0);
	$buffer = curl_exec($curl_handle);
	$response_code = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
	curl_close($curl_handle);
	if($response_code==200){
		$content = json_decode($buffer);
		//var_dump($content);
		foreach ($content->data as $photo) {
			$items[$photo->created_time.'_i'] = $photo;
		}
	}
	return $items;
}




function my_own_gallery($output, $attr) {
    global $post;

    static $instance = 0;
    $instance++;

    // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
    if ( isset( $attr['orderby'] ) ) {
        $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
        if ( !$attr['orderby'] )
            unset( $attr['orderby'] );
    }

    extract(shortcode_atts(array(
        'order'      => 'ASC',
        'orderby'    => 'menu_order ID',
        'id'         => $post->ID,
        'itemtag'    => 'div',
        'icontag'    => 'div',
        'captiontag' => 'div',
        'columns'    => 3,
        'size'       => 'cm_medium',
        'include'    => '',
        'exclude'    => ''
    ), $attr));

    $id = intval($id);
    if ( 'RAND' == $order )
        $orderby = 'none';

    if ( !empty($include) ) {
        $include = preg_replace( '/[^0-9,]+/', '', $include );
        $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );

        $attachments = array();
        foreach ( $_attachments as $key => $val ) {
            $attachments[$val->ID] = $_attachments[$key];
        }
    } elseif ( !empty($exclude) ) {
        $exclude = preg_replace( '/[^0-9,]+/', '', $exclude );
        $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
    } else {
        $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
    }

    if ( empty($attachments) )
        return '';

    if ( is_feed() ) {
        $output = "\n";
        foreach ( $attachments as $att_id => $attachment )
            $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
        return $output;
    }

    $itemtag = tag_escape($itemtag);
    $captiontag = tag_escape($captiontag);
    $columns = intval($columns);
    $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
    $float = is_rtl() ? 'right' : 'left';

    $selector = "gallery-{$instance}";

    $gallery_style = $gallery_div = '';
    if ( apply_filters( 'use_default_gallery_style', true ) )
    $size_class = sanitize_html_class( $size );
    $gallery_div = "<div class='gallery_part container'><div class='gallery row'>";
    $output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div );

    $i = 0;
    foreach ( $attachments as $id => $attachment ) {

		$alt = $attachment->post_title;
		$src= wp_get_attachment_image_src($id,'c_medium');
		$large_src= wp_get_attachment_image_src($id,'slider');
		//var_dump($alt);
		//exit;
		switch($columns){
			case 6:
			$class_col = 'col-md-2';
			break;
			case 5:
			$class_col = 'col-md-2';
			break;
			case 4:
			$class_col = 'col-md-3';
			break;
			case 3:
			$class_col = 'col-md-4';
			break;
			case 2:
			$class_col = 'col-md-6';
			break;
		}


		$output .= '<div class="col-6 col-sm-6 '.$class_col.' p-3">
		<a href="'.$large_src[0].'"  data-lightbox="lightbox" class="gallery_img_link" data-title="'.$alt.'">
		<img src="'.$src[0].'" alt="'.$alt.'" class="img-fluid">
		</a>
		</div>';

        if ( $columns > 0 && ++$i % $columns == 0 )
            $output .= '</div><div class="row gallery">';
    }

    $output .= "
            <br style='clear: both;' />
        </div></div>\n";

    return $output;
}
add_filter("post_gallery", "my_own_gallery",10,2);


add_action( 'wp_login_failed', 'pippin_login_fail' );  // hook failed login
function pippin_login_fail( $username ) {
     $referrer = $_SERVER['HTTP_REFERER'];  // where did the post submission come from?
     // if there's a valid referrer, and it's not the default log-in screen
	 //var_dump($referrer);exit;
     if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ) {
          wp_redirect($referrer. '?login=failed' );  // let's append some information (login=failed) to the URL for the theme to use
          exit;
     }
}


if( function_exists('acf_add_options_page') ) {

    acf_add_options_page(array(
        'page_title' 	=> 'Options',
        'menu_title'	=> 'Options du site',
        'menu_slug' 	=> 'theme-general-settings',
        'capability'	=> 'edit_posts',
        'redirect'		=> false
    ));

    acf_add_options_sub_page(array(
        'page_title' 	=> 'Nos produits',
        'menu_title'	=> 'Nos produits',
        'parent_slug'	=> 'theme-general-settings',
    ));

    acf_add_options_sub_page(array(
        'page_title' 	=> 'Informations',
        'menu_title'	=> 'Informations',
        'parent_slug'	=> 'theme-general-settings',
    ));

    acf_add_options_sub_page(array(
        'page_title' 	=> 'Actualités',
        'menu_title'	=> 'Actualités',
        'parent_slug'	=> 'theme-general-settings',
    ));

    acf_add_options_sub_page(array(
        'page_title' 	=> 'Activités',
        'menu_title'	=> 'Activités',
        'parent_slug'	=> 'theme-general-settings',
    ));

}



//select with custom post type for cf7
function pine_dynamic_select_field_values ( $scanned_tag, $replace ) {
    if ( $scanned_tag['name'] != 'produits' )
        return $scanned_tag;
    $rows = get_posts(
        array(
            'post_type' => 'produit',
            'posts_per_page' => -1,
        )
    );
    if ( ! $rows )
        return $scanned_tag;
    foreach ( $rows as $row ) {
        //$date_debut = get_field('date_debut_evenement',$row->ID);
        //if($date_debut>date('Ymd\THis')) {
            //$date_d = strftime("%A %d %B %Y", strtotime($date_debut));
            $title = $row->post_title;
            $scanned_tag['raw_values'][] = $row->post_title . '|' . $title;
        //}
    }
    $pipes = new WPCF7_Pipes($scanned_tag['raw_values']);
    $scanned_tag['values'] = $pipes->collect_befores();
    $scanned_tag['pipes'] = $pipes;
    return $scanned_tag;
}
add_filter( 'wpcf7_form_tag', 'pine_dynamic_select_field_values', 10, 2);


//select with taxonomies for cf7
function pine_dynamic_select_field_values_taxo ( $scanned_tag, $replace ) {
    //
    $taxo_fields = array('quantites','stocks','transports',);
    $taxonomies = array(
            'quantites' => 'pdt_qtty' ,
        'stocks' => 'pdt_stock' ,
        'transports' => 'pdt_transport',
    );
    //if ( $scanned_tag['name'] != 'quantites' )
    if(!in_array($scanned_tag['name'],$taxo_fields))
        return $scanned_tag;

    $current = $scanned_tag['name'];
    $rows = get_terms( array(
        'taxonomy' => $taxonomies[$current],
        'hide_empty' => false,
    ) );
    if ( ! $rows )
        return $scanned_tag;
    foreach ( $rows as $row ) {
        $title = $row->name;
        $slug = $row->slug;
        $scanned_tag['raw_values'][] = $title . '|' . $slug;
    }
    $pipes = new WPCF7_Pipes($scanned_tag['raw_values']);
    $scanned_tag['values'] = $pipes->collect_befores();
    $scanned_tag['pipes'] = $pipes;
    return $scanned_tag;
}
add_filter( 'wpcf7_form_tag', 'pine_dynamic_select_field_values_taxo', 10, 2);


?>
