<?php
/*
This file is part of sandbox.

sandbox is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.

sandbox is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with sandbox. If not, see http://www.gnu.org/licenses/.
*/

/**
 * Define content width
 * ====================
 */
if ( !isset( $content_width ) ) {
	$content_width = 1359;
}
/**
 * Ajax hooks
 * ==========
 */

/**
 * Theme setup hook
 * ================
 */
add_action('after_setup_theme', 'sandbox_setup_theme');

function sandbox_setup_theme() {

  // Translate, if applicable
  load_theme_textdomain('sandbox', get_template_directory() . '/translations');

  /**
   * Theme supports
   */
  add_theme_support('post-thumbnails');
  add_theme_support('custom-background');
  add_theme_support('html5', array('comment-list', 'comment-form', 'search-form', 'gallery', 'caption') );
  add_theme_support('custom-header');
  add_theme_support('automatic-feed-links');

  /*
   * Let WordPress manage the document title.
   * By adding theme support, we declare that this theme does not use a
   * hard-coded <title> tag in the document head, and expect WordPress to
   * provide it for us.
   */
  add_theme_support('title-tag');

  /**
   * Theme actions
   */

  // manage redirects
  // add_action('template_redirect', 'sandbox_template_redirect');

  // load scripts
  add_action('wp_enqueue_scripts', 'sandbox_enqueue_scripts');

  // init sidebars
  add_action('init', 'sandbox_sidebars_init');

  /**
   * Theme filters
   */

  // add shortcodes to widgets
  add_filter('widget_text', 'do_shortcode');
  add_filter('widget_title', 'do_shortcode');

  // add shortcodes to the excerpt
  add_filter('the_excerpt', 'shortcode_unautop');
  add_filter('the_excerpt', 'do_shortcode');

  // Adds filters for the description/meta content in archives.php
  add_filter('archive_meta', 'wptexturize');
  add_filter('archive_meta', 'convert_smilies');
  add_filter('archive_meta', 'convert_chars');
  add_filter('archive_meta', 'wpautop');

  // remove style attribute from cancel_comment_reply_link
  add_filter('cancel_comment_reply_link', 'sandbox_cancel_comment_reply_link', 10, 3);

  // filters the Categories archive widget to include the post count inside the link
  // https://www.sodawebmedia.com/blog/display-post-counts-within-link-for-categories-and-archive/
  add_filter('wp_list_categories', 'sandbox_count_span');

  // filters the Archive widget to include the post count inside the link
  add_filter('get_archives_link', 'sandbox_count_span');
}

/*
 * Setup hooks
 * ===========
 */
function sandbox_template_redirect(){
  // hide profile pages from not logged in users
  $profile_page_ID = array(5142, 5480);
  if ( !is_user_logged_in() && ( sandbox_is_page_or_descendant($profile_page_ID[0]) || sandbox_is_page_or_descendant($profile_page_ID[1]) ) ) {
    wp_redirect(home_url());
    die;
  }
}

// load scripts
function sandbox_enqueue_scripts(){
  $profile_post_ID = array(5142, 5480); // on profile page or descendants
  $post_id = get_the_ID();
  $post_type = get_post_type();
  $post_type_object = get_post_type_object($post_type);
  $post_type_rest_base = $post_type;

  if ( property_exists($post_type_object, 'rest_base') ) {
    $post_type_rest_base = $post_type_object->rest_base;
  }

	if ( !is_admin() ) {
    // jquery plugins
    wp_enqueue_script('jquery-plugins', get_template_directory_uri() . '/js/jquery.plugins.js', array('jquery'));
    // wp_enqueue_script('jquery-ui-css', get_template_directory_uri() . '/css/jquery-ui.theme.min.css');

  	// comments reply script
		if ( is_singular() && comments_open() && (get_option('thread_comments') == 1 ) ) {
			wp_enqueue_script('comment-reply');
		}

    // Javascript data for window.sandboxTheme_data
    $data = array(
      'id' => $post_id,
      'urls' => array(
        'ajax' => admin_url('admin-ajax.php'),
        'template' => get_stylesheet_directory_uri(),
        'rest' => rest_url('wp/v2/' . $post_type_rest_base . '/' . $post_id . '/'),
      ),
      'verify' => wp_create_nonce('sandbox_ajax_call'),
      'name' => sandbox_get_the_slug(),
      'categories' => get_the_category(),
      // 'terms' => get_the_terms(),
      'meta' => sandbox_get_post_meta(),
      'info' => array(
        'is_home' => is_home(),
        'is_front_page' => is_front_page(),
        'is_category' => is_category(),
        'is_archive' => is_archive(),
        'is_admin' => is_admin(),
        'is_single' => is_single(),
        'comments_open' => comments_open(),
        'is_page' => is_page(),
        'is_tag' => is_tag(),
        'is_tax' => is_tax(),
        'is_author' => is_author(),
        'is_search' => is_search(),
        'is_singular' => is_singular(),
        'is_user_logged_in' => is_user_logged_in(),
        'post_type' => $post_type,
      ),
    );

    // custom script: edit there for your own needs
	  wp_register_script('actions', get_template_directory_uri() . '/js/actions.js', false, '7', true);
    // Javascript data for window.sandboxTheme_data
    wp_localize_script('actions', 'sandboxTheme_data', $data );
	  wp_enqueue_script('actions');
    // custom script: edit there for your own needs
	}
	if ( is_user_logged_in() && ( is_page($profile_post_ID[0]) || is_page($profile_post_ID[1]) ) ) {
	  wp_enqueue_script('wp-util');
	  wp_enqueue_script('password-strength-meter');
	}
}


// init sidebars
function sandbox_sidebars_init() {

  if ( !function_exists('register_sidebar') ) {
    return;
  }

  // enter your sidebars here
	$sidebars = array('header', 'menu', 'highlight', 'content-before', 'content-after', 'content-footer', 'footer', 'footer-bar');

	foreach ( $sidebars as $sidebar ) {
	  $config = array(
			'name' => $sidebar,
			'id'   => $sidebar,
			'before_widget'  =>   '<div id="%1$s" class="widget %2$s"><div class="inner">',
			'after_widget'   =>   '</div></div>',
			'before_title'   =>   '<h3 class="title">',
			'after_title'    =>   '</h3>'
		);

    // Special markup for some sidebars
	  if ( $sidebar === 'menu') {
	    $config['before_widget'] = '<nav id="%1$s" class="widget %2$s">';
	    $config['after_widget']  = '</nav>';
	  }
	  else if ( $sidebar === 'footer') {
	    $config['before_widget'] = '<nav id="%1$s" class="widget clearfix %2$s">';
	    $config['after_widget']  = '</nav>';
	  }
	  else if ( $sidebar === 'header') {
	    $config['before_widget'] = '<div id="%1$s" class="widget %2$s">';
	    $config['after_widget']  = '</div>';
	  }
	  else if ( $sidebar === 'content-footer') {
	    $config['before_widget'] = '<div id="%1$s" class="widget %2$s site-container"><div class="inner">';
	    $config['after_widget']  = '</div></div>';
	  }
	  else if ( $sidebar === 'content-after') {
	    $config['before_widget'] = '<div id="%1$s" class="widget %2$s"><div class="inner clearfix">';
	    $config['after_widget']  = '</div></div>';
	  }

		register_sidebar($config);
	}
}

// filters to include the post count inside any link
function sandbox_count_span($output){
  $output = str_replace('</a> (', ' (', $output);
  $output = str_replace(')', ')</a>', $output);
  return $output;
}

/**
 * Template helper functions
 * =========================
 */
// is a given page ID the anchestor of the current page?
function sandbox_is_page_or_descendant($post_ID){
  $is_page_or_descendant = false;

  if ( is_page($post_ID) ) {
    $is_page_or_descendant = true;
  } elseif ( is_post_type_hierarchical(get_post_type()) ) {
    $post = get_post();
    $ancestors = get_post_ancestors($post->ID);

    if ( in_array($post_ID, $ancestors) ) {
      $is_page_or_descendant = true;
    }
  }
  return $is_page_or_descendant;
}

// Page slug
function sandbox_get_the_slug(){
  $slug = basename(get_permalink());
  do_action('before_slug', $slug);
  $slug = apply_filters('slug_filter', $slug);
  do_action('after_slug', $slug);
  return $slug;
}
function sandbox_the_slug(){
  echo sandbox_get_the_slug();
}

// Page description
function sandbox_get_page_description($sep, $num_words, $meta = true){
  if ( !is_string($sep) || empty($sep) ) { $sep = '-'; }
  if ( !is_numeric($num_words) || empty($num_words) ) { $num_words = 40; }

  $description = wp_title($sep, false);
  $sep = ' ' . $sep . ' ';
  if ( is_single() || is_page() || ( is_front_page() && !is_home() ) ) {
    $post = get_post(get_the_ID());
    if ( has_excerpt() ) {
      $description = $post->post_excerpt;
    } else  {
      $description = $post->post_content;
    }
  } else {
    if ( is_archive() || is_home() ) {
      if ( is_tax()  || is_tag()  || is_category() || is_author() ) {
        if ( is_tax()  || is_tag()  || is_category() ) {
          $termTitle = single_term_title('', false);
          $termDesc = term_description();
          $taxonomyTitle = get_taxonomy(get_queried_object()->taxonomy)->labels->singular_name;
        }
        if ( is_author() ) {
          $termTitle = get_the_author_meta('display_name');
          $termDesc = get_the_author_meta('description');
          $taxonomyTitle = __('Author', 'sandbox');
        }
        if ( !empty($termDesc) ) {
          $termDesc = $sep . $termDesc;
        }
        $description = $taxonomyTitle . ' ' . __('archive', 'sandbox') . $sep . $termTitle . $termDesc ;
      }
      if ( is_home() && ( $posts_page = get_option('page_for_posts') ) ) {
        $description = get_the_title($posts_page);
      } else{
        $description = get_option('blogname');
      }
      if ( is_search() ) {
        $description = __('Search Results For', 'sandbox') . ' ' . get_search_query();
      }
    }
    $description .= $sep . get_bloginfo('description');
  }
  return wp_trim_words(filter_var($meta, FILTER_VALIDATE_BOOLEAN) ? esc_html(wp_strip_all_tags($description, true)) : $description, $num_words);
}
function sandbox_the_page_description($sep = '-', $num_words = 40, $meta = true){
  echo sandbox_get_page_description($sep, $num_words, $meta);
}

// Page thumbnail
function sandbox_get_page_thumbnail(){
  $page_thumbnail = get_theme_mod('sandbox_logo');
  if ( is_single() && has_post_thumbnail() ) {
    $postThumbnail = wp_get_attachment_image_src(get_post_thumbnail_id(),'large', false);
    $page_thumbnail = $postThumbnail[0];
  } else if ( !empty($page_thumbnail) ) {
    $page_thumbnail = esc_url($page_thumbnail);
  } else {
    $page_thumbnail = esc_url(get_template_directory_uri()) . '/img/logo-basisbildung.png';
  }
  return $page_thumbnail;
}
function sandbox_the_page_thumbnail(){
  echo sandbox_get_page_thumbnail();
}

// Current page URI
function sandbox_get_current_URI(){
  $protocol = ( ( !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443 ) ? 'https://' : 'http://';
  return $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
function sandbox_the_current_URI(){
  echo sandbox_get_current_URI();
}

// Post meta single output for all fields
function sandbox_get_post_meta($post_id=0){
  $numeric_fields = array('_alpha_file_count', '_favorites', '_wpcr_rating', '_thumbnail_id');
  $serialized_fields = array('_more-link', '_alpha_file_options');
  $post_id = absint($post_id);
  if ( !$post_id ) {
    $post_id = get_the_ID();
  }
  $post_custom = get_post_custom($post_id);
  $post_meta_keys = get_post_custom_keys($post_id);
  $post_meta_keys_old = array_keys($post_custom);
  // echo var_dump($post_meta_keys_old);
  $post_meta = array();
  foreach ( $post_meta_keys as $post_meta_key ) {
    if ( !empty($post_custom[$post_meta_key][0]) ) {
      $post_meta[$post_meta_key] = $post_custom[$post_meta_key][0];
      // exeptions
      // numeric field type
      if ( in_array($post_meta_key, $numeric_fields) ) {
        $post_meta[$post_meta_key] = intval($post_custom[$post_meta_key][0]);
      }
      // serialized field type
      if ( in_array($post_meta_key, $serialized_fields) ) {
        $post_meta[$post_meta_key] = unserialize($post_custom[$post_meta_key][0]);
      }
    } else {
      $post_meta[$post_meta_key] = '';
      // exeptions
      // numeric field type
      if ( in_array($post_meta_key, $numeric_fields) ) {
        $post_meta[$post_meta_key] = 0;
      }
      // serialized field type
      if ( in_array($post_meta_key, $serialized_fields) ) {
        $post_meta[$post_meta_key] = array();
      }
    }
  }
  return $post_meta;
}

// Get the first tags title
function sandbox_get_the_tag_title(){
	$terms = get_the_terms(0, 'post_tag');

	if ( is_wp_error( $terms ) ){	return $terms; }
	if ( empty( $terms ) ){ return false;	}
	foreach ( $terms as $term ) {
  	$term_names[] = $term->name;
	}
	return $term_names[0];
}
function sandbox_the_tag_title(){
  echo sandbox_get_the_tag_title();
}

// Get the first tags slug
function sandbox_get_the_tag_slug(){
	$terms = get_the_terms(0, 'post_tag');

	if ( is_wp_error( $terms ) ){	return $terms; }
	if ( empty( $terms ) ){ return false;	}
	foreach ( $terms as $term ) {
    if ( $term->slug != 'kolumne') {
    	$term_slugs[] = $term->slug;
    }
	}
	return $term_slugs[0];
}
function sandbox_the_tag_slug(){
  echo sandbox_get_the_tag_slug();
}

// Get the first tags ID
function sandbox_get_the_tag_id(){
	$terms = get_the_terms(0, 'post_tag');

	if ( is_wp_error($terms) ){	return $terms; }
	if ( empty($terms) ){ return false;	}
	foreach ( $terms as $term ) {
  	$term_ids[] = $term->term_id;
	}
	return $term_ids[0];
}

function sandbox_the_tag_id(){
  echo sandbox_get_the_tag_id();
}

// Output from +431234567891 to +43 1 234 56 78 - 91
function sandbox_sanitize_phone($phone) {
  $data = array(
    substr($phone, 0,3),
    substr($phone, 3,1),
    substr($phone, 4,3),
    substr($phone, 7,2),
    substr($phone, 9,2),
    substr($phone, 11,2),
  );
  if ( !empty($data[5]) ) {
    $data[5] = ' - ' . $data[5];
  }
  return $data[0] . ' ' . $data[1] . ' ' . $data[2] . ' ' . $data[3] . ' ' . $data[4] . $data[5];
}

// Comment cancel reply link
function sandbox_cancel_comment_reply_link($formatted_link, $link, $text){
  return '<a rel="nofollow" id="cancel-comment-reply-link" href="' . $link . '">' . $text . '</a>';
}

// Comment Item, callback for wp_list_comments()
function sandbox_comment_item($comment, $args, $depth){
  if ( !isset($GLOBALS['comment']) ) {
    $GLOBALS['comment'] = $comment;
  }
  ?>
  <li id="comment-<?php comment_ID(); ?>" <?php comment_class( $comment->has_children ? 'parent' : '', $comment ); ?>>
    <div class="inner">
      <aside class="comment-meta">
        <ul class="inner">
        <?php if ( 0 != $args['avatar_size'] ) { ?>
          <li class="avatar">
            <?php echo get_avatar( $comment, $args['avatar_size'] ); ?>
          </li>
        <?php } ?>
          <li class="name">
            <?php echo get_comment_author_link( $comment ); ?>
          </li>
          <li class="date"><a href="<?php
              echo esc_url( get_comment_link( $comment, $args ) );
            ?>"><time datetime="<?php comment_time('c'); ?>"><?php
              /* translators: 1: comment date, 2: comment time */
              printf( __('%1$s at %2$s'), get_comment_date('', $comment ), get_comment_time() );
            ?></time></a></li>
        <?php if ( current_user_can('moderate_comments') ) { ?>
          <li class="edit"><?php edit_comment_link( __('Edit'), '<span class="edit-link">', '</span>'); ?></li>
        <?php } ?>
          <li class="reply"><?php
            comment_reply_link( array_merge( $args, array(
              'add_below' => 'div-comment',
              'depth'     => $depth,
              'max_depth' => $args['max_depth'],
              'before'    => '',
              'after'     => ''
            ) ) );
          ?></li>
        </ul>
      </aside>
      <div class="content">
        <div class="inner">
        <?php if ('0' == $comment->comment_approved ) : ?>
          <p class="comment-awaiting-moderation"><?php _e('Your comment is awaiting moderation.'); ?></p>
        <?php endif; ?>
        <?php echo apply_filters('comment_text', $comment->comment_content, $comment, $args); ?>
        </div>
      </div>
    </div>
  <?php
}
function sandbox_user_comments_item($comment, $args, $depth){
  if ( !isset($GLOBALS['comment']) ) {
    $GLOBALS['comment'] = $comment;
  }
  ?>
  <li id="comment-<?php comment_ID(); ?>" <?php comment_class( $comment->has_children ? 'parent' : '', $comment ); ?>>
    <div class="inner">
      <aside class="comment-meta">
        <ul class="inner">
        <?php if ( 0 != $args['avatar_size'] ) { ?>
          <li class="avatar">
            <?php echo get_avatar( $comment, $args['avatar_size'] ); ?>
          </li>
        <?php } ?>
          <li class="name">
            <?php echo get_comment_author_link( $comment ); ?>
          </li>
          <li class="date"><a href="<?php
              echo esc_url( get_comment_link( $comment, $args ) );
            ?>"><time datetime="<?php comment_time('c'); ?>"><?php
              /* translators: 1: comment date, 2: comment time */
              printf( __('%1$s at %2$s'), get_comment_date('', $comment ), get_comment_time() );
            ?></time></a></li>
        <?php if ( current_user_can('moderate_comments') ) { ?>
          <li class="edit"><?php edit_comment_link( __('Edit'), '<span class="edit-link">', '</span>'); ?></li>
        <?php } ?>
          <li class="reply"><?php
            comment_reply_link( array_merge( $args, array(
              'add_below' => 'div-comment',
              'depth'     => $depth,
              'max_depth' => $args['max_depth'],
              'before'    => '',
              'after'     => ''
            ) ) );
          ?></li>
        </ul>
      </aside>
      <div class="content">
        <div class="inner">
        <?php if ('0' == $comment->comment_approved ) : ?>
          <p class="comment-awaiting-moderation"><?php _e('Your comment is awaiting moderation.'); ?></p>
        <?php endif; ?>
        <?php echo apply_filters('comment_text', $comment->comment_content, $comment, $args); ?>
        </div>
      </div>
    </div>
  <?php
}

// Comments Link
function sandbox_get_the_comments_link(){ // use this function only inside the loop.
  $comments_count = get_comments_number();
  $commentsListId = 'comments-list';
  $commentsFormId = 'response';

	if ( $comments_count == 0 ) {
	  $commentLink = '<a href="#' . $commentsFormId . '">' . $comments_count . ' ' . __('Be the first to Comment', 'sandbox') . '</a>'; // 'Schreib den ersten Kommentar';
	}  else if ( $comments_count > 1 ) {
	  $commentLink = '<a href="#' . $commentsListId . '">' . $comments_count . ' ' . __('Comments', 'sandbox') . '</a>'; // 'Kommentare';
	} else {
		$commentLink = '<a href="#' . $commentsListId . '">' . $comments_count . ' ' . __('Comment', 'sandbox') . '</a>'; // 'Kommentar';
	}
	return $commentLink;
}
function sandbox_the_comments_link(){ // use this function only inside the loop.
  echo sandbox_get_the_comments_link();
}

// measure the approximately read-time of an article
function sandbox_read_time($text){
	$words = str_word_count(wp_strip_all_tags($text));
	if ( !empty($words) ) {
		$time_in_minutes = ceil($words/200);
		return $time_in_minutes;
	}
	return false;
}
// Collect term data for any kind of archive
function sandbox_get_archive_term(){
  $queried_object = get_queried_object();
  $term = new stdClass();
  $term->classes = '';
  $term->description = get_the_archive_description();
  $term->taxonomy = array('title' => '', 'WP_Taxonomy' => '');
  $term->post_type = array('title' => '', 'WP_Post_Type' => '');
  $term->post_types = array();
  $paged = get_query_var('paged');
  $max_num_pages = get_query_var('max_num_pages');

  // echo var_dump($max_num_pages);
  if ( is_post_type_archive() ) {
    if ( empty($term->description) ) {
      $term->description = $queried_object->description;
    }
    // custom long description
    $long_description = '';
    if ( function_exists('ptad_get_post_type_description') ) {
      $long_description = ptad_get_post_type_description($queried_object->name);
    }
    if ( !empty($long_description) ) {
      $term->description = $long_description;
    }
    $term->title = $queried_object->label;
    $term->thumbnail = esc_url(get_template_directory_uri()) . '/img/' . $queried_object->name . '.jpg';
    // $term->thumbnail = '';
    // $term->byline = __('All articles in', 'sandbox') . ' ' . $term->title;
    $term->count = wp_count_posts($queried_object->name)->publish; //$queried_object->count;
    $term->byline = $queried_object->labels->name;
    $term->post_type['WP_Post_Type'] = $queried_object;
    $term->post_types[] = $queried_object->name;
  }
  if ( is_tax()  || is_tag()  || is_category() ) {
    $queried_taxonomy = get_taxonomy($queried_object->taxonomy);
    $term->term_id = $queried_object->term_id;
    $term_meta = get_term_meta($term->term_id);
    $term->title = single_term_title('', false);
    $term->thumbnail = '';
    $term->thumbnail_id = isset($term_meta['_term_image']) && !empty($term_meta['_term_image'][0]) ? intval($term_meta['_term_image'][0]) : 0;
    if ( $term->thumbnail_id !== 0 ) {
      $term->thumbnail = wp_get_attachment_image($term->thumbnail_id, 'sandbox-hero');
    }
    $term->taxonomy['title'] = $queried_taxonomy->labels->singular_name;
    $term->taxonomy['WP_Taxonomy'] = $queried_taxonomy;
    $term->byline = $term->taxonomy['title'] . ' - ' . $term->title;
    $term->count = $queried_object->count;
    if ( !empty($queried_taxonomy->object_type) ) {
      $post_type_names = $queried_taxonomy->object_type;
      $term->post_type = array();
      foreach ( $post_type_names as $post_type_name ) {
        $post_type_object = get_post_type_object($post_type_name);
        $term->post_type[] = array(
          'title' => $post_type_object->label,
          'WP_Post_Type' => $post_type_object,
        );
      }
      $term->post_types = $post_type_names;
    }
  }
  if ( is_author() ) {
    $term->title = get_the_author_meta('display_name');
		$term->thumbnail = get_avatar($queried_object->data->ID, 'smr-thumb');
    $term->taxonomy['title'] = __('Author', 'sandbox');
    $term->byline = $term->title;
    $term->count = count_user_posts($queried_object->data->ID);
  }
	if ( is_date() ) {
    global $wp_query;
    $term->title = __('All articles from', 'sandbox') . ' ';
    $term->count = $wp_query->found_posts;

    if ( is_day() ) {
      $term->title .= get_the_time(get_option('date_format'));
    } elseif ( is_month() ) {
      $term->title .= get_the_time('F Y');
    } elseif ( is_year() ) {
      $term->title .= get_the_time('Y');
    }
	}
	if ( is_home() ) {
    global $wp_query;
    $posts_page_id = get_option('page_for_posts');
	  $term->post_type['WP_Post_Type'] = get_post_type_object('post');
	  $term->post_type['title'] =
    $term->description = get_the_content($posts_page);
    $term->title = get_the_title($posts_page);
    $term->byline = $term->title;
    $term->count = $wp_query->found_posts;
	}
  // Add a page number if necessary.
  $posts_per_page = get_query_var('posts_per_page');
  $all_pages = ceil($term->count/$posts_per_page);
    // echo 'blah: ' . var_dump($term->count);
    // echo 'blah: ' . var_dump($all_pages);
  if ( $paged > 1 && !is_404() ) {
    /* translators: %s: Page number. */
    $current_page = sprintf(__('Page %s'), $paged);
    $of = ' ' . __('von', 'sandbox') . ' ';
    $term->byline .= ' ' . $current_page . $of . $all_pages;
  } else if ( $term->count > $posts_per_page ) {
    $all_pages = ceil($term->count/$posts_per_page);
    $of = ' ' . __('von', 'sandbox') . ' ';
    $term->byline .= ' ' . __('Seite 1') . $of . $all_pages;
  }
	if ( !empty($term->taxonomy['title']) ) {
	  $term->taxonomy['title'] .= ' - ';
	}

  $term->has_description = false;
	if ( !empty($term->description) ) {
	  $term->classes .= ' has-description';
	  $term->description = wpautop($term->description);
	  $term->has_description = true;
	}
  $term->has_thumbnail = false;
	if ( !empty($term->thumbnail) ) {
	  $term->classes .= ' has-thumbnail';
	  $term->has_thumbnail = true;
	}
  $term->has_meta = false;
	if ( $term->has_description || $term->has_thumbnail || is_a($term->taxonomy['WP_Taxonomy'], 'WP_Taxonomy') ) {
	  $term->classes .= ' has-meta';
	  $term->has_meta = true;
	}
  $term->has_byline = false;
	if ( !empty($term->byline) ) {
	  // only when meta is present
	  if ( $term->has_meta ) {
	    $term->classes .= ' has-byline';
	  }
	  $term->has_byline = true;
	}
	if ( !empty($term->classes) ) {
	  $term->classes = ' ' . $term->classes;
	}
  // echo '<!-- ', var_dump($wp_query->query_vars),  ' -->';
  return $term;
}

// Count amount of pages in an archive
function sandbox_count_archive_pages($term = NULL){
  if ( !is_archive() ) { return NULL; }
  if ( $term === NULL ) { $term = sandbox_get_archive_term(); }

  $posts_per_page = get_option('posts_per_page');
  return ceil($term->count/$posts_per_page);
}

// Detect if an archive page is paged
function sandbox_archive_is_paged($term = NULL){
  if ( !is_archive() ) { return NULL; }
  if ( $term === NULL ) { $term = sandbox_get_archive_term(); }

  return sandbox_count_archive_pages($term) > 1;
}
function sandbox_get_more_url($post_type, $post_meta){
  $more_url = get_permalink();
  if ( ( isset($post_meta["_more-link-url"]) && !empty($post_meta["_more-link-url"]) ) || ( isset($post_meta['_more-link']) && !empty($post_meta['_more-link']) ) ) {
    // "download_aktion_de" uses that field for download button
    if ( $post_type !== 'download_aktion_de' ) {
      if ( !empty($post_meta["_more-link-url"]) ) {
        $more_url = $post_meta["_more-link-url"];
      } elseif ( isset($post_meta['_more-link'][0]) && isset($post_meta['_more-link'][0]['_more-link-url']) && !empty($post_meta['_more-link'][0]['_more-link-url']) ) {
        $more_url = $post_meta['_more-link'][0]['_more-link-url'];
      }
    }
  }
  return $more_url;
}
function sandbox_get_more_text($post_type, $post_meta){
  // Text for "Read more" button
  $more_texts = array(
    'default' => __('Read more', 'sandbox'),
    'download' => __('Download', 'sandbox'),
    'alpha_download' => array(
      'default' => __('More details', 'sandbox'),
    ),
    'download_aktion_de' => array(
      'default' => __('More details', 'sandbox'),
    ),
  );
  $more_text = $more_texts['default'];

  // post type handling
  if ( isset($more_texts[$post_type]) && isset($more_texts[$post_type]['default']) && !empty($more_texts[$post_type]['default']) ) {
    $more_text = $more_texts[$post_type]['default'];
  }

  // custom fields handling
  if ( ( isset($post_meta["_custom_more_text"]) && !empty($post_meta["_custom_more_text"]) ) || ( isset($post_meta['_more-link']) && !empty($post_meta['_more-link']) ) ) {
    if ( isset($post_meta["_custom_more_text"]) && !empty($post_meta["_custom_more_text"]) ) {
      $more_text = $post_meta["_custom_more_text"];
    } elseif ( isset($post_meta['_more-link'][0]) && isset($post_meta['_more-link'][0]['_more-link-text']) && !empty($post_meta['_more-link'][0]['_more-link-text']) ) {
      $more_text = $post_meta['_more-link'][0]['_more-link-text'];
    }
  }
  return $more_text;
}
// Get all taxonomies for a post and its terms
// works like get_the_terms() but returns an array of all taxonomies that are registered to the post.
function sandbox_get_the_taxonomies_and_terms($post_id=0){
  $post_id = absint($post_id);
  if ( !$post_id ) {
    $post_id = get_the_ID();
  }
  $post = get_post($post_id);
  $taxonomy_objects = get_object_taxonomies($post, 'objects');
  $taxonomies = array();
  $taxonomies_index = 0;

  foreach ( $taxonomy_objects as $taxonomy_object ) {
    $taxonomy_term_objects = get_the_terms($post_id, $taxonomy_object->name);
    if ( !empty($taxonomy_term_objects) && !is_wp_error($taxonomy_term_objects) ) {
      $taxonomies[$taxonomy_object->name] = array(
        'slug' =>$taxonomy_object->name,
        'label' =>$taxonomy_object->label,
        'terms' => array(),
      );
      foreach ( $taxonomy_term_objects as $taxonomy_term_object ) {
        $taxonomies[$taxonomy_object->name]['terms'][$taxonomy_term_object->slug] = array(
          'term_id' => $taxonomy_term_object->term_id,
          'slug' => $taxonomy_term_object->slug,
          'label' => $taxonomy_term_object->name,
          'description' => $taxonomy_term_object->description,
        );
      }
      $taxonomies_index++;
    }
  }
  return $taxonomies;
}
function sandbox_get_the_terms(){
  $post_id = get_the_ID();
  $taxonomies = get_post_taxonomies($post_id);
  $terms = array();

  foreach ( $taxonomies as $taxonomy ) {
    $terms_data = wp_get_post_terms($post_id, $taxonomy);

    if ( !empty($terms_data) && !is_wp_error($terms_data) ) {
      $terms[$taxonomy] = $terms_data;
    }
  }
  return $terms;
}

// get meta data of an article
function sandbox_get_meta_data( $force_meta = false ) {
	if ( !$force_meta ) { return; }

	$output = '';

	//Check for sticky
	if ( is_sticky() ) {
		$output .= '<div class="meta-stick">' . __('Sticky', 'sandbox') . '</div>';
	}

	//Check meta options
  $metas = is_array($force_meta) ? $force_meta : array( $force_meta );
  // echo '<!-- ', var_dump($metas), ' -->';

	if ( !empty( $metas ) ) {
		$post_id = get_the_ID();
    $post_type = get_post_type($post_id);
    $post_meta = get_post_custom();

		foreach ( $metas as $meta_id ) {
      $meta = '';
      $className = $meta_id;

		  switch ( $meta_id ) {

			  case 'format':
			    $formats = get_the_terms($post_id, 'format');
			    if ( !empty($formats) && ! is_wp_error($formats) ) {
	          foreach ( $formats as $format ) {
	            $className .= ' meta-' . $format->slug;
              $meta = $format->name;
            }
			    }
			    break;

			  case 'date':
				  $meta = get_the_date();
				  break;

			  case 'terms':
			    $terms_in_taxes = sandbox_get_the_terms();
				  $meta = '';

			    if ( !empty($terms_in_taxes) ) {
			      foreach ( $terms_in_taxes as $taxonomy_name => $terms ) {
			        if ( !empty($terms) ) {
      				  $meta .= '<ul class="terms-list ' . $taxonomy_name . '-list">';
    				    foreach ( $terms as $term ) {
    			        if ( !empty($term) && is_a($term, 'WP_Term') ) {
    				        $meta .= '<li class="' . $term->slug . '"><a href="' . esc_url(get_term_link($term)) . '">' . $term->name . '</a></li>';
    				      }
    				    }
    				    $meta .= '</ul>';
  				    }
			      }
			    }
				  break;

			  case 'author':
			    if ( $post_type === 'alpha_download' ) {
            $author = isset($post_meta['_download-author']) ? $post_meta['_download-author'][0] : '';
            $license = isset($post_meta['_download-license']) ? $post_meta['_download-license'][0] : '';
            if ( !empty($author) ) {
  			      $meta = $author . ( !empty($license) ? ' | ' . $license : '' );
            }
			    } else {
				    $author_id = get_post_field('post_author', $post_id);
				    $meta = get_the_author_meta('display_name', $author_id);
			    }
				  break;

			  case 'rtime':
				  $meta = sandbox_read_time(get_the_content());
				  if ( !empty( $meta ) ) {
					  $meta = $meta . ' ' . __('min read', 'sandbox');
				  }
				  break;

			  case 'comments':
				  if ( comments_open() || get_comments_number() ) {
					  ob_start();
					  comments_popup_link( __('Add Comment', 'sandbox'), __('1 Comment', 'sandbox'), __('% Comments', 'sandbox') );
					  $meta = ob_get_contents();
					  ob_end_clean();
				  } else {
					  $meta = '';
				  }
				  break;

			  default:
				  break;
			}
			if ( !empty($meta) ) {
				$output .= "\r\n" . '<li class="' . $className . '">' . $meta . '</li>';
			}
		}
	}
	return $output;
}



// Remember: the sandbox is for play.
?>
