<?php

error_log(__FILE__);

// Prohibit direct script loading.
defined( 'ABSPATH' ) || die( 'No direct script access allowed!' );

// startup actions for wordpress
// plugins loaded / init / wp_loaded / parse_request

// some constants
define ('DBRK', '<brk><brk>');
define ('SC_PRE', "\r<!-- wp:shortcode -->\r");
define ('SC_PST', "\r<!-- /wp:shortcode -->\r");
define ('HM_PLUGIN_DIR', ABSPATH . 'wp-content/plugins/hm-tcr/');
define ('HM_PLUGIN_RESOURCE_PATH', HM_PLUGIN_DIR . 'resources/');
// choices
define('AUTOSAVE_INTERVAL', 600 ); // seconds
define('WP_POST_REVISIONS', 2);
define('DISABLE_WP_CRON', false);
// only edit via shell access
// already done in config by ithemes
//define( 'DISALLOW_FILE_EDIT', true );
// remove date from uploads dir
add_filter( 'option_uploads_use_yearmonth_folders', '__return_false', 1 );

date_default_timezone_set('America/Los_Angeles');

// admin and editor go direct to admin, everyone else home page
add_filter( 'login_redirect', function ($redirect_to, $requested_redirect_to, $user) {
	$allowed_roles = array('administrator');
	$user = wp_get_current_user();
 	if( array_intersect($allowed_roles, $user->roles ) )
        return home_url() . '/wp-admin/edit.php';
        else return  home_url();
}, 0, 3);
// fiddles with when this is done, but this works now . assumes usp will only add image files
    add_action('wp_loaded','hm_do_first',9);
    // force everyone to home page after logout
add_action('wp_logout', function () {hm_redirect();});

// do this early
//add_action('init','hm_preprocess_files',8);
function hm_preprocess_files() {
    //add_action('parse_request', 'usp_checkForPublicSubmission', 1);
    remove_action('parse_request', 'usp_checkForPublicSubmission', 1);
    
    global $hm_vars;
    $hm_vars['pdfs'] = hm_file_filter('application/pdf');  
    add_action('parse_request', 'usp_checkForPublicSubmission', 1);
    
}

$x_more = 0;        
function hm_do_first() {
    global $hm_vars;
    // remove extraneous headerinfo
    remove_action('wp_head', 'wp_generator');
    remove_action( 'wp_head', 'wp_shortlink_wp_head');
    remove_action( 'wp_head', 'wlwmanifest_link');
    remove_action ('wp_head', 'rsd_link');
    // work around needed for homebrew security
    ob_start('hm_ob_all');
    hm_set_admin_bar();
    // get out early
    if (
        ($hm_vars['script'] == '/wp-admin/admin-ajax.php') ||
        ($hm_vars['script'] == '/wp-cron.php') ||
        ($hm_vars['script'] == '/wp-login.php') ||
        (($hm_vars['script'] == '/index.php') && (strpos($hm_vars['uri'],'ithemes-security') > 0))
        ) {
            remove_action('wp_loaded','hm_wp_loaded',10 );
            return;    
    }
    define( 'HM_UPLOAD_URL', wp_get_upload_dir()['url']);
    define( 'HM_UPLOAD_PATH', wp_get_upload_dir()['path'] . '/');
       
    // $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
    // user always gets directed back to home page
    add_filter ('wp_die_handler', function($_default_wp_die_handler) {return 'hm_die';});

 
    $hm_vars['logging'] = hm_get_const_value('HM_LOG', false);
    if ($hm_vars['logging']) {
        $log_path = wp_upload_dir()['path'] . '/logs/'  . date('y-m-d') . '.log';
        $hm_vars['log_path'] = $log_path;
        hm_log($hm_vars, '$hm_vars', false, 300, '0000', 2000);
     }
    // kluge related to focus in first text field - better way tbd
    if (isset($_POST['user_submitted_title'])) {
        $_POST['user-submitted-title'] = $_POST['user_submitted_title'];
    }
    // redirect 'uri' like '?p=' or '&p='
    add_action('plugins_loaded', function() {if (isset($_REQUEST['p'])) hm_die('p_request 070');});
    // for profiling
    add_action('shutdown', 'hm_shutdown',99); 
    // block 'p='
    add_filter('query_vars', function($query_vars) { unset($query_vars['p']); return $query_vars; }, 0);
    add_filter('post_type_link', function($post_link) {  return $post_link; }, 0);
    // apply_filters( 'post_type_link', string $post_link, WP_Post $post, bool $leavename, bool $sample )
   
}


function hm_shutdown() {
    global $hm_vars;
    // for profiling elapsed time in milliseconds
    $elapsed = (hrtime(true) - $hm_vars['started']) / 1000000;
    $elapsed = round($elapsed, 0);
    $var = $elapsed . ' ... ' . $hm_vars['uri'];
    hm_log($var , 'elapsed ... uri:', false, -1, 'profile');
    if (get_current_user_id() > 0) {
        hm_log($var , 'elapsed ... uri:', false, -1, 'profile_us');      
    }
 }

 add_action('wp_loaded','hm_wp_loaded',10 );
 add_action( 'wp_enqueue_scripts', 'hm_enqueue_scripts' );
	
function hm_wp_loaded(){
    global $hm_vars;
    global $hm_suspended_users;
    //hm_logx('ww',$_COOKIE['window_width']);
	remove_filter ('the_author', 'usp_replaceAuthor');
    

    //if (wp_doing_ajax()) return;
    $request = $hm_vars['uri'];
    //if ('/wp-login.php' == $hm_vars['script']) return;
    
   // if (strpos($request, 'ithemes-security') > 0) return;
   // wp_set_current_user(1);
    if(is_admin()  && hm_check_role('editor,administrator')) return;
    
    // set-up manipulating output if needed
    // put output buffers in place for certain requests
    $buffering = _hm_output_buffering($request, hm_get_const_value('HM_OUTPUT_BUFFERING', 'add-page,upload,search,submit-,announcements,table,pdf,&s=,no_menu,dl='));
    // housekeeping if 'usp form' plugin will be used
    _hm_usp_helper($request);
    
    // deep link - will not return if it is
    hm_check_link_request($_REQUEST);
    
    // if searching then setup search globals early
    if (!empty($_REQUEST['s'])) {
        // try to block ad-hoc searching
        if (empty($_REQUEST['hm-limit']))  hm_redirect();
        hm_search_words();
    }
    
    if (($hm_vars['script'] == '/index.php') && ($hm_vars['uri'] == '/')) return;
    if (!hm_is_permalink($hm_vars['uri'])) return;
    // at this point, all remains is permalinks
    // not logged in
    if ($hm_vars['user']->ID == 0) {
	// basic security - disable json for non logged in users
	add_filter('rest_enabled', '_return_false');
	add_filter('rest_jsonp_enabled', '_return_false');

        // no searching
        if (isset($_REQUEST['s'])) hm_redirect();
        if (!hm_is_allowed_page($request, 'world')) hm_redirect();
        return;
    }
    
    // if a resident
    if (hm_check_role('contributor,subscriber')) {
        $post_id = url_to_postid($request);
        $type = get_post_field('post_type', $post_id);
        if ($type == 'page') {	
            if (!hm_is_allowed_page($request, 'resident')) hm_redirect();
            return;
        }
        // must be a post
        if (!hm_is_allowed_post($post_id, 'resident')) hm_redirect();
        return;
     }
     // remaining roles get access
     return;
 }
 // parse uri to see if we have a permalink
 function hm_is_permalink($uri){
     $p = '/^\/([a-z0-9\-]+)\/$/';
     $m = array();
     preg_match($p, $uri, $m);
     return !empty($m[1]);     
 }
 
 function hm_is_allowed_post($post_id, $who = 'resident') {
     
     $cats = get_the_category($post_id);
     if (count($cats) != 1) hm_die("logic error 090 - no or multiple cats for $post_id", true);
     $cat_parents = get_category_parents($cats[0], ',', true);
     $restricted_slugs = hm_get_const_value('HM_CAT_RESTRICTED','3-posts-to-records,4-posts-to-committees');
     foreach (explode(',', $restricted_slugs) as $restricted_slug) {
         if (strpos($cat_parents, $restricted_slug)) return false;
     }
     return true;     
 }



// returns whether the request  matches a set of permalinks
function hm_is_allowed_page($request, $who) {
    global $wpdb, $table_prefix;
    // correspondence between 'role' and menu items available
  //  $roles2metavalue = array('world=>'', 'contributor'=>)
    switch ($who) {
        case 'world' :
            $meta_value = "(meta_value = '')";
            break;
        case 'resident' :
            $meta_value = "(meta_value  = 'in')";;
            break;
        case 'owner' :
            $meta_value = "((meta_value like '%author%') or meta_value = 'in'";;
            break;
        default :
            hm_die('logic error 040', true);            
    }
    
    $query="select p.post_name from tbl_prefixpostmeta  m, tbl_prefixposts p where m.meta_value = p.ID and p.post_type = 'page' and p.post_status = 'publish' and m.meta_key = '_menu_item_object_id' and m.post_id in (select post_id from tbl_prefixpostmeta where (meta_key = '_nav_menu_role') and $meta_value)";
    $query = str_replace('tbl_prefix', $table_prefix, $query);
    
    $allowed_pages = $wpdb->get_col(stripslashes($query));
    foreach ($allowed_pages as $page) {
        if (strpos($request, $page) != false) return true;
    }    
    return false;    
}

function _hm_output_buffering($request, $request_stems) {
    global $hm_vars;
    // for intercepting html output to introduce 'extra' functionality
    $buffer_stems = explode(',', $request_stems);
    foreach ($buffer_stems as $stem) {
        if (strpos($request, $stem) > 0) {
            // edge case
            if(strpos($request, 'help') && (!strpos($request, 'no_menu')))
                continue;
                
                $hm_vars['output_buffering'] = $stem;
                // delay  all output to browser until end of processing request
                // but first close out existing buffers
                ob_end_clean();
                ob_start('hm_ob');
                return true;
        }
    }
    $hm_vars['output_buffering'] = 'all';
}

//might be obsolete
// if we have uploaded a non-image file
// turn off usp submission image processing
function hm_adjust_usp(){
    global $hm_vars;
    
    // if no uploads then nop
    if (0 == count($_FILES)) {
        return;
    }
    
    // if we are using the form for images then nop
    if (isset($_FILES['user-submitted-image'])) {
        return;
    }
    
    // set up for processing a non-image file
    $hm_vars['usp-non-image'] = $_FILES;
    
    // turn off file upload processing for usp
    if (isset($GLOBALS['usp_options']['usp_images'] )) {
        $GLOBALS['usp_options']['usp_images'] = 'hide';
    }
    
}
/*
 * enqueue javascripts as needed
 */
function hm_enqueue_scripts() {
    global $hm_vars;
    $uri = $hm_vars['uri'];
  
    if (isset($_REQUEST['hm-hilite']))  {
        wp_register_script('hm_jump_to_span', plugins_url('../js/hm-span-jump.js', __FILE__), null,'1.0', false);
        wp_enqueue_script('hm_jump_to_span');
    }
    elseif(strpos($uri, 'search-this-website') > 0) {
        wp_register_script('hm_search_init_cursor', HM_PLUGIN_DIR . 'js/hm_search_init_cursor.js', null,'1.0', false);
        wp_enqueue_script('hm_search_init_cursor');
        
    }
    elseif(strpos($uri, 'submit') > 0) {
        wp_register_script('hm_submit_init_cursor', HM_PLUGIN_DIR . 'js/hm_submit_init_cursor.js', null,'1.0', false);
        wp_enqueue_script('hm_submit_init_cursor');
    }
    wp_register_script('hm_window_width', home_url() .'/wp-content/plugins/hm-tcr/js/hm_window_width.js', null,'1.0', false);
    wp_enqueue_script('hm_window_width');
    // don't want ajax heartbeat - unless I find out otherwise
    wp_deregister_script('heartbeat');

    
}

// bypass header contraints
function hm_ob_all($buffer){
    $buffer = str_ireplace('or Email Address', '', $buffer);
    return $buffer;    
}

function hm_ob($buffer){
    global $hm_vars;
   // hm_log (substr($buffer,0,20),'wp_ob_end_flush_all');
    if ($buffer == '') return $buffer;
    //return $buffer;
    
   // if ( $hm_vars['logging'] )  $buffer_in = str_split($buffer,1024);
    hm_log ('wp_ob_end_flush_all');
    
    switch ($hm_vars['output_buffering']) {
        case 'add-page' :
            $buffer =  _hm_add_page($buffer);
            break;
            
        case 'no_menu' :
            $buffer =  _hm_ob_no_menu($buffer);
            break;
        case 'table' :
            $buffer = _hm_ob_table($buffer);
            break;
        case 'upload' :
            break;
        case 'submit-' :
            $buffer =  _hm_usp_buffer($buffer, 'hm-post', '', 'posts.', 'Topic', 'Post');
            break;
        case 'announcements' :
            $buffer = _hm_usp_buffer($buffer, 'hm-announce', 'make-an-announcement', 'announcements.', 'Announcement','Announcement');
            break;
        case 'search' :
            $buffer =  _hm_ob_search($buffer);
            break;
         case '&s=' :
            $buffer =  _hm_ob_hilite($buffer);
            break;
        case 'post' :
            $buffer =  _hm_ob_table($buffer);
            break;
        case 'pdf' :
            $buffer =  _hm_ob_pdf($buffer);
            break;
            
        default: 
            //$buffer = str_replace('/hm28', '', $buffer);
            
    }
	// strays
	$host = parse_url(home_url(), PHP_URL_HOST);
	$buffer = str_replace('localhost', $host, $buffer);
    
    //if( $hm_vars['logging']) $buffer_out = str_split($buffer,1024);
    return $buffer;
    
}

// common to one variety of various usp forms
function _hm_usp_buffer($buffer, $form_id, $category, $category_replace,  $post_replace, $submit_replace) {
    
    $search = array();
    $replace = array();
    
    $user_id = get_current_user_id();
    $args = array('author'=>$user_id, 'post_status'=>'publish', 'post_type'=>'post');
    if ($category > '') {
        $cat_id = get_category_by_slug($category)->term_id;
        $args['cat'] = $cat_id;
    }

    $recent_posts = get_posts($args);
    hm_log($args, '$args', false, -1, 'buffer');
    
    $search[] = '!!!hm_post_list!!!';
    $list = '<br>';
    $list = '';
    $recent_post_ids = array();
    flush_rewrite_rules();
    if (isset($recent_posts) && is_array($recent_posts) && (count($recent_posts) > 0)) {
        $i = 1;
        foreach($recent_posts as $pst) {
            $list .= "$i) $pst->post_title <br>";
            $recent_post_ids[] = $pst->ID;
            $i++;
        }
    }
    else {
        $list .= DBRK . 'You have no recent ' . $category_replace ;
    }
            
            
    $replace[] = $list;
            
    $search[] = ' class="usp-';
    $replace[] = ' class="hm-usp usp-';
    
    $search[] = ' class="usp-';
    $replace[] = ' class="hm-usp usp-';
    
    $search[] = '<body class';
    $replace[] = '<body OnLoad="document.usp_form.user_submitted_title.focus();" class';
    $search[] = 'id="usp_form"';
    $replace[] = 'id="usp_form" name="usp_form"';
    // kluge related to focus in first text field - better way tbd
    $search[] = 'name="user-submitted-title"';
    $replace[] = 'name="user_submitted_title"';
    
    $search[] = 'image[]"';
    $replace[] = 'image[]" multiple ';

        
    // stash prior post id's in hidden field
    // so we can delete one if requested
        $marker = '<div id="usp-submit">';
        $hidden_html = sprintf('<input type="hidden" id="hm-recent-post-ids" name="hm-recent-post-ids" value="%s" />', 	implode(',',$recent_post_ids));
        $hidden_html .= DBRK . sprintf('<input type="hidden" id="hm-form-id" name="hm-form-id" value="%s" />', $form_id);
        
        if ($form_id == 'hm-announce') {
            // add checkbox for limiting distribution post comments
            $marker2 = '<fieldset class="hm-usp usp-content">';
            
            $radio_btn =
            '<fieldset class="hm-uspx usp-content">
             <label>Send this announcement to the following mailing list<BRK></label>';
            if (hm_check_role('author,editor,administrator')){
                $radio_btn .= '<label>&nbsp&nbsp&nbsp&nbsp<input type="radio"  name="hm-mailing-list" value="tcr-owners"  checked>&nbspTCR Owners &nbsp&nbsp';
            }
            $radio_btn .= '<input type="radio"  name="hm-mailing-list" value="tcr-residents" checked>&nbsp TCR Residents&nbsp&nbsp';
            $radio_btn .=  '&nbsp&nbsp&nbsp&nbsp<input type="radio"  name="hm-mailing-list" value="tcr-everyone"> TCR Everyone</label>';'
             </fieldset>';
        }
        // add checkbox for allowing post comments
        $marker2 = '<fieldset class="hm-usp usp-category">';
        /*
         $radio_btn =
         '<fieldset class="hm-uspx usp-content">
         <label>Allow people on <a href="http://localhost/tcr_everyone/" target="_blank">tcr-everyone</a> to comment, and optionally get email if they do.</label>
         <label>&nbsp&nbsp&nbsp&nbsp<input type="radio"  name="hm-allow-comment" value="no comments"  checked>&nbspComments not allowed&nbsp&nbsp
         <input type="radio"  name="hm-allow-comment" value="comment-without-notify">&nbspComments allowed&nbsp&nbsp
         <br>&nbsp&nbsp&nbsp&nbsp<input type="radio"  name="hm-allow-comment" value="comment-with-notify"> Comments allowed and get emailed for first comment from each person</label>
         </fieldset>';
         
         
        $radio_btn =
        '<fieldset class="hm-uspx usp-content">
            <label>Allow people on <a href="http://localhost/tcr_everyone/" target="_blank">tcr-everyone</a> to comment.</label>
            <label>&nbsp&nbsp&nbsp&nbsp<input type="radio"  name="hm-allow-comment" value="no comments"  checked>&nbspComments not allowed&nbsp&nbsp
            <input type="radio"  name="hm-allow-comment" value="comment-without-notify">&nbspComments allowed&nbsp&nbsp
 	</fieldset>';
 	         */
        
        $search[] = $marker;
        $replace[] = $marker . DBRK . $hidden_html;
        $search[] = $marker2;
        $replace[] =  $radio_btn  . DBRK . $marker2;
        
        $search[] = 'scroll-top.scroll-top-right{display:none;';
        $replace[] = 'scroll-top.scroll-top-right{display:none !important;';
        
        $search[] = 'Category';
        $replace[] = $category_replace;
        
     //   $search[] = 'category';
      //  $replace[] = strtolower($category_replace);
        
        
        //$search[] = 'Post Title';
        //$replace[] = $post_replace . ' Title';
        
        
        //$search[] = 'Post Content';
        //$replace[] = $post_replace . ' Content';
        
        $search[] = 'type="file"';
        $replace[] = 'type="file"  accept=".jpg,.jpeg,.png,.gif,.pdf"';
        
        
        $search[] = 'Submit Post';
        $replace[] = 'SUBMIT ' . $submit_replace;
        
        $search[] = '>1 - Personal';
        $replace[] = ' selected >1 - Personal';
        
        $search[] = 'Add another image';
        $replace[] = 'Add another image (or pdf)';
        

        
        $search[] = 'Post posts.';
        $replace[] = $post_replace;

        for ($i = 0; $i < count($search); $i++) {
            $buffer = str_replace($search[$i], $replace[$i], $buffer);
        }
        
        return $buffer;
    }
    
    
function _hm_add_page($buffer) {
    
    $search = array();
    $replace = array();
    /*
		<fieldset class="usp-custom">
			<label for="user-submitted-custom">Custom Field</label>
			<input id="user-submitted-custom" name="usp_xform_name" type="text" value="" placeholder="Custom Field" data-required="true" required class="usp-input">
		</fieldset>

     */

            // add checkbox for who can post
    $marker2 = '<fieldset class="usp-custom">';
    
    $radio_btn = '<fieldset class="hm-uspx usp-content">
     <label>Allow the following group to post to this page<BRK></label>';
    $radio_btn .= '<label>&nbsp&nbsp&nbsp&nbsp<input type="radio"  name="hm-postables" value="tcr-owners"  checked>&nbspTCR Owners &nbsp&nbsp';

    $radio_btn .= '<input type="radio"  name="hm-postables" value="tcr-residents" checked>&nbsp TCR Residents&nbsp&nbsp';
    $radio_btn .=  '&nbsp&nbsp&nbsp&nbsp<input type="radio"  name="hm-postables" value="tcr-everyone"> TCR Everyone</label>';'
    </fieldset>';                        

    $search[] = $marker2;
    $replace[] =  $radio_btn  . DBRK . $marker2;
     

    $search[] = '<label for="user-submitted-custom">Custom Field</label>';
    $replace[] = '';
    
    $search[] = 'name="usp_xform_name" type="text" value=""';
    $replace[] = 'name="usp_xform_name" type="hidden" value="add-pages"';
    
    $search[] = 'Post Title';
    $replace[] = 'New Page Title';
    
    $search[] = 'Post Category';
    $replace[] = 'New Page Parent Category';
    
    $search[] = 'Submit Post';
    $replace[] = 'Add New Page';
    
    
    $search[] = '<option value="46">1 - Personal Photos/Posts</option>';
    $replace[] = '';
    
    
    for ($i = 0; $i < count($search); $i++) {
        $buffer = str_replace($search[$i], $replace[$i], $buffer);
    }
    return $buffer;
    
}

function _hm_ob_no_menu($buffer) {

    
    $search = array();
    $replace = array();
    
    $search[] = '</style></head>';
    $replace[] = '</style><style>header#site-header{display:none;}</style></head>';
    
    for ($i = 0; $i < count($search); $i++) {
        $buffer = str_replace($search[$i], $replace[$i], $buffer);
    }
    return $buffer;
}

function _hm_ob_table($buffer) {
    
    $search = array();
    $replace = array();
    
    $search[] = 'type="file"';
    $replace[] = 'type="file"  accept=".csv,.xls,.xlsx"';
    
    $search[] = 'Upload an Image';
    $replace[] = 'Upload a Table (.csv or .xls or .xlsx)';
    
    $search[] = 'Please select your image(s) to upload.';
    $replace[] = 'Please select your table to upload.';
    
    $search[] = 'Add another image';
    $replace[] = '';
    
    
    
    for ($i = 0; $i < count($search); $i++) {
        $buffer = str_replace($search[$i], $replace[$i], $buffer);
    }
    
    return $buffer;
}
function _hm_ob_pdf($buffer) {
    
    $search = array();
    $replace = array();
    
    $search[] = 'type="file"';
    $replace[] = 'type="file"  accept=".pdf';
    
    $search[] = 'Upload an Image';
    $replace[] = "Upload a 'pdf' ";
    
    $search[] = 'Please select your image(s) to upload.';
    $replace[] = 'Please select your pdf to upload.';
    
    $search[] = 'Add another image';
    $replace[] = '';
  
    for ($i = 0; $i < count($search); $i++) {
        $buffer = str_replace($search[$i], $replace[$i], $buffer);
    }
    
    return $buffer;
}
function _hm_ob_search($buffer) {

    $search = array();
    $replace = array();
    // drop an option - for non-author
    if (!hm_check_role( 'author')) {
        $search[] = '<label><input id="min" type="radio" name="hm-limit"  value="Minutes-Committees"> <span>Minutes / Committees</span></label>';
        $replace[] = '';
    }
    $search[] = '<body class';
    $replace[] = '<body OnLoad="document.searchform.s.focus();" class';
	
	$search[] = '>here<';
    $replace[] = '>=>here<=<';

    for ($i = 0; $i < count($search); $i++) {
        $buffer = str_replace($search[$i], $replace[$i], $buffer);
    }

    return $buffer;
}
/*
 * substitute our search phrase on a per post basis
 */
function _hm_ob_hilite($buffer) {
    
    global $hm_hilite;
    hm_log($hm_hilite, '_hm_ob_hilite $hm_hilite', false, -1, 'hilite');
    //return $buffer;
    $new_buffer = $buffer;
    foreach ($hm_hilite as $key => $value) {
        hm_log($value, '_hm_ob_hilite $value', false, -1, 'hilite');
        $new_buffer = str_replace($key, $key . '/?hm-hilite=' . urlencode($value), $new_buffer);
    }
    return $new_buffer;
}
/*
 * return an array of category ID's for a string of comma delimited category names and their children
 */
function hm_get_cat_with_ids($cats_names) {
    hm_logx('hm-category2page', $cats_names);
    $id_array = array();
    $names = explode(',', $cats_names);
    foreach ($names as $name) {
        $id = get_category_by_slug($name)->cat_ID;
        hm_logx('hm-category2page', $id);
        $id_array[] = $id;
        $ids = get_term_children( $id->cat_ID, 'category' );
        hm_logx('hm-category2page', $ids);
        if (is_array($ids)) $id_array = array_merge($ids, $id_array);
    }
    return $id_array;
}
function hm_make_shortcode($shortcode) {
    return SC_PRE . $shortcode . SC_PST;
}
function hm_update_content($post_id, $content, $append = true) {
    if ($append) {
        $content = get_post($post_id)->post_content . $content;    
    }
    $result = wp_update_post(array('ID'=>$post_id, 'post_content'=>$content));
    return $result;
}
// obsolete ??
add_filter('xpre_get_posts', 'hm_posts_for_current_author');
function hm_posts_for_current_author($query) {
    global $pagenow;
    hm_log($pagenow, 'hm_posts_for_current_author $pagenow');
    if( 'edit.php' != $pagenow || !$query->is_admin )
        return $query;
        
    if( !hm_check_role('administrator,editor')) {
        global $user_ID;
        $query->set('author', $user_ID );
        hm_log($user_ID, 'hm_posts_for_current_author $user_ID');
    }
    return $query;
}
function hm_alter_the_edit_screen_query( $wp_query ) {
    if ( strpos( $_SERVER[ 'REQUEST_URI' ], '/wp-admin/edit.php' ) !== false ) {
        if (  !hm_check_role('administrator,editor')     )  {
            add_action( 'views_edit-post', 'hm_remove_items_from_edit' );
            global $current_user;
            $wp_query->set( 'author', $current_user->id );
        }
    }
}
add_filter('parse_query', 'hm_alter_the_edit_screen_query' );
function hm_remove_items_from_edit( $views ) {
    hm_log($views, '',false,-1,'views');
    hm_redirect();
    unset($views['all']);
    unset($views['publish']);
    unset($views['trash']);
    unset($views['draft']);
    unset($views['pending']);
    return $views;
}
//wp_insert_comments
add_action('wp_insert_comment','hm_wp_insert_comment',20,2);
function hm_wp_insert_comment($comment_id, $comment_object) {
    // see if user wants a notification for a comment
    $post_id = $comment_object->comment_post_ID;
    $meta_key = 'hm_notify_me';
    $meta_value = get_post_meta($post_id, $meta_key, true);
    if (false === $meta_value) return;
    
    // don't notify if this is a second comment from any user 
    //$comment_author = $comment_object->comment_author;
    // if (isset($meta_value['$comment_author'])) return;
    if (isset($meta_value['any'])) return;
    
    
    // don't notify for author responding to a comment
    $comment_user = get_user_by('email', $comment_object->comment_author_email);
    $post = get_post($post_id);
    $author_id = $post->post_author;
    if (isset($comment_user) && ($comment_user->ID == $author_id)) return;   
    
    // send the email
    $subject = $comment_author . ' commented on ' . $post->post_title;
    $message = substr($comment_object->comment_content, 0, $max_email);
    $result = hm_send_mail($author_id, $subject, $message);
    if ($result) {
        //$meta_value['$comment_author'] = '';
        $meta_value['any'] = true;
        update_post_meta($post_id, $meta_key, $meta_value);
    }
    hm_log($result, 'hm_wp_insert_comment $result');
  
}
// accepts a string of categories and outputs a grouping for each category
// thin filtering wrapper over plugin 'display posts'
// https://displayposts.com/docs/filters/
add_shortcode( 'hm-display-posts', 'hm_display_posts_shortcode' );

function hm_display_posts_shortcode($atts) {
    global $hm_vars;
    global $total_posts, $x_more;
    // only logged in users get to see posts via this shortcode
    if (0 == get_current_user_id()) return '';
    // must specify a category
    if (!isset($atts['category']) || ($atts['category'] == '')) return '';
    // here are our defaults
    if (!isset($atts['include_date'])) $atts['include_date'] = true;
    if (!isset($atts['posts_per_page']))  $atts['posts_per_page'] = hm_get_const_value('HM_POSTS_PER_PAGE', 7);
    if (!isset($atts['include_author']))  $atts['include_author'] = "true";
    if (!isset($atts['title']))  $atts['title'] = "Recent Posts<br>";
    if (isset($atts['new_window'])) {
        $new_window = $atts['new_window'];
        unset( $atts['new_window']);
    }
    $atts['offset'] = !empty($_REQUEST['offset']) ? $_REQUEST['offset'] : 0;
           
    // allow for multiple categories - comma separated list 
    $cats = explode(',',$atts['category']);
    if (($cats[0] != 'all') && ($atts['offset'] == 0)) {
        // check for 'personal' parent of first
        $cat_id = get_category_by_slug(strtolower($cats[0]))->term_id;
        $cat_parent = get_term_parents_list($cat_id, 'category', array('format'=>'slug'));
        if (is_string($cat_parent)) {
            $personal = hm_get_const_value('HM_PERSONAL_CAT','personal-photos-posts');
            if (stripos($cat_parent, $personal) !== false) {
                // treat this as display the first recent personal post in full
                // and then links to the rest of their personal posts
                $output = _hm_default_display_posts($atts, $cats[0]);
                return  $output;     
            }
        }
    }
    // start category and restriction logic
    // 'all'  and not restricted just drop 'category
    // 'all'  and restricted use 'category__not_in'
    // always drop 'administrator
    // not 'all and not restricted, nop
    // not 'all and restricted, drop out restricted cat from list
    $is_restricted_role = !hm_check_role('author,editor,administrator');
    $restricted_cats =  ($is_restricted_role) ? _hm_restricted_cats() : null;
    if (in_array('all',$cats)) {
        unset($atts['category']);
        $atts['category_display'] = 'true';
        $atts['category_label'] = '- Topic: ';
        
        //display_posts_shortcode_args', $args, $original_atts )
        add_filter('display_posts_shortcode_args','hm_display_posts_shortcode_args', 10, 1);
        
        if ($is_restricted_role) {
            // pass along to filter since display-posts doesn't expose this option
            $hm_vars['category__not_in'] = $restricted_cats;
        }
        // drop out admin posts
    }
    elseif ($is_restricted_role){
        // examine cats to see if any parent is restricted
        $mod_cats = array();
        foreach ($cats as $cat) {
            if (!in_array($cat, $restricted_cats)) $mod_cats[] = $cat;
        }
        $atts['category'] = implode(',', $mod_cats);      
    }  
    // end category and restriction logic
    $more_post_offset =  $atts['offset'] +  $atts['posts_per_page'];
    $atts['posts_per_page']++;
    $total_posts = 0; $x_more = 0;;
    $display_posts = be_display_posts_shortcode( $atts );
    hm_log($display_posts,'$display_posts', false, -1, 'display_posts',2048);
    
    return  ($x_more) ? _hm_add_more ($display_posts, $more_post_offset) : $display_posts;
}
function hm_display_posts_shortcode_args($args) {
    global $hm_vars;
    $exclude = get_users(array('fields'=>'ID', 'role__in'=>array('administrator','editor')));
    hm_log($exclude, '', false, -1, 'args',3000);
    $args['author__not_in'] = $exclude;
    if (!empty($hm_vars['category__not_in'])) $args['category__not_in'] = $hm_vars['category__not_in'];
    return $args;
}

    
//apply_filters( 'display_posts_shortcode_output'
// we need to count how many we got
add_filter('display_posts_shortcode_output','hm_display_posts_count', 10, 2);
function hm_display_posts_count($output, $original_atts) {
    global $total_posts, $x_more;
    $total_posts++; 
    // we always have asked for one more than needed, to determine whether there is more
    if ($total_posts >= $original_atts['posts_per_page']) {
        $x_more = 1;
        return '';
    }
    return $output;
}

//  put up 'more' link with offset
function _hm_add_more($display_posts, $more_post_offset) {
    global $hm_vars;
    $char0 =  (strpos($hm_vars['uri'], '?') != false) ? '&'  : '?';
    $href = home_url() . '/index.php' .  $hm_vars['uri'] . $char0 . 'offset=' . $more_post_offset;
    $more_link = DBRK . '...  <a href="' . $href .'">more</a>  ...';
    // $more_link = "DBRK . '... ' . '<a href="'. $href .'">more</a>' . ' ...';
    $display_posts .= $more_link;
    return $display_posts;
}
    
 // which categories are restricted - the model is that all are under a few parents
 function _hm_restricted_cats() {
     $restricted_slugs = hm_get_const_value('HM_CAT_RESTRICTED','3-posts-to-records,4-posts-to-committees');
     $restricted_cats = array();
     foreach (explode(',',$restricted_slugs) as $restricted_slug) {
         $restricted_id = get_category_by_slug($restricted_slug)->cat_ID;
         $restricted_cats = array_merge(get_term_children($restricted_id, 'category'),$restricted_cats); 
     }
     return $restricted_cats;
 }
 
 function _hm_default_display_posts(&$atts, $user_name){
     global $total_posts, $x_more;
     $npm = hm_get_const_value('HM_NO_PERSONAL','<p class="has-text-align-center">$user_name has not made any personal posts yet.</p>');
     $npm = str_replace('$user_name', $user_name, $npm);
     $def_ppp = $atts['posts_per_page'];
     $orig_offset = $atts['offset'];
    // first time thru display full post
     if ($orig_offset == 0) {
         $atts['posts_per_page'] = '2';
         $atts['include_content'] = true;
         $atts['include_author'] = false;
         $atts['include_date'] = false;
         $total_posts = 0; $x_more = 0;
         $display_posts = be_display_posts_shortcode( $atts );
         if ($display_posts == '') return $npm;
         if (!$x_more) return $display_posts;
         $atts['posts_per_page'] = $def_ppp;
         $atts['offset'] = 1;         
         unset($atts['no_posts_message']);
     }
     else {
         $atts['posts_per_page'] = $def_ppp + 1;         
     }
     // just display one liners
     $yop = 'Your other posts';
     $atts['include_title'] = true;
     $atts['include_date'] = true;
     $atts['include_content'] = false;
     $atts['include_date'] = true;
     $atts['title'] = $yop;
     $total_posts = 0; $x_more = 0;
     $display_posts_other = be_display_posts_shortcode($atts);
     // if (!$x_more || ($display_posts_other == '' )) return $display_posts . ;

     // if the other posts are clicked put them in a new tab/window without a menu
     $display_posts_other = _hm_new_window($display_posts_other);
     if ($x_more) {
         $new_offset = $orig_offset + $def_ppp;
         $display_posts_other = _hm_add_more($display_posts_other, $new_offset, );         
     }
     return $display_posts . DBRK . $display_posts_other;    
 }
 /*
  * force the anchor link(s) to open in a new window, and with no menu showing
  */
 function _hm_new_window($html) {
     $html = str_replace("\r\n", ' ', $html);
     $f = 'href="';
     $r = 'target="_blank" '  . $f;
     $c = 0;
     $html = str_replace($f, $r,$html, $c);
     $f = '/">';
     $r = '/?no_menu">';
     $html = str_replace($f, $r, $html, $c);
     return $html;    
 }
 
 /*
  * parse the uploaded $_FILES into two groups - all maintaining the structure of $_FILES
  *   - param - $pdf_files - empty input array passed by reference - pdf files
  *   return array of image files
  */
 function hm_break_out_files( $form_name, &$ni) {
     if (!isset($_FILES[$form_name]))  return $_FILES;
     
     $names = $_FILES[$form_name]['name'];
     $image = array();
     $image[$form_name] = array();
     $image[$form_name]['name'] = array();
     $image[$form_name]['type'] = array();
     $image[$form_name]['tmp_name'] = array();
     $image[$form_name]['error'] = array();
     $image[$form_name]['size'] = array();
     $image[$form_name]['ext'] = array();
     $ni = $image;
     for ($i = 0; $i < count($names); $i++) {
         $ext = pathinfo($names[$i], PATHINFO_EXTENSION );
         switch (strtolower($ext)) {
              case 'pdf' :
                 _hm_break_out_files($form_name,$ni, $i, $ext);
                 break;
             case 'jpg' :
             case 'jpeg' :
             case 'png' :
             case 'gif' :
                 _hm_break_out_files($form_name,$image, $i, $ext);
                 break;
             default: // nop;
          }
     }
     if (count($ni[$form_name]['name']) == 0) unset($ni[$form_name]);
     return $image;
 }
 
 function _hm_break_out_files($form_name, &$array, $index, $ext) {
     if (0 != $_FILES[$form_name]['error'][$index]) return;
     $array[$form_name]['name'][] = $_FILES[$form_name]['name'][$index]; 
     $array[$form_name]['type'][] = $_FILES[$form_name]['type'][$index];
     $array[$form_name]['tmp_name'][] = $_FILES[$form_name]['tmp_name'][$index];
     $array[$form_name]['error'][] = $_FILES[$form_name]['error'][$index];
     $array[$form_name]['size'][] = $_FILES[$form_name]['size'][$index];
     $array[$form_name]['ext'][] = $ext;
 }
 
 add_action( 'post_updated', 'hm_post_updated', 10, 3);
 /**
  * in order for search mods to work correctly, posts/pages need a non-empty excerpt
  */
 function hm_post_updated( $post_ID, $post_after, $post_before) {
     hm_log($post_ID, 'hm_post_updated - triggered');
     if (($post_before->post_type != 'page') && ($post_before->post_type != 'post')) return;
     // prevent looping   
     static $id = array();     
     remove_action( 'post_updated', 'hm_post_updated', 10);
     if ($post_after->post_excerpt == '') {
         if(!in_array($post_ID, $id, true)) {
             $id[] = "$post_ID";             
             wp_update_post(array('ID' => $post_after->ID, 'post_excerpt' => '...'));
         }
         hm_log($post_ID, 'hm_post_updated');
     }
     // restore
     add_action( 'post_updated', 'hm_post_updated', 10, 3);
 }
 
 function hm_send_mail($user_id_or_email, $subject, $message, $headers = null, $max_msg = null) {
     // send the email
     if ($user_id_or_email == '') {
         $email = wp_get_current_user()->user_email;
     }
     elseif (is_int($user_id_or_email)) {
         $email = get_user_by('ID', $user_id_or_email)->user_email;
     }
     else {
         $email = $user_id_or_email;
     }
     if (is_null($headers)) $headers = array();
     $headers[] = 'From: ' . hm_get_const_value('HM_REPLY_TO', 'tcr_reply_to@sonic.net');
     if (is_null($max_msg)) {
         $max_msg = hm_get_const_value('HM-MAX-EMAIL', 254);
     }
     $message = substr($message, 0, $max_msg);
     $result = wp_mail($email, $subject, $message, $headers );
     return $result;
 }
 
 
 	// Apply filters and return
 // return apply_filters( 'ocean_display_breadcrumbs', $return );
    add_filter('ocean_display_breadcrumbs','hm_ocean_display_breadcrumbs');
    function  hm_ocean_display_breadcrumbs($return) {
		$return = (get_current_user_id() > 0);

        hm_logx('bc', $return);
        // if not logged on then don't display breadcrumbs
       // return (get_current_user_id() > 0);  
       return $return;
    }
 
 // Allow developers to overwrite the items for the breadcrumb trail.
 // $this->items = array_unique( apply_filters( 'breadcrumb_trail_items', $this->items, $this->args ) );
 //add_filter('breadcrumb_trail_items','hm_breadcrumb_trail_items', 10, 2);
 function hm_breadcrumb_trail_items ($items, $args) {
     // this serves as a proxy for breadcrumbs to a page
     if (count($items) == 2) {
         $crumbs =  wpd_nav_menu_breadcrumbs('tcr_menu');
         hm_logx('bcmb', $crumbs);
         return $crumbs;
     }
     else {
         $items = array_slice($items, 1);
         hm_logx('bcmb', $items);
     }
     /*
     if (count($items) == 2) {
         if (strtolower($items[0]) == 'home') {
             $items = array_slice($items, 1);
         }    
     }  
     */   
     return $items;
  }
  // from https://wordpress.stackexchange.com/users/4771/milo 
 // helper function to find a menu item in an array of items
 function wpd_get_menu_item( $field, $object_id, $items ){
     foreach( $items as $item ){
         if( $item->$field == $object_id ) return $item;
     }
     return false;
 }
 
 function wpd_nav_menu_breadcrumbs( $menu ){
     // get menu items by menu id, slug, name, or object
     $items = wp_get_nav_menu_items( $menu );
     if( false === $items ){
         echo 'Menu not found';
         return;
     }
     // get the menu item for the current page
     $item = wpd_get_menu_item( 'object_id', get_queried_object_id(), $items );
     if( false === $item ){
         return;
     }
     // start an array of objects for the crumbs
     $menu_item_objects = array( $item );
     // loop over menu items to get the menu item parents
     while( 0 != $item->menu_item_parent ){
         $item = wpd_get_menu_item( 'ID', $item->menu_item_parent, $items );
         array_unshift( $menu_item_objects, $item );
     }
     // output crumbs
     $crumbs = array();
     foreach( $menu_item_objects as $menu_item ){
         $link = '<a href="%s">%s</a>';
         $crumbs[] = sprintf( $link, $menu_item->url, $menu_item->title );
     }
     return $crumbs ;
 }
 
 

 

