/**
         * settings_screen() is the catch-all method for displaying the content 
         * of the edit, create, and Dashboard admin panels
         */
        function settings_screen($group_id = NULL)
        {
            $categories = CMA_Category::getCategoriesTree(null, 0, $onlyVisible = false);
            $currentCategory = $this->getRelatedCategory();
            $options = '<option value="">-- none --</option>';
            foreach ($categories as $categoryId => $categoryName) {
                $options .= sprintf('<option value="%s"%s>%s</option>', esc_attr($categoryId), selected($categoryId, $currentCategory, false), esc_html($categoryName));
            }
            printf('<p><label for="cma-category">%s</label>
			<select name="cma-category" id="cma-category">%s</select></p>', CMA::__('Related CM Answers category'), $options);
        }
 public static function general_shortcode($atts, $widget = true)
 {
     $atts = is_array($atts) ? $atts : array();
     $displayOptionsDefaults = CMA_Settings::getDisplayOptionsDefaults();
     $atts = CMA_Thread::sanitize_array($atts, array('limit' => array('int', 5), 'cat' => array('*', null), 'tag' => array('*', null), 'author' => array('string', null), 'contributor' => array('string', null), 'answered' => array('bool', null), 'resolved' => array('bool', null), 'sort' => array('string', CMA_Settings::getOption(CMA_Settings::OPTION_INDEX_ORDER_BY)), 'order' => array('string', 'desc'), 'tiny' => array('bool', false), 'form' => array('bool', $displayOptionsDefaults['form']), 'displaycategories' => array('bool', (bool) $displayOptionsDefaults['categories']), 'resolvedprefix' => array('bool', $displayOptionsDefaults['resolvedPrefix']), 'icons' => array('bool', $displayOptionsDefaults['icons']), 'pagination' => array('bool', $displayOptionsDefaults['pagination']), 'hidequestions' => array('bool', $displayOptionsDefaults['hideQuestions']), 'search' => array('bool', $displayOptionsDefaults['search']), 'votes' => array('bool', $displayOptionsDefaults['votes']), 'views' => array('bool', $displayOptionsDefaults['views']), 'answers' => array('bool', $displayOptionsDefaults['answers']), 'updated' => array('bool', $displayOptionsDefaults['updated']), 'authorinfo' => array('bool', $displayOptionsDefaults['authorinfo']), 'statusinfo' => array('bool', $displayOptionsDefaults['statusinfo']), 'tags' => array('bool', $displayOptionsDefaults['tags']), 'wrapperclass' => array('string', $displayOptionsDefaults['wrapperclass']), 'navbar' => array('bool', false), 'sortbar' => array('bool', false), 'ajax' => array('bool', true), 'showid' => array('bool', false), 'dateposted' => array('bool', false), 'showcontent' => array('bool', false), 'formontop' => array('bool', $displayOptionsDefaults['formontop']), 'subtree' => array('bool', $displayOptionsDefaults['subtree'])));
     if ($atts['tiny']) {
         $atts['pagination'] = false;
     }
     $search = esc_attr(CMA_AnswerController::$query->get('search'));
     $paged = esc_attr(CMA_AnswerController::$query->get('paged'));
     $questionsArgs = array('post_type' => CMA_Thread::POST_TYPE, 'post_status' => 'publish', 'posts_per_page' => $atts['limit'], 'paged' => $paged, 'orderby' => $atts['sort'], 'order' => $atts['order'], 'fields' => 'ids', 'widget' => true, 'tag' => empty($atts['tag']) ? isset($_GET["cmatag"]) ? $_GET["cmatag"] : '' : $atts['tag'], 'search' => $search);
     if (!is_null($atts['resolved'])) {
         $questionsArgs['meta_query'] = array(array('key' => CMA_Thread::$_meta['resolved'], 'value' => intval($atts['resolved'])));
     }
     if (!empty($atts['user_questions'])) {
         $questionsArgs['user_questions'] = $atts['user_questions'];
     }
     if (!empty($atts['author'])) {
         if (!is_numeric($atts['author'])) {
             if ($user = get_user_by('slug', $atts['author'])) {
                 $atts['author'] = $user->ID;
             } else {
                 $atts['author'] = null;
             }
         }
         $questionsArgs['author'] = $atts['author'];
     }
     if (!empty($atts['contributor']) and !is_numeric($atts['contributor'])) {
         if ($user = get_user_by('slug', $atts['contributor'])) {
             $atts['contributor'] = $user->ID;
         } else {
             $atts['contributor'] = null;
         }
     }
     $category = null;
     if (!empty($atts['cat'])) {
         // there may be multiple categories separated by commas
         if (!is_array($atts['cat'])) {
             $categories = explode(',', $atts['cat']);
         } else {
             $categories = $atts['cat'];
         }
         $categories = array_filter($categories);
         $categoriesSlugs = array();
         foreach ($categories as $i => $cat) {
             if (!is_scalar($cat)) {
                 continue;
             }
             if (preg_match('/^[0-9]+$/', $cat)) {
                 $category = get_term($cat, CMA_Category::TAXONOMY);
                 $categoriesSlugs[] = $category->slug;
                 $catId = $cat;
             } else {
                 if ($category = get_term_by('slug', trim($cat), CMA_Category::TAXONOMY)) {
                     $catId = $category->term_id;
                     $categoriesSlugs[] = $category->slug;
                 } else {
                     $catId = false;
                 }
             }
             if ($catId) {
                 if (empty($questionsArgs['tax_query'][0])) {
                     $questionsArgs['tax_query'][0] = array('taxonomy' => CMA_Category::TAXONOMY, 'field' => 'term_id', 'terms' => array($catId));
                 } else {
                     $questionsArgs['tax_query'][0]['terms'][] = $catId;
                 }
             }
         }
         $atts['cat'] = implode(',', $categoriesSlugs);
     }
     $customWhereCallback = function ($val) use($atts) {
         global $wpdb;
         if (!is_null($atts['answered'])) {
             $val .= CMA_AnswerController::registerCommentsFiltering($val, $atts['answered'] ? 'ans' : 'unans');
         }
         if (!empty($atts['contributor'])) {
             $val .= $wpdb->prepare(" AND (post_author = %d OR ID IN (\n        \t\t\tSELECT wc.comment_post_ID FROM {$wpdb->comments} wc\n        \t\t\t\tWHERE wc.user_id = %d\n        \t\t\t\tAND wc.comment_approved = 1\n        \t\t\t))", $atts['contributor'], $atts['contributor']);
         }
         $val .= " AND {$wpdb->posts}.ID IS NOT NULL";
         return $val;
     };
     $questionsArgs = apply_filters('cma_questions_shortcode_query_args', $questionsArgs, $atts);
     add_filter('posts_where_request', $customWhereCallback);
     add_filter('posts_where_request', array('CMA_AnswerController', 'categoryAccessFilter'));
     $q = CMA_Thread::customOrder(new WP_Query(), $atts['sort']);
     foreach ($questionsArgs as $key => $val) {
         $q->set($key, $val);
     }
     $questions = array_map(array('CMA_Thread', 'getInstance'), $q->get_posts());
     $maxNumPages = $atts['maxNumPages'] = $q->max_num_pages;
     $paged = $q->query_vars['paged'];
     remove_filter('posts_where_request', $customWhereCallback);
     remove_filter('posts_where_request', array('CMA_AnswerController', 'categoryAccessFilter'));
     $displayOptions = array('hideQuestions' => $atts['hidequestions'], 'tags' => !$atts['tiny'], 'pagination' => !$atts['tiny'] && $atts['pagination'], 'form' => $atts['form'], 'categories' => $atts['displaycategories'], 'search' => $atts['search'], 'votes' => $atts['votes'], 'views' => $atts['views'], 'answers' => $atts['answers'], 'updated' => $atts['updated'], 'authorinfo' => $atts['authorinfo'], 'tags' => $atts['tags'], 'statusinfo' => $atts['statusinfo'], 'wrapperclass' => $atts['wrapperclass'], 'navbar' => $atts['navbar'], 'sortbar' => $atts['sortbar'], 'formontop' => $atts['formontop'], 'resolvedPrefix' => $atts['resolvedprefix'], 'icons' => $atts['icons'], 'showid' => $atts['showid'], 'dateposted' => $atts['dateposted'], 'showcontent' => $atts['showcontent'], 'subtree' => $atts['subtree']);
     $checkPermissions = true;
     $widget = true;
     $category = CMA_Category::getInstance($category);
     $options = array_merge($atts, compact('displayOptions', 'catId', 'maxNumPages', 'paged', 'widget', 'search', 'checkPermissions'));
     $options['checkPermissions'] = false;
     $options = apply_filters('cma_questions_shortcode_widget_options', $options);
     $widgetCacheId = $options['widgetCacheId'] = CMA_AnswerController::saveWidgetOptions($options);
     $options['questions'] = $questions;
     CMA_BaseController::loadScripts();
     $result = CMA_BaseController::_loadView('answer/widget/questions', $options);
     if ($atts['ajax']) {
         $result = '<div class="cma-widget-ajax" data-widget-cache-id="' . $widgetCacheId . '">' . $result . '</div>';
     }
     return $result;
 }
 public static function getCategoryAccessFilterSubquery($userId = null)
 {
     global $wpdb;
     if (is_null($userId)) {
         $userId = CMA::getPostingUserId();
     }
     if (empty($userId)) {
         $userId = 0;
     }
     if (user_can($userId, 'manage_options')) {
         // Admin can view all categories
         return $wpdb->prepare("SELECT tr.object_id\n\t    \t\tFROM {$wpdb->term_relationships} tr\n    \t\t\tINNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id\n\t    \t\tWHERE tt.taxonomy = %s", CMA_Category::TAXONOMY);
     } else {
         $sql = "SELECT tr.object_id\n\t    \t\tFROM {$wpdb->term_relationships} tr\n\t    \t\tJOIN {$wpdb->posts} p ON p.ID = tr.object_id\n\t    \t\tWHERE 1=1";
         if ($ids = CMA_Category::getVisibleTermTaxonomyIds($userId)) {
             // there are visible categories:
             $sql .= " AND tr.term_taxonomy_id IN (" . implode(',', $ids) . ")";
         } else {
             // there is no visible categories so reject all ids:
             $sql .= " AND 1=0 ";
         }
         if (CMA_Settings::getOption(CMA_Settings::OPTION_RESTRICT_UNANSWERED_QUESTIONS_TO_EXPERTS)) {
             $sql .= " AND (p.comment_count > 0";
             // question is unanswered
             if ($ids = CMA_Category::getExpertsTermTaxonomyIds($userId)) {
                 // or I'm the expert in question's category
                 $sql .= " OR tr.term_taxonomy_id IN (" . implode(',', $ids) . ")";
             }
             $sql .= ")";
         }
         return $sql;
     }
 }
 public static function getRootCategories($onlyVisible = true)
 {
     $cats = array();
     $terms = get_terms(CMA_Category::TAXONOMY, array('orderby' => 'name', 'hide_empty' => 0, 'parent' => null));
     foreach ($terms as $term) {
         if (!$onlyVisible or $category = CMA_Category::getInstance($term->term_id) and $category->isVisible()) {
             $cats[$term->term_id] = $term->name;
         }
     }
     return $cats;
 }
 public static function get_header($name = null)
 {
     $wp_query = self::$query;
     if (!CMA_Settings::getOption(CMA_Settings::OPTION_SEO_META_REWRITE_ENABLED)) {
         get_header($name);
         return;
     }
     ob_start();
     get_header($name);
     $content = ob_get_clean();
     if ($desc = static::getMetaDescription()) {
         $content = self::replaceHeadTag($content, '#(<meta name="description" content=")([^"]+)("[ /]*>)#i', '<meta name="description" content="' . esc_attr($desc) . '">', $desc, $append = true);
     }
     if ($keywords = CMA_Settings::getOption(CMA_Settings::OPTION_INDEX_META_KEYWORDS)) {
         $content = self::replaceHeadTag($content, '#(<meta name="keywords" content=")([^"]+)("[ /]*>)#i', '<meta name="keywords" content="' . esc_attr($keywords) . '">', $keywords, $append = true);
     }
     if (!$wp_query->is_single() and $title = CMA_Settings::getOption(CMA_Settings::OPTION_INDEX_META_TITLE)) {
         $content = self::replaceHeadTag($content, '#(<title>)([^<]+)(</title>)#i', '<title>' . esc_html($title) . '</title>', $title, $append = false);
     }
     // ---------------------------------------------------------------------------------------------------
     // Add canonical
     if ($wp_query->get('CMA-contributor-index')) {
         if ($user = get_user_by('slug', $wp_query->get('contributor'))) {
             $canonical = self::getContributorUrl($user);
         }
     } else {
         if ($wp_query->is_post_type_archive(CMA_Thread::POST_TYPE)) {
             $obj = $wp_query->get_queried_object();
             if (isset($obj->term_id) and $category = CMA_Category::getInstance($obj->term_id)) {
                 $canonical = $category->getPermalink();
             } else {
                 $canonical = CMA::permalink();
             }
         } else {
             if ($wp_query->is_single() and $wp_query->get('post_type') == CMA_Thread::POST_TYPE) {
                 // Canonical is added by WP
             }
         }
     }
     if (!empty($canonical)) {
         $content = self::replaceHeadTag($content, '#(<link rel=[\'"]?canonical[\'"]? href=[\'"])([^\'"]+)([\'"][ /]*>)#i', '<link rel="canonical" href="' . esc_attr($canonical) . '">', $canonical, $append = false);
     }
     echo $content;
 }
 static function questionForm($categoryId, $threadId = null)
 {
     if ($category = CMA_Category::getInstance($categoryId)) {
         $fields = $category->getCustomFields();
         if ($threadId and $thread = CMA_Thread::getInstance($threadId)) {
             $values = $thread->getCategoryCustomFields();
         } else {
             $values = array_fill(0, count($fields), '');
         }
         echo self::_loadView('answer/meta/question-form-category-custom-fields', compact('fields', 'values'));
     }
 }
    public static function getByUser($user_id, $approved = null, $limit = -1, $page = 1, $onlyVisible = true)
    {
        global $wpdb;
        if (!$user_id) {
            return array();
        }
        $limitPart = '';
        if ($limit > 1) {
            $limitPart = 'LIMIT ' . intval($limit) . ' OFFSET ' . intval($limit * ($page - 1));
        }
        $where = '';
        if (!is_null($approved)) {
            $where .= ' AND c.comment_approved = ' . intval($approved);
        }
        if ($onlyVisible) {
            if ($user_id != get_current_user_id()) {
                $where .= ' AND (cmpa.meta_value IS NULL OR cmpa.meta_value <> 1)';
            }
            if (CMA_Category::isAnyCategoryResticted()) {
                $where .= ' AND (c.comment_post_id IN (' . CMA_Thread::getCategoryAccessFilterSubquery() . ')
	    					OR c.comment_post_id NOT IN (' . CMA_Thread::getCategorizedThreadIdsSubquery() . '))';
            }
        }
        $query = $wpdb->prepare("SELECT c.* FROM {$wpdb->comments} c\n\t\t\t\tINNER JOIN {$wpdb->posts} p ON p.ID = c.comment_post_ID\n\t\t\t\tLEFT JOIN {$wpdb->commentmeta} cmpa ON c.comment_id = cmpa.comment_id AND cmpa.meta_key = %s\n\t\t\t\tWHERE user_id = %d\n\t\t\t\tAND c.comment_type = %s", self::META_PRIVATE, $user_id, self::COMMENT_TYPE) . " {$where} ORDER BY comment_id DESC {$limitPart}";
        $comments = $wpdb->get_results($query);
        $result = array();
        foreach ($comments as $comment) {
            $result[] = new self($comment);
        }
        return $result;
    }
 protected static function _processLoadSubcategories()
 {
     $categoryId = self::_getParam('cma-category-id');
     $result = array();
     if (!CMA_Settings::getOption(CMA_Settings::OPTION_ALLOW_POST_ONLY_SUBCATEGORIES)) {
         $result[] = array('id' => 0, 'name' => CMA_Labels::getLocalized('all_subcategories'), 'url' => '');
     }
     if (!empty($categoryId)) {
         $categories = CMA_Category::getSubcategories($categoryId);
         foreach ($categories as $category_id => $name) {
             $result[] = array('id' => $category_id, 'name' => $name, 'url' => get_term_link($category_id, CMA_Category::TAXONOMY));
         }
     }
     header('Content-type: application/json');
     echo json_encode($result);
     exit;
 }