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 newThread($data = array())
 {
     $userId = CMA::getPostingUserId();
     $user = get_userdata($userId);
     if (empty($userId) or empty($user)) {
         throw new Exception(CMA::__('Invalid user.'));
     }
     $title = self::titleFilter($data['title']);
     $content = self::contentFilter($data['content'], $userId);
     self::validateTitle($title, $editId = false, $errors);
     if (!CMA_Settings::getOption(CMA_Settings::OPTION_QUESTION_DESCRIPTION_OPTIONAL) && empty($content)) {
         $errors[] = __('Content cannot be empty', 'cm-answers-pro');
     }
     if (($badWord = CMA_BadWords::filterIfEnabled($content)) !== false) {
         $errors[] = sprintf(CMA_Labels::getLocalized('msg_content_includes_bad_word'), $badWord);
     }
     if (!empty($_FILES) and !self::areQuestionAttachmentsAllowed()) {
         $errors[] = __('Upload is not allowed.', 'cm-answers-pro');
     } elseif (!self::validateUploadSize()) {
         $errors[] = __('The file you uploaded is too big', 'cm-answers-pro');
     } elseif (!self::validateUploadNames()) {
         $errors[] = __('The file you uploaded is not allowed', 'cm-answers-pro');
     }
     if (!empty($data['category']) && $data['category'] > 0) {
         if ($category = CMA_Category::getInstance($data['category'])) {
             if (!$category->isVisible()) {
                 $errors[] = CMA::__('You have no permission to post this question.');
             }
         } else {
             $errors[] = CMA::__('Choose a valid category.');
         }
     } else {
         if (CMA_Settings::getOption(CMA_Settings::OPTION_QUESTION_REQUIRE_CATEGORY)) {
             $errors[] = CMA::__('Choose a category.');
         }
     }
     if (!empty($errors)) {
         throw new Exception(serialize($errors));
     }
     if (CMA_Settings::getOption(CMA_Settings::OPTION_QUESTION_AUTO_APPROVE) || self::isAuthorAutoApproved($userId)) {
         $status = 'publish';
     } else {
         $status = 'draft';
         if (self::getSpamFilter() || CMA_Settings::getOption(CMA_Settings::OPTION_SIMULATE_COMMENT)) {
             /** Hack, simulate comment adding to trigger spam filters * */
             $commentdata = array('comment_post_ID' => 0, 'comment_author' => $user->first_name, 'comment_author_email' => $user->user_email, 'comment_author_url' => '', 'comment_content' => $title . ' ' . $content, 'comment_type' => self::POST_TYPE, 'user_ID' => $userId, 'comment_parent' => 0, 'comment_author_IP' => preg_replace('/[^0-9a-fA-F:., ]/', '', $_SERVER['REMOTE_ADDR']), 'comment_date' => current_time('mysql'), 'comment_date_gmt' => current_time('mysql', 1), 'comment_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? substr($_SERVER['HTTP_USER_AGENT'], 0, 254) : '');
             if (CMA_Settings::getOption(CMA_Settings::OPTION_SIMULATE_COMMENT)) {
                 // Simulate comment to detect flood and so on.
                 if (wp_allow_comment($commentdata) == 'spam') {
                     $status = 'draft';
                 }
             }
         }
     }
     $postData = array('post_status' => $status, 'post_type' => self::POST_TYPE, 'post_title' => $title, 'post_content' => $content, 'post_name' => urldecode(sanitize_title_with_dashes(remove_accents($title))), 'post_author' => $userId);
     do_action('cma_question_post_before', $postData);
     $id = wp_insert_post($postData);
     if ($id instanceof WP_Error) {
         return $id->get_error_message();
     } else {
         $instance = self::getInstance($id);
         $instance->setUpdated()->setResolved(false)->setAuthorIP()->checkGeolocation();
         if (!empty($data['notify']) and $data['notify'] == 1) {
             $instance->getFollowersEngine()->addFollower();
         }
         $instance->savePostMeta(array(self::$_meta['views'] => 0));
         $instance->savePostMeta(array(self::$_meta['votes_answers'] => 0));
         $instance->savePostMeta(array(self::$_meta['votes_question'] => 0));
         $instance->savePostMeta(array(self::$_meta['votes_question_answers'] => 0));
         $instance->savePostMeta(array(self::$_meta['highestRatedAnswer'] => 0));
         $instance->savePostMeta(array(self::$_meta['stickyPost'] => 0));
         if (!empty($data['category'])) {
             $r = wp_set_post_terms($id, array($data['category']), CMA_Category::TAXONOMY, true);
         }
         if (isset($data['tags'])) {
             $r = wp_set_post_tags($id, $data["tags"], true);
         }
         if (CMA_Settings::getOption(CMA_Settings::OPTION_USER_RELATED_QUESTIONS_ENABLE) and !empty($data['userRelatedQuestions'])) {
             $instance->setUserRelatedQuestions(CMA_UserRelatedQuestions::getIdsFromRaw($data['userRelatedQuestions']));
         }
         $instance->savePost();
         $attachmentsIds = CMA_QuestionAttachment::handleUpload($instance->getId());
         if (!empty($_POST['attached']) && is_array($_POST['attached'])) {
             $attachmentsIds = array_merge($attachmentsIds, $_POST['attached']);
         }
         foreach ($attachmentsIds as $attachmentId) {
             if (!empty($attachmentId)) {
                 $instance->addAttachment($attachmentId);
             }
         }
         if (CMA_Settings::getOption(CMA_Settings::OPTION_NEW_QUESTION_EVERYBODY_FOLLOW_ENABLED)) {
             $instance->makeEverybodyFollowers();
         }
         if ($status == 'draft') {
             $instance->notifyModerator();
         } else {
             self::updateQA($userId);
             $instance->notifyAboutNewQuestion();
         }
         if (CMA_Settings::getOption(CMA_Settings::OPTION_LOGS_ENABLED)) {
             CMA_QuestionPostLog::instance()->log($id);
         }
         do_action('cma_question_post_after', $instance, $data);
         return $instance;
     }
 }
 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'));
     }
 }
 protected static function _processFollow()
 {
     $result = array('success' => 0, 'message' => CMA::__('An error occurred.'));
     if (empty($_POST['nonce']) or !wp_verify_nonce($_POST['nonce'], 'cma_follow')) {
         $result['message'] = CMA::__('Invalid nonce.');
     } else {
         if (!empty(self::$query->post) and $thread = CMA_Thread::getInstance(self::$query->post->ID) and empty($_POST['categoryId'])) {
             $followersEngine = $thread->getFollowersEngine();
             if ($thread->canSubscribe()) {
                 if ($followersEngine->isFollower()) {
                     $followersEngine->removeFollower();
                     $result = array('success' => 1, 'message' => CMA_Labels::getLocalized('unfollow_success'), 'isFollower' => false);
                 } else {
                     $followersEngine->addFollower();
                     $result = array('success' => 1, 'message' => CMA_Labels::getLocalized('follow_success'), 'isFollower' => true);
                 }
             }
         } else {
             if (CMA_Settings::getOption(CMA_Settings::OPTION_ENABLE_CATEGORY_FOLLOWING) and !empty($_POST['categoryId']) and $category = CMA_Category::getInstance($_POST['categoryId'])) {
                 $followersEngine = $category->getFollowersEngine();
                 if (CMA_FollowersEngine::canBeFollower()) {
                     if ($followersEngine->isFollower()) {
                         $followersEngine->removeFollower();
                         $result = array('success' => 1, 'message' => CMA_Labels::getLocalized('unfollow_category_success'), 'isFollower' => false);
                     } else {
                         $followersEngine->addFollower();
                         $result = array('success' => 1, 'message' => CMA_Labels::getLocalized('follow_category_success'), 'isFollower' => true);
                     }
                 }
             }
         }
     }
     header('Content-type: application/json');
     echo json_encode($result);
     exit;
 }