public static function selectForQuestion(CMA_Thread $thread)
 {
     $ids = $thread->getPostMeta(CMA_Thread::$_meta['attachment'], false);
     if (!empty($ids)) {
         return parent::select($thread->getId(), $ids);
     } else {
         return array();
     }
 }
 public static function save_postdata($post_id)
 {
     $postType = isset($_POST['post_type']) ? $_POST['post_type'] : '';
     if ('cma_thread' != $postType) {
         return;
     }
     $answerThread = CMA_Thread::getInstance($post_id);
     if (empty($answerThread)) {
         return;
     }
     $sticky = 0;
     if (isset($_POST["cma_sticky_box"]) and isset($_POST["cma_sticky_box"])) {
         $sticky = 1;
     }
     update_post_meta($post_id, '_sticky_post', $sticky);
     /*
      * Update views count
      */
     $viewsAmount = isset($_POST['cma_views_box']) ? $_POST['cma_views_box'] : 0;
     $answerThread->setViews($viewsAmount);
     if (isset($_POST['cma_post_rating_box']) and is_numeric($_POST['cma_post_rating_box'])) {
         $answerThread->setRatingHandicap($_POST['cma_post_rating_box']);
     }
     if (isset($_POST['cma_post_votes_handicap_box']) and is_numeric($_POST['cma_post_votes_handicap_box'])) {
         $answerThread->setVotesHandicap($_POST['cma_post_votes_handicap_box']);
     }
 }
Пример #3
0
 public static function init($pluginFilePath)
 {
     register_activation_hook($pluginFilePath, array(__CLASS__, 'install'));
     register_uninstall_hook($pluginFilePath, array(__CLASS__, 'uninstall'));
     add_action('init', array('CMA_Update', 'run'), 0);
     add_action('widgets_init', array('CMA_AnswerController', 'registerSidebars'));
     // Check licensing API before controller init
     $licensingApi = new CMA_Cminds_Licensing_API('CM Answers Pro', CMA_Thread::ADMIN_MENU, 'CM Answers Pro', CMA_PLUGIN_FILE, array('release-notes' => 'http://answers.cminds.com/release-notes/'), '', array('CM Answers Pro'));
     self::$isLicenseOk = $licensingApi->isLicenseOk();
     CMA_Labels::bootstrap();
     CMA_Thread::init();
     add_action('plugins_loaded', array('CMA_BuddyPress', 'bootstrap'));
     add_action('init', array('CMA_BaseController', 'bootstrap'));
     add_action('wp_enqueue_scripts', array(__CLASS__, 'enable_scripts'));
     add_action('admin_enqueue_scripts', array(__CLASS__, 'enable_admin_scripts'));
     add_action('wp_head', array(__CLASS__, 'add_base_url'));
     add_filter('bp_blogs_record_comment_post_types', array(get_class(), 'bp_record_my_custom_post_type_comments'));
     add_filter('plugin_action_links_' . CMA_PLUGINNAME, array(__CLASS__, 'cma_settings_link'));
     add_filter('cm_micropayments_integrations', function ($a = array()) {
         if (!is_array($a)) {
             $a = array();
         }
         $a[] = 'CM Answers Pro';
         return $a;
     });
     add_action('plugins_loaded', array(__CLASS__, 'cm_lang_init'));
 }
 static function addHeader()
 {
     if (!CMA_Thread::canPostQuestions()) {
         self::addMessage(self::MESSAGE_ERROR, 'You cannot post questions.');
         wp_redirect(CMA::getReferer());
     }
     self::loadScripts();
 }
 protected static function optoutThread($threadId)
 {
     $token = self::_getParam('token');
     if ($thread = CMA_Thread::getInstance($threadId) and CMA_ThreadNewsletter::getOptOutToken($thread) == $token) {
         $thread->getFollowersEngine()->removeFollower();
         self::$contentMessage = CMA_Labels::getLocalized('unfollow_success');
     } else {
         self::$contentMessage = 'An error occurred.';
     }
 }
 static function shortcode($atts = array())
 {
     $atts = shortcode_atts(array('title' => 0, 'backlink' => 1, 'cat' => null), $atts);
     CMA_BaseController::loadScripts();
     if (CMA_Thread::canPostQuestions()) {
         $post = $thread = null;
         $catId = $atts['cat'];
         $redirectAfterPost = '_thread';
         $displayOptions = array('hideTitle' => empty($atts['title']), 'showBacklink' => !empty($atts['backlink']));
         return CMA_BaseController::_loadView('answer/widget/question-form', compact('post', 'thread', 'catId', 'displayOptions', 'redirectAfterPost'));
     }
 }
 static function save_post($postId)
 {
     if ($thread = CMA_Thread::getInstance($postId) and self::save_post_verify_nonce()) {
         $related = array();
         if (!empty($_POST['cma_related_questions'])) {
             $related = $_POST['cma_related_questions'];
         }
         if (!empty($_POST['cma_related_questions_add'])) {
             $related = array_merge($related, self::getIdsFromRaw($_POST['cma_related_questions_add']));
         }
         $thread->setUserRelatedQuestions($related);
     }
 }
 protected function getRelatedQuestions($limit, $matchCategory, $matchTags)
 {
     $wp_query = CMA_AnswerController::$query;
     if (empty($this->questions) and $wp_query->get('post_type') == CMA_Thread::POST_TYPE and $wp_query->is_single()) {
         $post = $wp_query->get_posts();
         $post = reset($post);
         if (!empty($post) and $post->post_type == CMA_Thread::POST_TYPE) {
             $thread = CMA_Thread::getInstance($post->ID);
             $questions = $thread->getRelated($limit, $matchCategory, $matchTags);
             $this->questions = array_map(array('CMA_Thread', 'getInstance'), $questions);
         }
     }
     return $this->questions;
 }
 protected static function _processCommentAdd()
 {
     $wp_query = self::$query;
     $response = array('success' => 0, 'msg' => CMA::__('An error occured.'));
     $post = $wp_query->post;
     $thread = CMA_Thread::getInstance($post->ID);
     $content = self::_getParam('content');
     $answerId = self::_getParam('cma-answer-id');
     if (empty($_POST['nonce']) or !wp_verify_nonce($_POST['nonce'], 'cma_comment')) {
         $error = CMA::__('Invalid nonce.');
     } else {
         if (!CMA_Comment::canCreate()) {
             $error = CMA::__('You have to be logged-in.');
         } else {
             if (empty($content)) {
                 $error = CMA::__('Content cannot be empty.');
             } else {
                 if ($answerId) {
                     $answer = CMA_Answer::getById($answerId);
                     if (empty($answer)) {
                         $error = CMA::__('Unknown answer.');
                     }
                 }
             }
         }
     }
     header('content-type: application/json');
     if (empty($error)) {
         try {
             $comment = CMA_Comment::create($content, CMA::getPostingUserId(), $thread->getId(), $answerId);
             if (!$comment) {
                 throw new Exception(CMA::__('Failed to add comment.'));
             }
             if ($comment->isApproved()) {
                 $thread->setUpdated();
             }
             $msg = $comment->isApproved() ? CMA::__('Comment has been added.') : CMA::__('Thank you for your comment, it has been held for moderation.');
             $html = $comment->isApproved() ? self::_loadView('answer/comments/comment-single', compact('comment')) : null;
             $response = array('success' => 1, 'msg' => $msg, 'html' => $html);
         } catch (Exception $e) {
             $error = $e->getMessage();
         }
     }
     if (!empty($error)) {
         $response['msg'] = $error;
     }
     echo json_encode(apply_filters('cma_comment_add_ajax_response', $response));
     exit;
 }
 public static function indexAction()
 {
     $userId = self::getContributorAndId();
     $user = $userId['user'];
     $id = $userId['id'];
     $socialLinks = array();
     $providers = array('google', 'linkedin', 'facebook');
     foreach ($providers as $provider) {
         $link = get_user_meta($id, '_cma_social_' . $provider . '_url', true);
         if (!empty($link)) {
             $socialLinks[$provider] = $link;
         }
     }
     return array('name' => $user->display_name, 'user_id' => $id, 'link' => get_user_meta($id, '_cma_social_url', true), 'socialLinks' => $socialLinks, 'questions' => CMA_Thread::getQuestionsByUser($id, -1, $onlyVisible = true), 'answers' => CMA_Answer::getByUser($id, $approved = true, $limit = -1, $page = 1, $onlyVisible = true));
 }
Пример #11
0
 protected function importQuestion(array $question)
 {
     global $wpdb;
     $question['post_status'] = 'publish';
     $question['post_type'] = 'cma_thread';
     $question['post_author'] = $wpdb->get_var("SELECT user_id FROM {$wpdb->usermeta}\n\t\t\tWHERE meta_key = 'cma_import_old_id' AND meta_value = " . $question['import_old_author_id']);
     if (empty($question['post_author'])) {
         throw new Exception(sprintf('Failed to import question with old ID %d. Unknown user with old ID %d.', $question['import_old_id'], $question['import_old_author_id']));
     }
     $id = wp_insert_post($question, true);
     if ($id and is_numeric($id)) {
         update_post_meta($id, 'cma_import_old_id', $question['import_old_id']);
         $instance = CMA_Thread::getInstance($id);
         $instance->savePostMeta(array(CMA_Thread::$_meta['votes_answers'] => 0));
         $instance->savePostMeta(array(CMA_Thread::$_meta['votes_question'] => 0));
         $instance->savePostMeta(array(CMA_Thread::$_meta['votes_question_answers'] => 0));
         $instance->savePostMeta(array(CMA_Thread::$_meta['highestRatedAnswer'] => 0));
         $instance->savePostMeta(array(CMA_Thread::$_meta['stickyPost'] => 0));
         // 			$votes = $this->getQuestionVotes($instance->getId());
         return $instance;
     } else {
         throw new Exception('Error: ' . json_encode($id));
     }
 }
 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;
 }
 static function getOptOutToken(CMA_Thread $thread)
 {
     return sha1(implode('|', array(NONCE_SALT, $thread->getId(), NONCE_KEY)));
 }
Пример #14
0
 /**
  * Get the thread's permalink.
  * 
  * @param array $query Query args.
  * @param string $append Append a string to the URL path.
  * @return string
  */
 public function getPermalink(array $query = array(), $backlink = false, $append = '')
 {
     $result = get_permalink($this->getId());
     if (strlen($append) > 0) {
         $result .= $append;
     }
     $query = CMA_Thread::sanitize_array($query, array('ajax' => array('int', null), 'post_id' => array('int', null), 'sort' => array('string', null), CMA_AnswerController::PARAM_EDIT_ANSWER_ID => array('int', null), CMA_AnswerController::PARAM_EDIT_QUESTION_ID => array('int', null), CMA_AnswerController::PARAM_RESOLVE_QUESTION_ID => array('int', null)));
     if ($backlink === true and CMA_Settings::getOption(CMA_Settings::OPTION_BACKLINK_PARAM_ENABLED)) {
         $query['backlink'] = base64_encode($_SERVER['REQUEST_URI']);
     }
     $query = array_filter($query);
     if (!empty($query)) {
         $result = add_query_arg(urlencode_deep($query), $result);
     }
     return $result;
 }
 public static function notifyAllUsers()
 {
     global $wpdb;
     if (!empty($_GET['nonce']) and wp_verify_nonce($_GET['nonce'], CMA_BaseController::ADMIN_BP_NOTIFY)) {
         $usersIds = $wpdb->get_col("SELECT ID FROM {$wpdb->users}");
         if (!empty($_GET['post_id']) and $thread = CMA_Thread::getInstance($_GET['post_id'])) {
             $notification = array('item_id' => $thread->getId(), 'secondary_item_id' => 0, 'component_name' => 'cma_notifier', 'component_action' => self::ACTION_NOTIFICATION_THREAD, 'date_notified' => bp_core_current_time(), 'is_new' => 1, 'allow_duplicate' => true);
             foreach ($usersIds as $userId) {
                 if ($thread->isVisible($userId)) {
                     $notification['user_id'] = $userId;
                     bp_notifications_add_notification($notification);
                 }
             }
         }
         if (!empty($_GET['comment_id']) and $answer = CMA_Answer::getById($_GET['comment_id'])) {
             $notification = array('item_id' => $answer->getId(), 'secondary_item_id' => 0, 'component_name' => 'cma_notifier', 'component_action' => self::ACTION_NOTIFICATION_ANSWER, 'date_notified' => bp_core_current_time(), 'is_new' => 1, 'allow_duplicate' => true);
             foreach ($usersIds as $userId) {
                 if ($answer->isVisible($userId)) {
                     $notification['user_id'] = $userId;
                     bp_notifications_add_notification($notification);
                 }
             }
         }
     }
     wp_safe_redirect(CMA::getReferer());
     exit;
 }
Пример #16
0
 protected function _vote($positive)
 {
     $current = $this->getRating();
     $point = $positive ? 1 : -1;
     $userVotingId = CMA_Thread::getUserVotingId();
     $metaId = add_comment_meta($this->getId(), $positive ? self::META_USER_RATING_POSITIVE : self::META_USER_RATING_NEGATIVE, $userVotingId, $unique = false);
     if ($metaId) {
         add_post_meta($this->getId(), self::META_VOTE_IP . '_' . $metaId, $_SERVER['REMOTE_ADDR']);
         add_post_meta($this->getId(), self::META_VOTE_UA . '_' . $metaId, $_SERVER['HTTP_USER_AGENT']);
         add_post_meta($this->getId(), self::META_VOTE_TIME . '_' . $metaId, time());
         if (!empty($_COOKIE[CMA_Thread::COOKIE_ANONYMOUS_UID])) {
             add_post_meta($this->getId(), self::META_VOTE_COOKIE . '_' . $metaId, $_COOKIE[CMA_Thread::COOKIE_ANONYMOUS_UID]);
         }
         $this->updateRatingCache();
         if (CMA_Settings::getOption(CMA_Settings::OPTION_LOGS_ENABLED)) {
             CMA_AnswerVoteLog::instance()->log($this->getId(), $point);
         }
     } else {
         $point = 0;
     }
     return $current + $point;
 }
 protected function importQuestion(array $question)
 {
     global $wpdb;
     $thread = false;
     $existing = $wpdb->get_var("SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'cma_import_old_id' AND meta_value = " . $question['import_old_id']);
     if ($existing) {
         $this->showWarning(sprintf('Question with old ID %d already imported.', $question['import_old_id']));
         $id = $existing;
         $thread = CMA_Thread::getInstance($id);
     } else {
         try {
             if ($thread = parent::importQuestion($question) and $thread instanceof CMA_Thread) {
                 $thread->setResolved($question['state_type'] == 'closed');
                 if (!empty($question["tagnames"])) {
                     $this->showSuccess(sprintf('Question with old ID %d imported.', $question['import_old_id']));
                     wp_set_post_tags($thread->getId(), str_replace(" ", ',', $question["tagnames"]), true);
                     $this->importedQuestions++;
                 }
             } else {
                 $this->showError(sprintf('Failed to import question with old ID %d', $question['import_old_id']));
             }
         } catch (Exception $e) {
             $this->showError($e);
         }
     }
     return $thread;
 }
Пример #18
0
 public function getLastActivity()
 {
     global $wpdb;
     if (CMA_Category::isAnyCategoryResticted()) {
         $accessFilter = ' AND (ID IN (' . CMA_Thread::getCategoryAccessFilterSubquery() . ')
 					OR ID NOT IN (' . CMA_Thread::getCategorizedThreadIdsSubquery() . ')
 					OR post_author = ' . intval(get_current_user_id()) . '
 				)';
     } else {
         $accessFilter = '';
     }
     return $wpdb->get_var($wpdb->prepare("SELECT MAX(p.post_modified) AS pm\n\t\t\tFROM {$wpdb->posts} p\n\t\t\tJOIN {$wpdb->term_relationships} tr ON tr.object_id = p.ID\n\t\t\tJOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.taxonomy = %s\n\t\t\tWHERE p.post_type = %s\n\t\t\tAND p.post_status = 'publish'\n\t\t\tAND tt.term_id = %d\n\t\t\t" . $accessFilter, CMA_Category::TAXONOMY, CMA_Thread::POST_TYPE, $this->getId()));
 }
 /**
  * Action then the thread has been resolved.
  * 
  * @param CMA_Thread $thread
  */
 public function threadResolved(CMA_Thread $thread)
 {
     if (CMA_Settings::getOption(CMA_Settings::OPTION_MP_REWARD_BEST_ANSWER_ENABLE)) {
         if ($points = CMA_Settings::getOption(CMA_Settings::OPTION_MP_REWARD_BEST_ANSWER_POINTS)) {
             if ($thread->isResolved() and $bestAnswer = CMA_Answer::getById($thread->getBestAnswerId())) {
                 if ($userId = $bestAnswer->getAuthorId() and $user = get_userdata($userId)) {
                     if ($this->chargeUserWallet($userId, $points)) {
                         add_filter('cma_question_resolved_msg_success', array($this, 'questionResolvedMessageSuccess'));
                         add_filter('cma_question_mark_best_answer_msg_success', array($this, 'questionResolvedMessageSuccess'));
                     }
                 }
             }
         }
     }
 }
 static function bestAnswerNotification(CMA_Thread $thread)
 {
     global $wpdb;
     $answer = $thread->getBestAnswer();
     $receivers = array();
     $receiversOption = CMA_Settings::getOption(CMA_Settings::OPTION_NOTIF_BEST_ANSWER_RECEIVERS);
     if (in_array(CMA_Settings::NOTIF_QUESTION_AUTHOR, $receiversOption)) {
         $receivers[] = $thread->getAuthorEmail();
     }
     if (in_array(CMA_Settings::NOTIF_ANSWER_AUTHOR, $receiversOption)) {
         $receivers[] = $answer->getAuthorEmail();
     }
     if (in_array(CMA_Settings::NOTIF_FOLLOWERS, $receiversOption)) {
         $receivers = array_merge($receivers, $thread->getFollowersEmails());
     }
     if (in_array(CMA_Settings::NOTIF_CONTRIBUTORS, $receiversOption)) {
         $receivers = array_merge($receivers, $thread->getContributorsEmails());
         $receivers[] = $thread->getAuthorEmail();
     }
     $receivers = array_filter(array_unique($receivers));
     if (!empty($receivers)) {
         $message = CMA_Settings::getOption(CMA_Settings::OPTION_NOTIF_BEST_ANSWER_CONTENT);
         $title = CMA_Settings::getOption(CMA_Settings::OPTION_NOTIF_BEST_ANSWER_TITLE);
         $replace = array('[blogname]' => get_bloginfo('name'), '[question_title]' => strip_tags($thread->getTitle()), '[question_body]' => strip_tags($thread->getContent()), '[question_author]' => strip_tags($thread->getAuthorName()), '[answer]' => strip_tags($answer->getContent()), '[answer_link]' => $answer->getPermalink(), '[answer_author]' => strip_tags($answer->getAuthorName()));
         CMA_Email::send($receivers, $title, $message, $replace);
     }
 }
Пример #21
0
 public static function update_2_4_13()
 {
     global $wpdb;
     // Comment rating
     $commentsIds = array();
     if (CMA_Settings::getOption(CMA_Settings::OPTION_NEGATIVE_RATING_ALLOWED)) {
         // Copy comments' ratings to the rating handicap fields.
         $ratings = $wpdb->get_results($wpdb->prepare("SELECT m.comment_id, m.meta_value, c.comment_post_ID\n\t\t\t\tFROM {$wpdb->commentmeta} m\n\t\t\t\tINNER JOIN {$wpdb->comments} c ON m.comment_id = c.comment_ID\n\t\t\t\tWHERE m.meta_key = %s", CMA_Thread::$_meta['rating']), ARRAY_A);
         foreach ($ratings as $record) {
             add_comment_meta($record['comment_id'], CMA_Answer::META_USER_RATING_HANDICAP, $record['meta_value'], $unique = true);
             $commentsIds[$record['comment_id']] = $record['comment_id'];
         }
     } else {
         // Only positive ratings - move voters to the positive voters meta
         $voters = $wpdb->get_results($wpdb->prepare("SELECT m.comment_id, m.meta_value, c.comment_post_ID\n\t\t\t\tFROM {$wpdb->commentmeta} m\n\t\t\t\tINNER JOIN {$wpdb->comments} c ON m.comment_id = c.comment_ID\n\t\t\t\tWHERE m.meta_key = %s", CMA_Answer::META_USERS_RATED), ARRAY_A);
         foreach ($voters as $record) {
             $commentRatingPositive = get_comment_meta($record['comment_id'], CMA_Answer::META_USER_RATING_POSITIVE, $single = false);
             if (!in_array($record['meta_value'], $commentRatingPositive)) {
                 add_comment_meta($record['comment_id'], CMA_Answer::META_USER_RATING_POSITIVE, $record['meta_value'], $unique = false);
             }
             $commentsIds[$record['comment_id']] = $record['comment_id'];
         }
     }
     // ----------------------------------------------------
     // Post rating
     $postsIds = array();
     if (CMA_Settings::getOption(CMA_Settings::OPTION_NEGATIVE_RATING_ALLOWED)) {
         // Copy posts' ratings to the rating handicap fields.
         $ratings = $wpdb->get_results($wpdb->prepare("SELECT post_id, meta_value FROM {$wpdb->postmeta}\n\t\t\t\tWHERE meta_key = %s", CMA_Thread::$_meta['rating']), ARRAY_A);
         foreach ($ratings as $record) {
             add_post_meta($record['post_id'], CMA_Thread::$_meta['userRatingHandicap'], $record['meta_value'], $unique = true);
             $postsIds[$record['post_id']] = $record['post_id'];
         }
     } else {
         // Only positive ratings - copy voters to the positive voters meta
         $voters = $wpdb->get_results($wpdb->prepare("SELECT post_id, meta_value FROM {$wpdb->postmeta}\n\t\t\t\tWHERE meta_key = %s", CMA_Thread::$_meta['usersRated']), ARRAY_A);
         foreach ($voters as $record) {
             $postRatingPositive = get_post_meta($record['post_id'], CMA_Thread::$_meta['userRatingPositive'], $single = false);
             if (!in_array($record['meta_value'], $postRatingPositive)) {
                 add_post_meta($record['post_id'], CMA_Thread::$_meta['userRatingPositive'], $record['meta_value'], $unique = false);
             }
             $postsIds[$record['post_id']] = $record['post_id'];
         }
     }
     // ----------------------------------------------------
     // Update comments counter cache
     foreach ($commentsIds as $commentId) {
         if ($answer = CMA_Answer::getById($commentId)) {
             $answer->updateRatingCache();
         }
     }
     // Update posts counter cache
     foreach ($postsIds as $postId) {
         if ($thread = CMA_Thread::getInstance($postId)) {
             $thread->updateRatingCache();
         }
     }
 }
 static function threadSaveAfter(CMA_Thread $instance, $data = null)
 {
     if ($category = $instance->getCategory() and !empty($_POST[self::FIELD_CUSTOM_FIELDS])) {
         $instance->setCategoryCustomFields($_POST[self::FIELD_CUSTOM_FIELDS]);
     }
 }
Пример #23
0
 public function getThread()
 {
     return CMA_Thread::getInstance($this->getThreadId());
 }
 public static function processSettings()
 {
     if (empty($_POST)) {
         return;
     }
     // CSRF protection
     if (!empty($_POST) and (empty($_POST['nonce']) or !wp_verify_nonce($_POST['nonce'], self::ADMIN_SETTINGS))) {
         die('Invalid nonce');
     }
     CMA_Settings::processPostRequest();
     CMA_Thread::setDisclaimerEnabled(isset($_POST['disclaimer_approve']) && $_POST['disclaimer_approve'] == 1);
     CMA_Thread::setDisclaimerContent(stripslashes($_POST['disclaimer_content']));
     CMA_Thread::setDisclaimerContentAccept(stripslashes($_POST['disclaimer_content_accept']));
     CMA_Thread::setDisclaimerContentReject(stripslashes($_POST['disclaimer_content_reject']));
     CMA_Thread::setSidebarSettings('before_widget', stripslashes($_POST['sidebar_before_widget']));
     CMA_Thread::setSidebarSettings('after_widget', stripslashes($_POST['sidebar_after_widget']));
     CMA_Thread::setSidebarSettings('before_title', stripslashes($_POST['sidebar_before_title']));
     CMA_Thread::setSidebarSettings('after_title', stripslashes($_POST['sidebar_after_title']));
     CMA_Thread::setSidebarEnabled(isset($_POST['sidebar_enable']) && $_POST['sidebar_enable'] == 1);
     CMA_Thread::setSidebarMaxWidth((int) $_POST['sidebar_max_width']);
     CMA_Thread::setSidebarContributorEnabled(isset($_POST['sidebar_contributor_enable']) ? $_POST['sidebar_contributor_enable'] : '1');
     // Social login
     if (isset($_POST['fb_app_id']) && isset($_POST['fb_app_secret'])) {
         update_option('_cma_fb_app_id', trim($_POST['fb_app_id']));
         update_option('_cma_fb_app_secret', trim($_POST['fb_app_secret']));
     }
     if (isset($_POST['google_client_id']) && isset($_POST['google_client_secret'])) {
         update_option('_cma_google_client_id', trim($_POST['google_client_id']));
         update_option('_cma_google_client_secret', trim($_POST['google_client_secret']));
     }
     if (isset($_POST['linkedin_api_key']) && isset($_POST['linkedin_secret_key'])) {
         update_option('_cma_linkedin_api_key', trim($_POST['linkedin_api_key']));
         update_option('_cma_linkedin_secret_key', trim($_POST['linkedin_secret_key']));
     }
     if (isset($_POST['twitter_consumer_key']) && isset($_POST['twitter_consumer_secret'])) {
         update_option('_cma_twitter_consumer_key', trim($_POST['twitter_consumer_key']));
         update_option('_cma_twitter_consumer_secret', trim($_POST['twitter_consumer_secret']));
     }
     if (isset($_POST['live_client_id']) && isset($_POST['live_client_secret'])) {
         update_option('_cma_live_client_id', trim($_POST['live_client_id']));
         update_option('_cma_live_client_secret', trim($_POST['live_client_secret']));
     }
     // Labels
     $labels = CMA_Labels::getLabels();
     foreach ($labels as $labelKey => $label) {
         if (isset($_POST['label_' . $labelKey])) {
             CMA_Labels::setLabel($labelKey, stripslashes($_POST['label_' . $labelKey]));
         }
     }
     CMA_Thread::setSpamFilter(isset($_POST['spamFilter']) && $_POST['spamFilter'] == 1);
     CMA_Thread::setReferralEnabled(isset($_POST['referral_enable']) && $_POST['referral_enable'] == 1);
     if (!empty($_POST['affiliate_code'])) {
         CMA_Thread::setAffiliateCode(stripslashes($_POST['affiliate_code']));
     }
     if (isset($_POST['custom_css'])) {
         CMA_Thread::setCustomCss(stripslashes($_POST['custom_css']));
     }
     // Clear the permalinks
     flush_rewrite_rules(true);
     delete_option('rewrite_rules');
     wp_redirect($_SERVER['REQUEST_URI']);
     exit;
 }