/** * The function for processing a message to see if it might be SPAM * returns: * 0 if the message is SPAM * 1 if the message might be SPAM (it will be marked for moderation) * 2 if the message is not SPAM * * @param string $author Author field from the posting * @param string $email Email field from the posting * @param string $website Website field from the posting * @param string $body The text of the comment * @param string $imageLink A link to the album/image on which the post was made * @param string $ip the IP address of the comment poster * * @return int */ function filterMessage($author, $email, $website, $body, $imageLink, $ip) { $commentData = array('author' => $author, 'email' => $email, 'website' => $website, 'body' => $body, 'permalink' => $imageLink); $zp_galUrl = FULLWEBPATH; // Sets the webpath for the Akismet server $zp_akismetKey = getOption('Akismet_key'); $forgive = getOption('Forgiving'); $die = 2; // good comment until proven bad $akismet = new Akismet($zp_galUrl, $zp_akismetKey, $commentData); if ($akismet->errorsExist()) { // TODO: Add more improved error handling (maybe) // echo "Couldn't connected to Akismet server!"; // print_r ($akismet->getErrors()); $die = 1; // mark for moderation if we can't check for Spam } else { if ($akismet->isSpam()) { // Message is spam according to Akismet // echo 'Spam detected'; // echo "bad message."; $die = $forgive; } else { // Message is not spam according to Akismet // echo "spam filter is true. good message."; } } return $die; }
/** * validate the elements data against the rule * @param string data to check * @param object element model * @param int plugin sequence ref * @return bol true if validation passes, false if fails */ function validate($data, &$elementModel, $c) { $params = $this->getParams(); $user = JFactory::getUser(); if ($params->get('akismet-key') != '') { $username = $user->get('username') != '' ? $user->get('username') : $this->_randomSring(); $email = $user->get('email') != '' ? $user->get('email') : $this->_randomSring().'@'.$this->_randomSring().'com'; require_once(JPATH_COMPONENT.DS.'plugins'.DS.'validationrule'.DS.'akismet'.DS.'akismet.class.php'); $akismet_comment = array ( 'author' => $username, 'email' => $user->get('email'), 'website' => JURI::base(), 'body' => $data ); $akismet = new Akismet(JURI::base(), $params->get('akismet-key'), $akismet_comment); if ($akismet->errorsExist()) { JError::raiseNotice( JText::_("Couldn't connected to Akismet server!")); } else { if ($akismet->isSpam()) { return false; } } } return true; }
/** * Validate the elements data against the rule * * @param string $data To check * @param int $repeatCounter Repeat group counter * * @return bool true if validation passes, false if fails */ public function validate($data, $repeatCounter) { $params = $this->getParams(); if ($params->get('akismet-key') != '') { $username = $this->user->get('username') != '' ? $this->user->get('username') : $this->_randomSring(); require_once JPATH_COMPONENT . '/plugins/validationrule/akismet/libs/akismet.class.php'; $akismet_comment = array('author' => $username, 'email' => $this->user->get('email'), 'website' => JURI::base(), 'body' => $data); $akismet = new Akismet(JURI::base(), $params->get('akismet-key'), $akismet_comment); if ($akismet->errorsExist()) { throw new RuntimeException("Couldn't connected to Akismet server!"); } else { if ($akismet->isSpam()) { return false; } } } return true; }
function onSubmit($vals) { $ak = appconf('akismet_key'); if ($ak) { loader_import('siteblog.Akismet'); $comment = array('author' => $vals['name'], 'email' => $vals['email'], 'website' => $vals['url'], 'body' => $vals['body'], 'permalink' => site_url() . '/index/siteblog-post-action/id.' . $vals['post'] . '/title.' . siteblog_filter_link_title($title), 'user_ip' => $_SERVER['REMOTE_ADDR'], 'user_agent' => $_SERVER['HTTP_USER_AGENT']); $akismet = new Akismet(site_url(), $ak, $comment); if (!$akismet->errorsExist()) { // no errors if ($akismet->isSpam()) { // akismet says spam $title = db_shift('select subject from siteblog_post where id = ?', $vals['post']); db_execute('insert into siteblog_akismet values (null, ?, now(), ?, ?, ?, ?, ?, ?)', $vals['post'], $comment['author'], $comment['email'], $comment['website'], $comment['user_ip'], $comment['user_agent'], $comment['body']); header('Location: ' . site_prefix() . '/index/siteblog-post-action/id.' . $vals['post'] . '/title.' . siteblog_filter_link_title($title)); exit; } } } if (!empty($vals['post'])) { $res = db_execute('insert into siteblog_comment (id, child_of_post, body, date, author, email, url, ip) values (null, ?, ?, now(), ?, ?, ?, ?)', $vals['post'], $vals['body'], $vals['name'], $vals['email'], $vals['url'], $_SERVER['REMOTE_ADDR']); if (!$res) { die(db_error()); } $id = db_lastid(); } else { $res = db_execute('update siteblog_comment set body = ?, author = ?, email = ?, url = ? where id = ?', $vals['body'], $vals['name'], $vals['email'], $vals['url'], $vals['_key']); if (!$res) { die(db_error()); } $id = $vals['_key']; $vals['post'] = db_shift('select child_of_post from siteblog_comment where id = ?', $vals['_key']); } $title = db_shift('select subject from siteblog_post where id = ?', $vals['post']); header('Location: ' . site_prefix() . '/index/siteblog-post-action/id.' . $vals['post'] . '/title.' . siteblog_filter_link_title($title) . '#siteblog-comment-' . $id); exit; }
function akismet_check_submit(&$vars) { if (phpnum() >= 5) { include akismet_lib_path . 'Akismet.class_5.php'; $x = $x['linkres']; $user = new User(); $user->id = $x->author; $user->read(); $akismet = new Akismet(my_base_url . my_pligg_base, get_misc_data('wordpress_key')); $akismet->setCommentAuthor($user->username); $akismet->setCommentAuthorEmail($user->email); $akismet->setCommentAuthorURL($x->url); $akismet->setCommentContent($x->content); $akismet->setPermalink(getmyurl('story', $x->id)); if ($akismet->isCommentSpam()) { // store the comment but mark it as spam (in case of a mis-diagnosis) $spam_links = get_misc_data('spam_links'); if ($spam_links != '') { $spam_links = unserialize(get_misc_data('spam_links')); } else { $spam_links = array(); } $spam_links[] = $x->id; misc_data_update('spam_links', serialize($spam_links)); totals_adjust_count($x->status, -1); totals_adjust_count('discard', 1); $x->status = 'discard'; } else { // echo 'not spam'; } } else { include akismet_lib_path . 'Akismet.class_4.php'; $x = $vars['linkres']; $user = new User(); $user->id = $x->author; $user->read(); $story['author'] = $user->username; $story['email'] = $user->email; $story['website'] = $x->url; $story['body'] = $x->content; $story['permalink'] = getmyurl('story', $x->id); $story['user_ip'] = $user->extra_field['user_lastip']; $akismet = new Akismet(my_base_url . my_pligg_base, get_misc_data('wordpress_key'), $story); // test for errors if ($akismet->errorsExist()) { // returns true if any errors exist if ($akismet->isError('AKISMET_INVALID_KEY')) { // echo 'invalid key'; } elseif ($akismet->isError('AKISMET_RESPONSE_FAILED')) { // echo 'response failed'; } elseif ($akismet->isError('AKISMET_SERVER_NOT_FOUND')) { // echo 'server not found'; } } else { // No errors, check for spam if ($akismet->isSpam()) { // returns true if Akismet thinks the comment is spam $spam_links = get_misc_data('spam_links'); if ($spam_links != '') { $spam_links = unserialize(get_misc_data('spam_links')); } else { $spam_links = array(); } $spam_links[] = $x->id; misc_data_update('spam_links', serialize($spam_links)); } else { // echo 'not spam'; } } } }
$errors[] = 'formmail_error_text_too_long'; } if (mb_strlen($subject, CHARSET) > $settings['email_subject_maxlength']) { $errors[] = 'formmail_error_subj_too_long'; } if (empty($errors)) { // Akismet spam check: if ($settings['akismet_key'] != '' && $settings['akismet_mail_check'] == 1) { #require('./cms/modules/akismet/akismet.class.php'); $mail_parts = explode("@", $email); $check_mail['author'] = $mail_parts[0]; $check_mail['email'] = $email; $check_mail['body'] = $message; $akismet = new Akismet(BASE_URL, $settings['akismet_key'], $check_mail); // test for errors if ($akismet->errorsExist()) { if ($akismet->isError(AKISMET_INVALID_KEY)) { $errors[] = 'akismet_error_api_key'; } elseif ($akismet->isError(AKISMET_RESPONSE_FAILED)) { $errors[] = 'akismet_error_connection'; } elseif ($akismet->isError(AKISMET_SERVER_NOT_FOUND)) { $errors[] = 'akismet_error_connection'; } } else { // No errors, check for spam if ($akismet->isSpam()) { $errors[] = 'akismet_spam_suspicion'; } } } // End Akismet spam check:
function wassupAppend() { global $wpdb, $wpurl, $wassup_options; //removed unused globals $siteurl = get_bloginfo('siteurl'); $table_name = $wpdb->prefix . "wassup"; $table_tmp_name = $wpdb->prefix . "wassup_tmp"; $wassup_settings = get_option('wassup_settings'); $current_user = wp_get_current_user(); $logged_user = $current_user->user_login; $urlRequested = clean_url($_SERVER['REQUEST_URI']); if (empty($logged_user) && $wassup_setting->wassup_hack == "1") { $hackercheck = true; } else { $hackercheck = false; } if ((!is_admin() && stristr($urlRequested,"/wp-admin/") === FALSE) || $hackercheck) { //exclude valid wordpress admin page visits //#### Get the visitor's details from http header... if (isset($_SERVER["REMOTE_ADDR"])) { if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){ //in case of multiple forwarding list($IP) = explode(",",$_SERVER["HTTP_X_FORWARDED_FOR"]); $proxy = $_SERVER["REMOTE_ADDR"]; $hostname = @gethostbyaddr($IP); if (empty($hostname) || $hostname == "unknown") { $hostname = @gethostbyaddr($proxy); } if (empty($IP) || $IP == "unknown") { $IP = $proxy; $ipAddress = $_SERVER["REMOTE_ADDR"]; } else { $ipAddress = $proxy.",".$IP; } }else{ list($IP) = explode(",",$_SERVER["REMOTE_ADDR"]); $hostname = @gethostbyaddr($IP); $ipAddress = $_SERVER["REMOTE_ADDR"]; } } if (empty($IP)) { $IP = $ipAddress; } if (empty($hostname)) { $hostname = "unknown"; } // Get the visitor's resolution, TODO /* if(isset($HTTP_COOKIE_VARS["users_resolution"])) { $screen_res = $HTTP_COOKIE_VARS["users_resolution"]; } else { //means cookie is not found set it using Javascript ?> <script language="javascript"> <!-- writeCookie(); function writeCookie() { var today = new Date(); var the_date = new Date("December 31, 2023"); var the_cookie_date = the_date.toGMTString(); var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height; var the_cookie = the_cookie + ";expires=" + the_cookie_date; document.cookie=the_cookie location = '<?php echo $_SERVER['REQUEST_URI']; ?>'; } //--> </script> <?php $screen_res = $HTTP_COOKIE_VARS["users_resolution"]; } */ $referrer = (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : ''); $userAgent = (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''); $language = (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? attribute_escape($_SERVER['HTTP_ACCEPT_LANGUAGE']) : ''); //$current_user = wp_get_current_user(); //moved up //$logged_user = $current_user->user_login; //moved up $comment_user = (isset($_COOKIE['comment_author_'.COOKIEHASH]) ? utf8_encode($_COOKIE['comment_author_'.COOKIEHASH]) : ''); $timestamp = wassup_get_time(); //Add a timestamp to visit... $flag_exclude_url = 0; //#####Start recording visit.... //## wassup is activated and IP not on exclusion list... if ($wassup_options->wassup_active == 1) { //(moved) if (empty($wassup_options->wassup_exclude) || strstr($wassup_options->wassup_exclude,$ipAddress) == FALSE) { //## check if url requested is not on exclusion list... if (!empty($wassup_options->wassup_exclude_url)) { $exclude_url_list = explode(",", $wassup_options->wassup_exclude_url); foreach ($exclude_url_list as $exclude_url) { if (stristr($urlRequested, trim($exclude_url)) !== FALSE) { $flag_exclude_url = 1; } } } if ($flag_exclude_url != 1) { //### Exclude requests for themes, plugins, and favicon from recordings if (stristr($urlRequested,"favicon.ico") === FALSE) { //moved if (stristr($urlRequested,"/wp-content/plugins") === FALSE || stristr($urlRequested,"forum") !== FALSE || $hackercheck) { //moved and modified to allow forum requests if (stristr($urlRequested,"/wp-content/themes") === FALSE || stristr($urlRequested,"comment") !== FALSE) { //moved and modified to allow comment requests //# More recording exclusion controls if ($wassup_options->wassup_loggedin == 1 || !is_user_logged_in()) { if ($wassup_options->wassup_attack == 1 || stristr($userAgent,"libwww-perl") === FALSE ) { if (!is_404() || $hackercheck) { //don't record 404 pages... //##### Extract useful visit information from http header.. $browser = ""; $os = ""; list($browser,$os) = wGetBrowser($userAgent); //#=================================================== //###Start visitor tracking... //Work-around for cookie rejection: //# Create a temporary id for this visit from a combination of //# date/hour/min/ip/hostname/useragent/os/browser. //# It is not unique so that multiple visits from the same //# ip/userAgent within a 30 minute-period, can be tracked as //# such, even when session/cookies is disabled. //# An md5 encoded version of temp_id is saved as "wassup_id". $temp_id = sprintf("%-060.60s", date('YmdH').str_replace(array(' ','http://','www.','/','.','\'','"',"\\",'$','-','&','+','_',';',',','>','<',':','#','*','%','!','@',')','(',), '', intval(date('i')/30).$IP.strrev($logged_user).strrev($userAgent).strrev($hostname).intval(date('i')/30)).date('HdmY').$hostname.rand()); $wassup_id = ""; //Read the cookie for wassup_id if (isset($_COOKIE['wassup'])) { $wassup_cookie = explode('::',$_COOKIE['wassup']); $wassup_id = $wassup_cookie[0]; } /* $session_timeout = 1; //### Check if this is an ongoing visit or a new hit... //#visitor tracking with "session"... //# Set savepath directory before session_start() $sessionpath = $wassup_options->wassup_savepath; if (empty($sessionpath)) { $sessionpath = getSessionpath(); } if ($sessionpath != "" && $wassup_options->isWritableFolder($sessionpath)) { session_save_path($sessionpath); } session_start(); //required to use/update $_SESSION //#confirm that session is started... if (isset($_SESSION)) { // Prevent Session Fixation attack (http://shiflett.org/articles/session-fixation) if (!isset($_SESSION['initiated'])) { session_regenerate_id(); $_SESSION['initiated'] = true; } //Get session variables... if (isset($_SESSION['wassup_id'])) { $wassup_id = $_SESSION['wassup_id']; $session_timeout = ((int)$_SESSION['wassup_timer'] - (int)time()); if (isset($_SESSION['spamresult'])) { $spamresult = $_SESSION['spamresult']; } if ( $_SESSION['urlrequest'] == $urlRequested && (($timestamp - (int)$_SESSION['visittime']) < 5)) { $dup_urlrequest=1; } } //#reset wassup_id for new visitors or when timer is 0... if (empty($wassup_id) or $session_timeout < 1) { //# don't "destroy" old session in case it is //# in use elsewhere in wordpress ??.. //if (!empty($wassup_id)) { // session_destroy(); // session_start(); //} $_SESSION['wassup_id'] = md5($temp_id); //$_SESSION['wassup_id'] = md5(uniqid(rand(), true)); //#timeout session after 24 minutes $_SESSION['wassup_timer'] = ((int)time() + 1440); $dup_urlrequest=0; } $wassup_id = $_SESSION['wassup_id']; if ($dup_urlrequest == 0) { //for dup checks $_SESSION['visittime'] = $timestamp; //for dup checks $_SESSION['urlrequest'] = $urlRequested; } //#SID is empty when session uses cookies... //if (defined('SID') && !empty(SID)) { // //#manually add SID to url_rewriter when trans-sid // //# is disabled (how to test for this???)... // output_add_rewrite_var(session_name(), htmlspecialchars(session_id())); //} @session_write_close(); } */ //### Check if this is an ongoing visit or a new hit... /* //#visitor tracking with "cookie"... if (isset($_COOKIE['wassup'])) { $wassup_cookie = unserialize($_COOKIE['wassup']); //$wassup_id = $wassup_cookie['wassup_id']; $wassup_timer = $wassup_cookie['timer']; if (isset($wassup_cookie['spamresult'])) { $spamresult = $wassup_cookie['spamresult']; } $session_timeout = ((int)$wassup_timer - (int)time()); if ( $session_timeout < 1) { //#reset cookie values when timer is 0 unset($wassup_cookie); $wassup_id = ""; //a new id will be assigned } } */ //Work-around for cookie rejection: //#assign new wassup id from "temp_id" and include it in dup check if (empty($wassup_id)) { $wassup_id = md5($temp_id); //$wassup_id = $temp_id; //debug } //### Check for duplicates. $dup_urlrequest=0; // Dup: Hit recorded, ==wassup_id, last visit, <90 secs old, ==URL $dups = $wpdb->get_results("SELECT wassup_id, urlrequested, spam, `timestamp` AS hit_timestamp FROM ".$table_tmp_name." WHERE wassup_id='".$wassup_id."' AND `timestamp` >".($timestamp-90)." GROUP BY wassup_id ORDER BY hit_timestamp DESC"); if (!empty($dups)) { $i=0; foreach ($dups as $dup) { //check first record only if ($i == 0) { if ($dup->urlrequested == $urlRequested) { $dup_urlrequest=1; } //retrieve spam check results $spamresult = $dup->spam; } $i=$i+1; } } // //#End visitor tracking with cookie/session //#=================================================== //### Exclude duplicates... if ($dup_urlrequest == 0) { //##### Extract useful visit information from http header.. if (empty($browser) || strstr($browser,"N/A") || is_feed()) { list($spider,$feed) = wGetSpider($userAgent,$hostname,$browser); } //#I prefer to see os/browser info. for spiders/bots. //spider exclusion control //# Spider exclusion control moved to avoid unneeded tests if ($wassup_options->wassup_spider == 1 || $spider == '') { // //#get language/locale info from hostname or referrer data $language = wGetLocale($language,$hostname,$referrer); //# get search string details from referrer data list($searchengine,$search_phrase)=explode("|",wGetSE($referrer)); $se=seReferer($referrer); if ($search_phrase != '') { if (stristr($searchengine,"images")) { // ATTENTION Position retrieved by referer in Google Images is // the Position number of image NOT the number of items in the page like web search $searchpage=$se['Pos']; $searchcountry = explode(".", $se['Se']); } else { $searchpage=($se['Pos']/10+1); $searchcountry = explode(".", $se['Se']); } if ($searchcountry[3] != '' ) { $searchengine .= " ".strtoupper($searchcountry[3]); } elseif ($searchcountry[2] != '') { $searchengine .= " ".strtoupper($searchcountry[2]); } } if ($searchpage == "") { $searchpage = 0; } //### Check for spam... $spam = 0; //a spam default of 0 is required to add record... if ( $wassup_options->wassup_spamcheck == 1 ) { if ( $wassup_options->wassup_refspam == 1 && !empty($referrer) ) { //#first check for referrer spam (faster, if positive) //#...but skip when referrer is own blog ($siteurl/$wpurl) if (stristr($referrer,$wpurl) === FALSE && stristr($referrer,$siteurl) === FALSE) { // Do a control if it is Referrer Spam if (wGetSpamRef($referrer) == 1) { $spam = 2; $spamresult = $spam; } } } if ( $wassup_options->wassup_spam == 1 && $spam == 0 ) { //# some valid spiders to exclude from spam checking $goodbot = false; if ($hostname!="" && !empty($spider)) { if (preg_match('/^(googlebot|msnbot|yahoo\!\ slurp|technorati)/i',$spider)>0 && preg_match('/\.(googlebot|live|msn|yahoo|technorati)\.(com|net)$/i',$hostname)>0){ $goodbot = true; } } //# No duplicate spam testing in same session unless there //# is a forum page request or comment... if (isset($spamresult) && stristr($urlRequested,"comment") === FALSE && stristr($urlRequested,"forum") === FALSE && empty($comment_user) && empty($_POST['comment'])) { $spam = $spamresult; //# No spam check on known bots (google, yahoo,...) unless //# there is a comment or forum page request... } elseif (empty($spider) || !$goodbot || stristr($urlRequested,"comment") !== FALSE || stristr($urlRequested,"forum") !== FALSE || !empty($comment_user) ) { // Try to search for previous spammer detected by akismet with same IP if (!empty($ipAddress)) { $checkauthor = New CheckComment; $checkauthor->tablePrefix = $wpdb->prefix; $spammerIP = $checkauthor->isSpammer($ipAddress); if ( $spammerIP > 0) { $spam = 1; $spamresult = $spam; } } // search for spammer in badhosts file... if ( $spam == 0) { if (!empty($hostname) && $hostname != "unknown") { if (wGetSpamRef($hostname) == 1) { $spam = 1; $spamresult = $spam; } } } //#lastly check for comment spammers using Akismet API //# Note: this causes "header already sent" errors in some Wordpress configurations if ($spam == 0) { $akismet_key = get_option('wordpress_api_key'); $akismet_class = dirname(__FILE__).'/lib/akismet.class.php'; if (file_exists($akismet_class) && !empty($akismet_key)) { $comment_user_email = utf8_encode($_COOKIE['comment_author_email_'.COOKIEHASH]); $comment_user_url = utf8_encode($_COOKIE['comment_author_url_'.COOKIEHASH]); include($akismet_class); // load array with comment data $Acomment = array( 'author' => $comment_user, 'email' => $comment_user_email, 'website' => $comment_user_url, 'body' => $_POST["comment"], 'permalink' => $urlRequested, 'user_ip' => $ipAddress, 'user_agent' => $userAgent ); // instantiate an instance of the class $akismet = new Akismet($wpurl, $akismet_key, $Acomment); // Check if it's spam if ( $akismet->isSpam() ) { $spam = 1; $spamresult = $spam; } // test for errors if($akismet->errorsExist()) { //#error means don't save result in cookie unset($spamresult); } } //end if file_exists(akismet_class) } //end if $spam == 0 } //end else $spamresult } //end if wassup_spam == 1 } //end if wassup_spamcheck == 1 //identify hacker/bad activity attempts and assign spam=3 if ($spam == 0 && $hackercheck) { if (is_admin() || stristr($urlRequested,"/wp-content/plugins")!==FALSE || stristr($urlRequested,"/wp-admin/")!== FALSE) { $spam=3; } } // Personally used to debug if ($current_user->user_email == "*****@*****.**") { } //## Final exclusion control is spam... if ($spam == 0 OR ($wassup_options->wassup_spam == 1 AND $spam == 1) OR ($wassup_options->wassup_refspam == 1 AND $spam == 2)) { /* // #save spam results in session... if (isset($spamresult)) { @session_start(); //required to access $_SESSION $_SESSION['spamresult'] = $spamresult; @session_write_close(); } */ // #Record visit in wassup tables... // Insert the record into the db insert_into_wp($table_name, $wassup_id, $timestamp, $ipAddress, $hostname, $urlRequested, $userAgent, $referrer, $search_phrase, $searchpage, $os, $browser, $language, $screen_res, $searchengine, $spider, $feed, $logged_user, $comment_user, $spam); // Insert the record into the wassup_tmp table too insert_into_wp($table_tmp_name, $wassup_id, $timestamp, $ipAddress, $hostname, $urlRequested, $userAgent, $referrer, $search_phrase, $searchpage, $os, $browser, $language, $screen_res, $searchengine, $spider, $feed, $logged_user, $comment_user, $spam); // Delete records older then 3 minutes $wpdb->query("DELETE FROM $table_tmp_name WHERE `timestamp`<'".strtotime("-3 minutes", $timestamp)."'"); } //end if $spam == 0 } //end if wassup_spider } //end if dup_urlrequest == 0 } //end if !is_404 } //end if wassup_attack } //end if wassup_loggedin } //end if !themes } //end if !plugins } //end if !favicon //### Purge old records from wassup table //automatic database cleanup of old records... if ($wassup_options->delete_auto != "") { // do purge every few visits to keep wassup fast... if ( ((int)$timestamp)%7 == 0 ) { //use visit timestamp instead of current time for // delete parameter //$to_date = wassup_get_time(); $from_date = strtotime($wassup_options->delete_auto, $timestamp); //#check before doing delete as it could lock the table... if ((int)$wpdb->get_var("SELECT COUNT(id) FROM $table_name WHERE `timestamp`<'$from_date'") > 0) { $wpdb->query("DELETE FROM $table_name WHERE `timestamp`<'$from_date'"); } // Optimize table once a day if ($timestamp > strtotime("24 hours", $wassup_options->wassup_optimize)) { $wpdb->query("OPTIMIZE TABLE $table_name"); $wassup_options->wassup_optimize = wassup_get_time(); $wassup_options->saveSettings(); } } } //end if delete_auto } //end if wassup_exclude } //end if wassup_exclude_url } //end if wassup_active } //end if !is_admin //### Notify admin if alert is set and wassup table > alert if ($wassup_options->wassup_remind_flag == 1) { // check database size every few visits to keep wassup fast... if ( (time())%7 == 0 ) { $table_status = $wpdb->get_results("SHOW TABLE STATUS LIKE '$table_name'"); foreach ($table_status as $fstatus) { $data_lenght = $fstatus->Data_length; } $tusage = ($data_lenght/1024/1024); if ($tusage > $wassup_options->wassup_remind_mb) { $recipient = get_bloginfo('admin_email'); $sender = get_bloginfo('name').' <wassup_noreply@'.parse_url(get_bloginfo('siteurl'),PHP_URL_HOST).'>'; $subject = "[ALERT]".__('WassUp Plugin table has reached maximum size!','wassup'); $message = __('Hi','wassup').",\n".__('you have received this email because your WassUp Database table at your Wordpress blog','wassup')." (".get_bloginfo('url').") ".__('has reached the maximum value you set in the options menu','wassup')." (".$wassup_options->wassup_remind_mb." Mb).\n\n"; $message .= __('This is only a reminder, please take the actions you want in the WassUp options menu','wassup')." (".get_bloginfo('url')."/wp-admin/admin.php?page=wassup-options).\n\n".__('This alert now will be removed and you will be able to set a new one','wassup').".\n\n"; $message .= __('Thank you for using WassUp plugin. Check if there is a new version available here:','wassup')." http://wordpress.org/extend/plugins/wassup/\n\n".__('Have a nice day!','wassup')."\n"; mail($recipient, $subject, $message, "From: $sender"); $wassup_options->wassup_remind_flag = 2; $wassup_options->saveSettings(); } } } //if wassup_remind_flag //} //if SECRET_KEY } //end function wassupAppend()
private function is_spam_akismet($text) { global $config, $user; if (strlen($config->get_string('comment_wordpress_key')) > 0) { $comment = array('author' => $user->name, 'email' => $user->email, 'website' => '', 'body' => $text, 'permalink' => ''); $akismet = new Akismet($_SERVER['SERVER_NAME'], $config->get_string('comment_wordpress_key'), $comment); if ($akismet->errorsExist()) { return false; } else { return $akismet->isSpam(); } } return false; }
/** * @param string $text * @return bool */ private function is_spam_akismet($text) { global $config, $user; if (strlen($config->get_string('comment_wordpress_key')) > 0) { $comment = array('author' => $user->name, 'email' => $user->email, 'website' => '', 'body' => $text, 'permalink' => ''); # akismet breaks if there's no referrer in the environment; so if there # isn't, supply one manually if (!isset($_SERVER['HTTP_REFERER'])) { $comment['referrer'] = 'none'; log_warning("comment", "User '{$user->name}' commented with no referrer: {$text}"); } if (!isset($_SERVER['HTTP_USER_AGENT'])) { $comment['user_agent'] = 'none'; log_warning("comment", "User '{$user->name}' commented with no user-agent: {$text}"); } $akismet = new Akismet($_SERVER['SERVER_NAME'], $config->get_string('comment_wordpress_key'), $comment); if ($akismet->errorsExist()) { return false; } else { return $akismet->isSpam(); } } return false; }
/** * Process new reply submission called via an iframe. * * @since 2.0 * @access public */ public function ajaxSubmitReply() { // Process when a new reply is made from bbcode / wysiwyg editor $my = JFactory::getUser(); $config = DiscussHelper::getConfig(); $ajax = new Disjax(); $acl = DiscussHelper::getHelper('ACL'); $post = JRequest::get('POST'); // @task: User needs to be logged in, in order to submit a new reply. if (!$acl->allowed('add_reply', '0') && $my->id == 0) { // Append result $output = array(); $output['message'] = JText::_('COM_EASYDISCUSS_PLEASE_KINDLY_LOGIN_INORDER_TO_REPLY'); $output['type'] = 'error'; echo $this->_outputJson($output); return false; } if (!$acl->allowed('add_reply', '0')) { // Append result $output = array(); $output['message'] = JText::_('COM_EASYDISCUSS_ENTRY_NO_PERMISSION_TO_REPLY'); $output['type'] = 'error'; echo $this->_outputJson($output); return false; } if (!isset($post['parent_id'])) { // Append result $output = array(); $output['message'] = JText::_('COM_EASYDISCUSS_SYSTEM_INVALID_ID'); $output['type'] = 'error'; echo $this->_outputJson($output); return false; } $question = DiscussHelper::getTable('Post'); $state = $question->load($post['parent_id']); if (!$state) { // Append result $output = array(); $output['message'] = JText::_('COM_EASYDISCUSS_SYSTEM_INVALID_ID'); $output['type'] = 'error'; echo $this->_outputJson($output); return false; } // Ensure that the user really has access to the discussion if ($question->private && $my->id != $question->user_id && !DiscussHelper::isSiteAdmin() && !DiscussHelper::isModerator($post->category_id, $my->id)) { // Append result $output = array(); $output['message'] = JText::_('COM_EASYDISCUSS_SYSTEM_INSUFFICIENT_PERMISSIONS'); $output['type'] = 'error'; echo $this->_outputJson($output); return false; } $questionCategory = DiscussHelper::getTable('Category'); $questionCategory->load($question->category_id); $questionAccess = $question->getAccess($questionCategory); if (!$questionAccess->canReply()) { // Append result $output = array(); $output['message'] = JText::_('COM_EASYDISCUSS_ENTRY_NO_PERMISSION_TO_REPLY'); $output['type'] = 'error'; echo $this->_outputJson($output); return false; } if (empty($post['dc_reply_content'])) { // Append result $output = array(); $output['message'] = JText::_('COM_EASYDISCUSS_ERROR_REPLY_EMPTY'); $output['type'] = 'error'; echo $this->_outputJson($output); return false; } if (empty($my->id)) { if (empty($post['user_type'])) { // Append result $output = array(); $output['message'] = JText::_('COM_EASYDISCUSS_INVALID_USER_TYPE'); $output['type'] = 'error'; echo $this->_outputJson($output); return false; } if (!DiscussUserHelper::validateUserType($post['user_type'])) { $output = array(); $output['message'] = JText::sprintf('COM_EASYDISCUSS_THIS_USERTYPE_HAD_BEEN_DISABLED', $post['user_type']); $output['type'] = 'error'; echo $this->_outputJson($output); return false; } if (empty($post['poster_name']) || empty($post['poster_email'])) { $output = array(); $output['message'] = JText::sprintf('COM_EASYDISCUSS_GUEST_SIGN_IN_DESC'); $output['type'] = 'error'; echo $this->_outputJson($output); return false; } } else { $post['user_type'] = 'member'; $post['poster_name'] = ''; $post['poster_email'] = ''; } // get id if available $id = 0; // set alias $post['alias'] = DiscussHelper::getAlias($post['title'], 'post'); // set post owner $post['user_id'] = $my->id; $content = JRequest::getVar('dc_reply_content', '', 'post', 'none', JREQUEST_ALLOWRAW); $content = DiscussHelper::getHelper('String ')->unhtmlentities($content); // Rebind the post data $post['dc_reply_content'] = $content; $post['content_type'] = DiscussHelper::getEditorType('reply'); // Set the ip address $post['ip'] = JRequest::getVar('REMOTE_ADDR', '', 'SERVER'); // bind the table $table = DiscussHelper::getTable('Post'); $table->bind($post, true); // Set the category id for the reply since we might need to use this for acl checks. $table->category_id = $question->category_id; if ($config->get('main_moderatepost', 0) && !DiscussHelper::isModerateThreshold($my->id) && !DiscussHelper::isSiteAdmin($post->user_id)) { $table->published = DISCUSS_ID_PENDING; } else { $table->published = DISCUSS_ID_PUBLISHED; } require_once DISCUSS_CLASSES . '/recaptcha.php'; if (DiscussRecaptcha::isRequired()) { $obj = DiscussRecaptcha::recaptcha_check_answer($config->get('antispam_recaptcha_private'), $_SERVER['REMOTE_ADDR'], $post['recaptcha_challenge_field'], $post['recaptcha_response_field']); if (!$obj->is_valid) { $output = array(); $output['message'] = JText::_('COM_EASYDISCUSS_POST_INVALID_RECAPTCHA_RESPONSE'); $output['type'] = 'error.captcha'; echo $this->_outputJson($output); return false; } } else { if ($config->get('antispam_easydiscuss_captcha')) { $runCaptcha = DiscussHelper::getHelper('Captcha')->showCaptcha(); if ($runCaptcha) { $response = JRequest::getVar('captcha-response'); $captchaId = JRequest::getInt('captcha-id'); $discussCaptcha = new stdClass(); $discussCaptcha->captchaResponse = $response; $discussCaptcha->captchaId = $captchaId; $state = DiscussHelper::getHelper('Captcha')->verify($discussCaptcha); if (!$state) { $output = array(); $output['message'] = JText::sprintf('COM_EASYDISCUSS_INVALID_CAPTCHA'); $output['type'] = 'error'; echo $this->_outputJson($output); return false; } } } } if ($config->get('antispam_akismet') && $config->get('antispam_akismet_key')) { require_once DISCUSS_CLASSES . '/akismet.php'; $data = array('author' => $my->name, 'email' => $my->email, 'website' => DISCUSS_JURIROOT, 'body' => $post['dc_reply_content'], 'alias' => ''); $akismet = new Akismet(DISCUSS_JURIROOT, $config->get('antispam_akismet_key'), $data); if (!$akismet->errorsExist()) { if ($akismet->isSpam()) { $output = array(); $output['message'] = JText::_('COM_EASYDISCUSS_AKISMET_SPAM_DETECTED'); $output['type'] = 'error'; echo $this->_outputJson($output); return false; } } } // hold last inserted ID in DB $lastId = null; // @rule: Bind parameters $table->bindParams($post); $isNew = true; // @trigger: onBeforeSave DiscussEventsHelper::importPlugin('content'); DiscussEventsHelper::onContentBeforeSave('reply', $table, $isNew); if (!$table->store()) { $output = array(); $output['message'] = JText::_('COM_EASYDISCUSS_ERROR_SUBMIT_REPLY'); $output['type'] = 'error'; echo $this->_outputJson($output); return false; } // Process poll items. if ($config->get('main_polls_replies')) { $polls = JRequest::getVar('pollitems'); if (!is_array($polls)) { $polls = array($polls); } // If the post is being edited and // there is only 1 poll item which is also empty, // we need to delete existing polls tied to this post. //if( count( $polls ) == 1 && empty( $polls[0] ) && !$isNew ) if (!$isNew) { $post->removePoll(); } if (count($polls) > 0) { $hasPolls = false; foreach ($polls as $poll) { // As long as there is 1 valid poll, we need to store them. if (!empty($poll)) { $hasPolls = true; break; } } if ($hasPolls) { $pollItems = JRequest::getVar('pollitems'); // Check if the multiple polls checkbox is it checked? $multiplePolls = JRequest::getVar('multiplePolls', '0'); if ($pollItems) { // As long as we need to create the poll answers, we need to create the main question. $pollTitle = JRequest::getVar('poll_question', ''); // Since poll question are entirely optional. $pollQuestion = DiscussHelper::getTable('PollQuestion'); $pollQuestion->loadByPost($table->id); $pollQuestion->post_id = $table->id; $pollQuestion->title = $pollTitle; $pollQuestion->multiple = $config->get('main_polls_multiple') ? $multiplePolls : false; $pollQuestion->store(); if (!$isNew) { // Try to detect which poll items needs to be removed. $remove = JRequest::getVar('pollsremove'); if (!empty($remove)) { $remove = explode(',', $remove); foreach ($remove as $id) { $id = (int) $id; $poll = DiscussHelper::getTable('Poll'); $poll->load($id); $poll->delete(); } } } foreach ($pollItems as $item) { $value = (string) $item; if (trim($value) == '') { continue; } $poll = DiscussHelper::getTable('Poll'); if (!$poll->loadByValue($value, $table->id, $multiplePolls)) { $poll->set('value', $value); $poll->set('post_id', $table->get('id')); $poll->store(); } } } } } } // Process custom fields $this->saveCustomFieldsValue($table->id); // @trigger: onAfterSave DiscussEventsHelper::onContentAfterSave('reply', $table, $isNew); // @rule: Add notifications for the thread starter if ($table->published && $config->get('main_notifications_reply')) { // Get all users that are subscribed to this post $model = $this->getModel('Posts'); $participants = $model->getParticipants($table->parent_id); // Add the thread starter into the list of participants. $participants[] = $question->get('user_id'); // Notify all subscribers foreach ($participants as $participant) { if ($participant != $my->id) { $notification = DiscussHelper::getTable('Notifications'); $notification->bind(array('title' => JText::sprintf('COM_EASYDISCUSS_REPLY_DISCUSSION_NOTIFICATION_TITLE', $question->get('title')), 'cid' => $question->get('id'), 'type' => DISCUSS_NOTIFICATIONS_REPLY, 'target' => $participant, 'author' => $table->get('user_id'), 'permalink' => 'index.php?option=com_easydiscuss&view=post&id=' . $question->get('id'))); $notification->store(); } } // @rule: Detect if any names are being mentioned in the post $names = DiscussHelper::getHelper('String')->detectNames($table->content); if ($names) { foreach ($names as $name) { $name = JString::str_ireplace('@', '', $name); $id = DiscussHelper::getUserId($name); if (!$id || $id == $table->get('user_id')) { continue; } $notification = DiscussHelper::getTable('Notifications'); $notification->bind(array('title' => JText::sprintf('COM_EASYDISCUSS_MENTIONED_REPLY_NOTIFICATION_TITLE', $question->get('title')), 'cid' => $question->get('id'), 'type' => DISCUSS_NOTIFICATIONS_MENTIONED, 'target' => $id, 'author' => $table->get('user_id'), 'permalink' => 'index.php?option=com_easydiscuss&view=post&id=' . $question->get('id'))); $notification->store(); } } } if ($table->published && !$question->private) { // Create notification item in EasySocial DiscussHelper::getHelper('EasySocial')->notify('new.reply', $table, $question); // @rule: Badges DiscussHelper::getHelper('History')->log('easydiscuss.new.reply', $table->user_id, JText::sprintf('COM_EASYDISCUSS_BADGES_HISTORY_NEW_REPLY', $question->title), $table->id); DiscussHelper::getHelper('Badges')->assign('easydiscuss.new.reply', $table->user_id); DiscussHelper::getHelper('Points')->assign('easydiscuss.new.reply', $table->user_id, $table); // Assign badge for EasySocial DiscussHelper::getHelper('EasySocial')->assignBadge('reply.question', $table->user_id, JText::sprintf('COM_EASYDISCUSS_BADGES_HISTORY_NEW_REPLY', $question->title)); // @rule: AUP integrations DiscussHelper::getHelper('Aup')->assign(DISCUSS_POINTS_NEW_REPLY, $table->user_id, $question->title); // @rule: ranking DiscussHelper::getHelper('ranks')->assignRank($table->user_id, $config->get('main_ranking_calc_type')); } // Bind file attachments if ($acl->allowed('add_attachment', '0')) { if (!$table->bindAttachments() && $table->getError()) { $output = array(); $output['message'] = $table->getError(); $output['type'] = 'error'; echo $this->_outputJson($output); return false; } } $replier = new stdClass(); if ($my->id > 0) { $replier->id = $my->id; $replier->name = $my->name; } else { $replier->id = 0; $replier->name = JText::_('COM_EASYDISCUSS_GUEST'); // TODO: user the poster_name } //load porfile info and auto save into table if user is not already exist in discuss's user table. $creator = DiscussHelper::getTable('Profile'); $creator->load($replier->id); $table->user = $creator; $voteModel = $this->getModel('votes'); // clean up bad code $table->content_raw = $table->content; //$table->content = DiscussHelper::parseContent( $table->content ); // @rule: URL References $table->references = $table->getReferences(); // Since this is a new reply, it's impossible that it has been voted before. $table->voted = false; // get total vote for this reply $table->totalVote = $table->sum_totalvote; $result['status'] = 'success'; $result['title'] = JText::_('COM_EASYDISCUSS_SUCCESS_SUBMIT_REPLY'); $result['id'] = $table->id; $result['message'] = JText::_('COM_EASYDISCUSS_REPLY_SAVED'); $table->title = DiscussHelper::wordFilter($table->title); $table->content = DiscussHelper::wordFilter($table->content); // Legacy fix when switching from WYSIWYG editor to bbcode. $table->content = EasyDiscussParser::html2bbcode($table->content); $table->content = DiscussHelper::formatContent($table, true); //all access control goes here. $canDelete = false; $isMainLocked = false; if (DiscussHelper::isSiteAdmin() || $acl->allowed('delete_reply', '0') || $table->user_id == $my->id) { $canDelete = true; } $parent = DiscussHelper::getTable('Post'); $parent->load($table->parent_id); $isMainLocked = $parent->islock; //default value $table->isVoted = 0; $table->total_vote_cnt = 0; $table->likesAuthor = ''; $table->minimize = 0; if ($config->get('main_content_trigger_replies')) { $tempContent = $table->content; $table->content = str_replace('@', '@', $tempContent); // process content plugins DiscussEventsHelper::importPlugin('content'); DiscussEventsHelper::onContentPrepare('reply', $table); $table->event = new stdClass(); $results = DiscussEventsHelper::onContentBeforeDisplay('reply', $table); $table->event->beforeDisplayContent = trim(implode("\n", $results)); $results = DiscussEventsHelper::onContentAfterDisplay('reply', $table); $table->event->afterDisplayContent = trim(implode("\n", $results)); } $tpl = new DiscussThemes(); $category = DiscussHelper::getTable('Category'); $category->load($question->category_id); $table->access = $table->getAccess($category); // Since the reply dont have any comments yet. $table->comments = array(); $tpl->set('category', $category); $tpl->set('post', $table); $tpl->set('question', $parent); $tpl->set('isMine', DiscussHelper::isMine($parent->user_id)); $tpl->set('isAdmin', DiscussHelper::isSiteAdmin()); $tpl->set('isMainLocked', $isMainLocked); $recaptcha = ''; $enableRecaptcha = $config->get('antispam_recaptcha', 0); $publicKey = $config->get('antispam_recaptcha_public'); $html = $table->published == DISCUSS_ID_PENDING ? $tpl->fetch('post.reply.item.moderation.php') : $tpl->fetch('post.reply.item.php'); //send notification to all comment's subscribers that want to receive notification immediately $notify = DiscussHelper::getNotification(); $excludeEmails = array(); $attachments = $table->getAttachments(); $emailData['attachments'] = $attachments; $emailData['postTitle'] = $parent->title; $emailData['comment'] = DiscussHelper::parseContent($table->content); $emailData['commentAuthor'] = $my->id ? $creator->getName() : $table->poster_name; $emailData['postLink'] = DiscussRouter::getRoutedURL('index.php?option=com_easydiscuss&view=post&id=' . $parent->id, false, true); $emailContent = $table->content; $isEditing = $isNew == true ? false : true; $emailContent = DiscussHelper::bbcodeHtmlSwitcher($table, 'reply', $isEditing); $emailContent = $question->trimEmail($emailContent); $emailData['replyContent'] = $emailContent; $emailData['replyAuthor'] = $my->id ? $creator->getName() : $table->poster_name; $emailData['replyAuthorAvatar'] = $creator->getAvatar(); $emailData['post_id'] = $parent->id; $emailData['cat_id'] = $parent->category_id; $subscriberEmails = array(); if (($config->get('main_sitesubscription') || $config->get('main_postsubscription')) && $config->get('notify_subscriber') && $table->published == DISCUSS_ID_PUBLISHED) { $emailData['emailTemplate'] = 'email.subscription.reply.new.php'; $emailData['emailSubject'] = JText::sprintf('COM_EASYDISCUSS_NEW_REPLY_ADDED', $parent->id, $parent->title); $posterEmail = $post['poster_email'] ? $post['poster_email'] : $my->email; // Get the emails of user who subscribe to this post only // This does not send to subscribers whom subscribe to site and category $subcribersEmails = DiscussHelper::getHelper('Mailer')->notifyThreadSubscribers($emailData, array($posterEmail, $my->email)); $excludeEmails[] = $posterEmail; $excludeEmails = array_merge($excludeEmails, $subcribersEmails); $excludeEmails = array_unique($excludeEmails); } //notify post owner. $postOwnerId = $parent->user_id; $postOwner = JFactory::getUser($postOwnerId); $ownerEmail = $postOwner->email; if ($parent->user_type != 'member') { $ownerEmail = $parent->poster_email; } // Notify Owner // if reply under moderation, send owner a notification. if ($config->get('notify_owner') && $table->published == DISCUSS_ID_PUBLISHED && $postOwnerId != $replier->id && !in_array($ownerEmail, $excludeEmails) && !empty($ownerEmail)) { $emailData['owner_email'] = $ownerEmail; $emailData['emailSubject'] = JText::sprintf('COM_EASYDISCUSS_NEW_REPLY_ADDED', $parent->id, $parent->title); $emailData['emailTemplate'] = 'email.post.reply.new.php'; DiscussHelper::getHelper('Mailer')->notifyThreadOwner($emailData); // Notify Participants $excludeEmails[] = $ownerEmail; $excludeEmails = array_unique($excludeEmails); } if ($config->get('notify_participants') && $table->published == DISCUSS_ID_PUBLISHED) { $emailData['emailSubject'] = JText::sprintf('COM_EASYDISCUSS_NEW_REPLY_ADDED', $parent->id, $parent->title); $emailData['emailTemplate'] = 'email.post.reply.new.php'; DiscussHelper::getHelper('Mailer')->notifyThreadParticipants($emailData, $excludeEmails); } if ($table->published == DISCUSS_ID_PENDING) { // Notify admins. // Generate hashkeys to map this current request $hashkey = DiscussHelper::getTable('Hashkeys'); $hashkey->uid = $table->id; $hashkey->type = DISCUSS_REPLY_TYPE; $hashkey->store(); require_once DISCUSS_HELPERS . '/router.php'; $approveURL = DiscussHelper::getExternalLink('index.php?option=com_easydiscuss&controller=posts&task=approvePost&key=' . $hashkey->key); $rejectURL = DiscussHelper::getExternalLink('index.php?option=com_easydiscuss&controller=posts&task=rejectPost&key=' . $hashkey->key); $emailData['moderation'] = '<div style="display:inline-block;width:100%;padding:20px;border-top:1px solid #ccc;padding:20px 0 10px;margin-top:20px;line-height:19px;color:#555;font-family:\'Lucida Grande\',Tahoma,Arial;font-size:12px;text-align:left">'; $emailData['moderation'] .= '<a href="' . $approveURL . '" style="display:inline-block;padding:5px 15px;background:#fc0;border:1px solid #caa200;border-bottom-color:#977900;color:#534200;text-shadow:0 1px 0 #ffe684;font-weight:bold;box-shadow:inset 0 1px 0 #ffe064;-moz-box-shadow:inset 0 1px 0 #ffe064;-webkit-box-shadow:inset 0 1px 0 #ffe064;border-radius:2px;moz-border-radius:2px;-webkit-border-radius:2px;text-decoration:none!important">' . JText::_('COM_EASYDISCUSS_EMAIL_APPROVE_REPLY') . '</a>'; $emailData['moderation'] .= ' ' . JText::_('COM_EASYDISCUSS_OR') . ' <a href="' . $rejectURL . '" style="color:#477fda">' . JText::_('COM_EASYDISCUSS_REJECT') . '</a>'; $emailData['moderation'] .= '</div>'; $emailData['emailSubject'] = JText::sprintf('COM_EASYDISCUSS_NEW_REPLY_MODERATE', $parent->title); $emailData['emailTemplate'] = 'email.post.reply.moderation.php'; DiscussHelper::getHelper('Mailer')->notifyAdministrators($emailData, array(), $config->get('notify_admin'), $config->get('notify_moderator')); } elseif ($table->published == DISCUSS_ID_PUBLISHED && !$question->private) { $emailData['emailTemplate'] = 'email.post.reply.new.php'; $emailData['emailSubject'] = JText::sprintf('COM_EASYDISCUSS_NEW_REPLY_ADDED', $parent->id, $parent->title); $emailData['post_id'] = $parent->id; DiscussHelper::getHelper('Mailer')->notifyAdministrators($emailData, $excludeEmails, $config->get('notify_admin_onreply'), $config->get('notify_moderator_onreply')); } // @rule: Jomsocial activity integrations if ($table->published == DISCUSS_ID_PUBLISHED && !$question->private) { DiscussHelper::getHelper('jomsocial')->addActivityReply($table); DiscussHelper::getHelper('easysocial')->replyDiscussionStream($table); } $autoSubscribed = false; if ($config->get('main_autopostsubscription') && $config->get('main_postsubscription') && $table->user_type != 'twitter') { //automatically subscribe this user into this post. $subscription_info = array(); $subscription_info['type'] = 'post'; $subscription_info['userid'] = !empty($table->user_id) ? $table->user_id : '0'; $subscription_info['email'] = !empty($table->user_id) ? $my->email : $table->poster_email; $subscription_info['cid'] = $parent->id; $subscription_info['member'] = !empty($table->user_id) ? '1' : '0'; $subscription_info['name'] = !empty($table->user_id) ? $my->name : $table->poster_name; $subscription_info['interval'] = 'instant'; $model = $this->getModel('Subscribe'); $sid = ''; if ($subscription_info['userid'] == 0) { $sid = $model->isPostSubscribedEmail($subscription_info); if (empty($sid)) { if ($model->addSubscription($subscription_info)) { $autoSubscribed = true; } } } else { $sid = $model->isPostSubscribedUser($subscription_info); if (empty($sid['id'])) { //add new subscription. if ($model->addSubscription($subscription_info)) { $autoSubscribed = true; } } } } // Append result $output = array(); $output['message'] = $autoSubscribed ? JText::_('COM_EASYDISCUSS_SUCCESS_REPLY_POSTED_AND_SUBSCRIBED') : JText::_('COM_EASYDISCUSS_SUCCESS_REPLY_POSTED'); $output['type'] = 'success'; $output['html'] = $html; // Perhaps the viewer is unable to view the replies. if (!$questionCategory->canViewReplies()) { $output['message'] = JText::_('COM_EASYDISCUSS_REPLY_SUCCESS_BUT_UNABLE_TO_VIEW_REPLIES'); } if ($enableRecaptcha && !empty($publicKey) && $recaptcha) { $output['type'] = 'success.captcha'; } echo $this->_outputJson($output); }
public function get_pingback($id) { $postdata = file_get_contents("php://input"); if ($postdata) { $xml = new SimpleXMLElement($postdata); $pingback_sender_url = strval($xml->params->param[0]->value->string); $pingback_receiver_url = strval($xml->params->param[1]->value->string); // get content: if ($pingback_sender_url) { if ($url_content = $this->_get_url_content($pingback_sender_url)) { if (strpos($url_content[1], BASE_URL . PAGE) !== false) { // get title: preg_match("/<title>(.*)<\\/title>/i", $url_content[1], $matches); if (isset($matches[1]) && trim($matches[1]) != '') { $pingback_title = trim(filter_control_characters($matches[1])); if (mb_strlen($pingback_title) > $this->pingback_title_maxlength) { $pingback_title = truncate($pingback_title, $this->pingback_title_maxlength); } } else { $pingback_error = true; } // get body: preg_match("/<body[^>]*>(.*)<\\/body>/smi", $url_content[1], $b_matches); if (isset($b_matches[1]) && trim($b_matches[1]) != '') { $body = strip_tags($b_matches[1]); $body = preg_replace("/\r\n|\r|\n/", "\n", $body); $body_lines = explode("\n", $body); $cleared_body = ''; foreach ($body_lines as $body_line) { if (trim($body_line) != '') { $cleared_body .= trim($body_line) . ' '; } } $cleared_body = trim(filter_control_characters($cleared_body)); } else { $pingback_error = true; } if (empty($pingback_error)) { // not accepted words check: $joined_message = mb_strtolower($pingback_title . ' ' . $pingback_sender_url . ' ' . $cleared_body); $not_accepted_words = get_not_accepted_words($joined_message); if ($not_accepted_words) { $pingback_error = true; } } if (empty($pingback_error)) { // Akismet spam check: if ($this->settings['akismet_key'] != '' && $this->settings['akismet_entry_check'] == 1) { $check_posting['author'] = $pingback_title; $check_posting['website'] = $pingback_sender_url; $check_posting['body'] = truncate($cleared_body, 3000); $akismet = new Akismet(BASE_URL, $this->settings['akismet_key'], $check_posting); // test for errors if ($akismet->errorsExist()) { //$pingback_error = true; if ($akismet->isError(AKISMET_INVALID_KEY)) { $akismet_errors[] = 'akismet_error_api_key'; } elseif ($akismet->isError(AKISMET_RESPONSE_FAILED)) { $akismet_errors[] = 'akismet_error_connection'; } elseif ($akismet->isError(AKISMET_SERVER_NOT_FOUND)) { $akismet_errors[] = 'akismet_error_connection'; } } else { // No errors, check for spam if ($akismet->isSpam()) { // TODO: #$pingback_error = true; $akismet_spam = true; #$mail = new Mail(); #$mail->send($this->settings['email'], $this->settings['email'], 'Pingback-Spam?', $check_posting['author']."\n".$check_posting['website']."\n".$check_posting['body'], $this->settings['mail_parameter']); } } } } if (empty($pingback_error)) { // check if url was already posted: $dbr = Database::$entries->prepare("SELECT COUNT(*) FROM " . Database::$db_settings['comment_table'] . " WHERE comment_id=:comment_id AND type=0 AND comment='' AND email_hp=:email_hp"); $dbr->bindParam(':comment_id', $id, PDO::PARAM_INT); $dbr->bindParam(':email_hp', $pingback_sender_url, PDO::PARAM_STR); $dbr->execute(); $comment_count = $dbr->fetchColumn(); if ($comment_count > 0) { $pingback_error = true; } } if (empty($pingback_error)) { $dbr = Database::$entries->prepare("INSERT INTO " . Database::$db_settings['comment_table'] . " (type, comment_id, time, ip, name, email_hp, comment) VALUES (0, :comment_id, :time, :ip, :name, :email_hp, '')"); $dbr->bindParam(':comment_id', $id, PDO::PARAM_INT); $dbr->bindValue(':time', time(), PDO::PARAM_INT); $dbr->bindParam(':ip', $_SERVER['REMOTE_ADDR'], PDO::PARAM_STR); $dbr->bindParam(':name', $pingback_title, PDO::PARAM_STR); $dbr->bindParam(':email_hp', $pingback_sender_url, PDO::PARAM_STR); $dbr->execute(); // E-mail notification to admin: if ($this->settings['comment_notification'] && $this->settings['email']) { $this->_localization->replacePlaceholder('page', PAGE, 'pingback_notification_subject'); $this->_localization->replacePlaceholder('title', $pingback_title, 'pingback_notification_message'); $this->_localization->replacePlaceholder('url', $pingback_sender_url, 'pingback_notification_message'); $this->_localization->replacePlaceholder('link', BASE_URL . PAGE, 'pingback_notification_message'); // TODO: if (isset($akismet_spam)) { $add = "\n\nAkismet: SPAM!"; } else { $add = ''; } $mail = new Mail(); $mail->set_charset(CHARSET); $mail->send($this->settings['email'], $this->settings['email'], Localization::$lang['pingback_notification_subject'], Localization::$lang['pingback_notification_message'] . $add, $this->settings['mail_parameter']); } $response = '<?xml version="1.0"?><methodResponse><params><param><value><string>OK</string></value></param></params></methodResponse>'; header('Content-Type: text/xml'); echo $response; return true; } } } } } $response = '<?xml version="1.0"?><methodResponse><fault><value><struct><member><name>faultCode</name><value><int>0</int></value></member><member><name>faultString</name><value><string>FAIL</string></value></member></struct></value></fault></methodResponse>'; header('Content-Type: text/xml'); echo $response; return false; }
/** * Handles POST request for new discussions * * @since 3.0 * @access public */ public function submit() { JRequest::checkToken('request') or jexit('Invalid Token'); $config = DiscussHelper::getConfig(); $my = JFactory::getUser(); $app = JFactory::getApplication(); $acl = DiscussHelper::getHelper('ACL'); // If guest posting is disallowed in the settings, they shouldn't be able to create a discussion at all. if (!$my->id && !$acl->allowed('add_question', '0')) { DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_POST_PLEASE_LOGIN'), DISCUSS_QUEUE_ERROR); $app->redirect(DiscussRouter::_('index.php?option=com_easydiscuss', false)); return $app->close(); } // If user is disallowed in the acl, they shouldn't be able to create a discussion at all. if ($my->id && !$acl->allowed('add_question', '0')) { DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_SYSTEM_INSUFFICIENT_PERMISSIONS'), DISCUSS_QUEUE_ERROR); $app->redirect(DiscussRouter::_('index.php?option=com_easydiscuss', false)); return $app->close(); } // Get values from the posted form. $data = JRequest::get('post'); if (isset($data['mod_post_topic_category_id'])) { $data['category_id'] = $data['mod_post_topic_category_id']; unset($data['mod_post_topic_category_id']); } // Run validation on the posted data. if (!$this->_fieldValidate($data)) { $files = JRequest::getVar('filedata', array(), 'FILES'); $data['attachments'] = $files; DiscussHelper::storeSession($data, 'NEW_POST_TOKEN'); $app->redirect(DiscussRouter::getAskRoute(null, false)); } // get id if available $id = JRequest::getInt('id', 0); // bind the table $post = DiscussHelper::getTable('Post'); $post->load($id); // set is new value $isNew = !$post->id ? true : false; // If the post is edited and it doesn't have private the user might be switching from private -> non private if (!$isNew && !isset($data['private'])) { $post->private = false; } // Perform captcha validation $state = EDC::validateCaptcha($data); if (!$state) { // Store the data into the session EDC::storeSession($data, 'NEW_POST_TOKEN'); // Set error message EDC::setMessageQueue(JText::_('COM_EASYDISCUSS_INVALID_CAPTCHA'), DISCUSS_QUEUE_ERROR); if ($isNew) { $app->redirect(DiscussRouter::_('index.php?option=com_easydiscuss&view=ask', false)); } else { $app->redirect(DiscussRouter::_('index.php?option=com_easydiscuss&view=ask&id=' . $post->id, false)); } } $previousTags = array(); if (!$isNew) { //check if admin or is owner before allowing edit. $isMine = DiscussHelper::isMine($post->user_id); $isAdmin = DiscussHelper::isSiteAdmin(); $isEditor = $acl->allowed('edit_question'); if (!$my->id && !$isMine && !$isAdmin && !$isEditor) { DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_NO_PERMISSION_TO_PERFORM_THE_REQUESTED_ACTION'), DISCUSS_QUEUE_ERROR); $this->setRedirect(DiscussRouter::_('index.php?option=com_easydiscuss&view=post&id=' . $id, false)); return; } // If this is an edited post, we need to remove existing tags and add them back again. $postsTagsModel = $this->getModel('PostsTags'); $tmppreviousTags = $postsTagsModel->getPostTags($id); if (!empty($tmppreviousTags)) { foreach ($tmppreviousTags as $previoustag) { $previousTags[] = $previoustag->id; } } if ($acl->allowed('add_tag', '0')) { $postsTagsModel->deletePostTag($id); } } // Get raw content from request as we may need to respect the html codes. $content = JRequest::getVar('dc_reply_content', '', 'post', 'none', JREQUEST_ALLOWRAW); if (empty($content)) { // if there is no content from component, get from module quick question $content = JRequest::getVar('quick_question_reply_content', '', 'post', 'none', JREQUEST_ALLOWRAW); } // some joomla editor htmlentity the content before it send to server. so we need // to do the god job to fix the content. $content = DiscussHelper::getHelper('String ')->unhtmlentities($content); // Ensure that the posted content is respecting the correct values. $data['dc_reply_content'] = $content; // Cleanup alias. $alias = DiscussHelper::wordFilter($data['title']); $data['alias'] = DiscussHelper::getAlias($alias, 'post', $post->id); // Detect the poster type. $data['user_type'] = empty($my->id) ? 'guest' : 'member'; // Akismet configurations. if ($config->get('antispam_akismet') && $config->get('antispam_akismet_key')) { require_once DISCUSS_CLASSES . '/akismet.php'; $params = array($data['title'], $data['dc_reply_content']); foreach ($params as $param) { $akismet = new Akismet(DISCUSS_JURIROOT, $config->get('antispam_akismet_key'), array('author' => $my->name, 'email' => $my->email, 'website' => DISCUSS_JURIROOT, 'body' => urlencode($param), 'alias' => '')); // Detect if there's any errors in Akismet. if (!$akismet->errorsExist() && $akismet->isSpam()) { DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_AKISMET_SPAM_DETECTED'), DISCUSS_QUEUE_ERROR); $app->redirect(DiscussRouter::_('index.php?option=com_easydiscuss&view=ask', false)); return $app->close(); } } } // Get previous status before binding. $prevPostStatus = $post->published; // If post is being edited, do not change the owner of the item. if (!$post->id) { $data['user_id'] = !$post->user_id ? $my->id : $post->user_id; } // Check permission to modify assignee $category = DiscussHelper::getTable('Category'); $access = $post->getAccess($category); if ($access->canAssign()) { $assignment = DiscussHelper::getTable('PostAssignment'); $assignment->load($post->id); // Add new record if assignee was changed if (array_key_exists('assignee_id', $data) && $assignment->assignee_id != $data['assignee_id']) { $newAssignment = DiscussHelper::getTable('PostAssignment'); $newAssignment->post_id = $post->id; $newAssignment->assignee_id = (int) $data['assignee_id']; $newAssignment->assigner_id = (int) JFactory::getUser()->id; if (!$newAssignment->store()) { $ajax->fail('Storing failed'); return $ajax->send(); } } } $data['content_type'] = DiscussHelper::getEditorType('question'); // Bind posted data against the table. $post->bind($data, true); // Set all post to be published by default. $post->published = DISCUSS_ID_PUBLISHED; // Detect if post should be moderated. if ($config->get('main_moderatepost') && !DiscussHelper::isSiteAdmin($post->user_id) && !DiscussHelper::isModerateThreshold($post->user_id)) { $post->published = DISCUSS_ID_PENDING; } // Bind posted parameters such as custom tab contents. $post->bindParams($data); // Check for maximum length of content if category has specific settings. $category = DiscussHelper::getTable('Category'); $category->load($post->category_id); // If there's a maximum content length specified per category base, then we need to check against the content. if ($category->getParam('maxlength')) { $length = JString::strlen($post->content); if ($length > $category->getParam('maxlength_size', 1000)) { DiscussHelper::storeSession($data, 'NEW_POST_TOKEN'); DiscussHelper::setMessageQueue(JText::sprintf('COM_EASYDISCUSS_MAXIMUM_LENGTH_EXCEEDED', $category->getParam('maxlength_size', 1000)), DISCUSS_QUEUE_ERROR); $app->redirect(DiscussRouter::_('index.php?option=com_easydiscuss&view=ask', false)); return $app->close(); } } // If user tries to submit in a container, throw an error. if ($category->container) { DiscussHelper::storeSession($data, 'NEW_POST_TOKEN'); DiscussHelper::setMessageQueue(JText::_('COM_EASYDISCUSS_NOT_ALLOWED_TO_POST_INTO_CONTAINER'), DISCUSS_QUEUE_ERROR); $app->redirect(DiscussRouter::_('index.php?option=com_easydiscuss&view=ask', false)); return $app->close(); } // @trigger: onBeforeSave DiscussEventsHelper::importPlugin('content'); DiscussEventsHelper::onContentBeforeSave('post', $post, $isNew); // If password is disabled, do not allow users to set password. if (!$config->get('main_password_protection')) { $post->password = ''; } // Detect user's ip address. $ip = JRequest::getVar('REMOTE_ADDR', '', 'SERVER'); $post->ip = $ip; // Try to store the post object. if (!$post->store()) { DiscussHelper::setMessageQueue($post->getError(), DISCUSS_QUEUE_ERROR); $app->redirect(DiscussRouter::getAskRoute($category->id, false)); return $app->close(); } // API: References. $reference = JRequest::getWord('reference', ''); $referenceId = JRequest::getInt('reference_id', 0); if (!empty($reference) && !empty($referenceId)) { $referenceTable = DiscussHelper::getTable('PostsReference'); $referenceTable->extension = $reference; $referenceTable->post_id = $post->id; $referenceTable->reference_id = $referenceId; $referenceTable->store(); } //Clear off previous records before storing $ruleModel = DiscussHelper::getModel('CustomFields'); $ruleModel->deleteCustomFieldsValue($post->id, 'update'); // Process custom fields. $fieldIds = JRequest::getVar('customFields'); if (!empty($fieldIds)) { foreach ($fieldIds as $fieldId) { $fields = JRequest::getVar('customFieldValue_' . $fieldId); if (!empty($fields)) { // Cater for custom fields select list // To detect if there is no value selected for the select list custom fields if (in_array('defaultList', $fields)) { $tempKey = array_search('defaultList', $fields); $fields[$tempKey] = ''; } } $post->bindCustomFields($fields, $fieldId); } } // @trigger: onAfterSave DiscussEventsHelper::onContentAfterSave('post', $post, $isNew); // The category_id for the replies should change too $post->moveChilds($post->id, $post->category_id); // Process poll items. if ($config->get('main_polls')) { $polls = JRequest::getVar('pollitems'); if (!is_array($polls)) { $polls = array($polls); } // If the post is being edited and // there is only 1 poll item which is also empty, // we need to delete existing polls tied to this post. if (count($polls) == 1 && empty($polls[0]) && !$isNew) { $post->removePoll(); } if (count($polls) > 0) { $hasPolls = false; foreach ($polls as $poll) { // As long as there is 1 valid poll, we need to store them. if (!empty($poll)) { $hasPolls = true; break; } } if ($hasPolls) { // Check if the multiple polls checkbox is it checked? $multiplePolls = JRequest::getVar('multiplePolls', '0'); // Get the poll question here. $pollQuestion = JRequest::getVar('poll_question', ''); // Try to detect which poll items needs to be removed. $removePolls = JRequest::getVar('pollsremove'); // Get the poll items. $pollItems = JRequest::getVar('pollitems'); $pollItemsOri = JRequest::getVar('pollitemsOri'); // Store the polls now. $post->bindPolls($isNew, $pollItems, $removePolls, $multiplePolls, $pollQuestion, $pollItemsOri); } } } // Bind file attachments if ($acl->allowed('add_attachment') && $config->get('attachment_questions')) { $post->bindAttachments(); } // Detect if the current post should be moderated or not. $isModerate = $post->published == DISCUSS_ID_PENDING ? true : false; // Process auto posting for posts that are really published and is in a public category. if ($post->published == DISCUSS_ID_PUBLISHED && $category->canPublicAccess()) { $post->autopost(); } // Detect known names in the post. $names = DiscussHelper::getHelper('String')->detectNames($post->content); if ($names) { foreach ($names as $name) { $name = JString::str_ireplace('@', '', $name); $id = DiscussHelper::getUserId($name); if (!$id || $id == $post->get('user_id')) { continue; } $notification = DiscussHelper::getTable('Notifications'); $notification->bind(array('title' => JText::sprintf('COM_EASYDISCUSS_MENTIONED_QUESTION_NOTIFICATION_TITLE', $post->get('title')), 'cid' => $post->get('id'), 'type' => DISCUSS_NOTIFICATIONS_MENTIONED, 'target' => $id, 'author' => $post->get('user_id'), 'permalink' => 'index.php?option=com_easydiscuss&view=post&id=' . $post->get('id'))); $notification->store(); } } if (($isNew || $prevPostStatus == DISCUSS_ID_PENDING) && $post->published == DISCUSS_ID_PUBLISHED) { $post->ping(); } $notify = DiscussHelper::getNotification(); // badwords filtering for email data. $post->title = DiscussHelper::wordFilter($post->title); $post->content = DiscussHelper::wordFilter($post->content); if ($acl->allowed('add_tag', '0')) { //@task: Save tags $postTagModel = $this->getModel('PostsTags'); $tags = JRequest::getVar('tags', '', 'POST'); if (!empty($tags)) { $tagModel = $this->getModel('Tags'); foreach ($tags as $tag) { if (!empty($tag)) { $tagTable = DiscussHelper::getTable('Tags'); //@task: Only add tags if it doesn't exist. if (!$tagTable->exists($tag)) { $tagTable->set('title', JString::trim($tag)); $tagTable->set('alias', DiscussHelper::getAlias($tag, 'tag')); $tagTable->set('created', DiscussHelper::getDate()->toMySQL()); $tagTable->set('published', 1); $tagTable->set('user_id', $my->id); $tagTable->store(); } else { $tagTable->load($tag, true); } $postTagInfo = array(); //@task: Store in the post tag $postTagTable = DiscussHelper::getTable('PostsTags'); $postTagInfo['post_id'] = $post->id; $postTagInfo['tag_id'] = $tagTable->id; $postTagTable->bind($postTagInfo); $postTagTable->store(); } } } } // prepare email content and information. $profile = DiscussHelper::getTable('Profile'); $profile->load($my->id); // For use within the emails. $emailData = array(); $emailData['postTitle'] = $post->title; $emailData['postAuthor'] = $profile->id ? $profile->getName() : $post->poster_name; $emailData['postAuthorAvatar'] = $profile->getAvatar(); $emailData['postLink'] = DiscussRouter::getRoutedURL('index.php?option=com_easydiscuss&view=post&id=' . $post->id, false, true); $emailContent = $post->content; if ($post->content_type != 'html') { // the content is bbcode. we need to parse it. $emailContent = EasyDiscussParser::bbcode($emailContent); $emailContent = EasyDiscussParser::removeBrTag($emailContent); } // If post is html type we need to strip off html codes. if ($post->content_type == 'html') { $emailContent = strip_tags($post->content); } $emailContent = $post->trimEmail($emailContent); $attachments = $post->getAttachments(); $emailData['attachments'] = $attachments; $emailData['postContent'] = $emailContent; $emailData['post_id'] = $post->id; $emailData['cat_id'] = $post->category_id; $emailData['emailTemplate'] = 'email.subscription.site.new.php'; $emailData['emailSubject'] = JText::sprintf('COM_EASYDISCUSS_NEW_QUESTION_ASKED', $post->id, $post->title); if ($isModerate) { // Generate hashkeys to map this current request $hashkey = DiscussHelper::getTable('HashKeys'); $hashkey->uid = $post->id; $hashkey->type = DISCUSS_QUESTION_TYPE; $hashkey->store(); require_once DISCUSS_HELPERS . '/router.php'; $approveURL = DiscussHelper::getExternalLink('index.php?option=com_easydiscuss&controller=posts&task=approvePost&key=' . $hashkey->key); $rejectURL = DiscussHelper::getExternalLink('index.php?option=com_easydiscuss&controller=posts&task=rejectPost&key=' . $hashkey->key); $emailData['moderation'] = '<div style="display:inline-block;width:100%;padding:20px;border-top:1px solid #ccc;padding:20px 0 10px;margin-top:20px;line-height:19px;color:#555;font-family:\'Lucida Grande\',Tahoma,Arial;font-size:12px;text-align:left">'; $emailData['moderation'] .= '<a href="' . $approveURL . '" style="display:inline-block;padding:5px 15px;background:#fc0;border:1px solid #caa200;border-bottom-color:#977900;color:#534200;text-shadow:0 1px 0 #ffe684;font-weight:bold;box-shadow:inset 0 1px 0 #ffe064;-moz-box-shadow:inset 0 1px 0 #ffe064;-webkit-box-shadow:inset 0 1px 0 #ffe064;border-radius:2px;moz-border-radius:2px;-webkit-border-radius:2px;text-decoration:none!important">' . JText::_('COM_EASYDISCUSS_EMAIL_APPROVE_POST') . '</a>'; $emailData['moderation'] .= ' ' . JText::_('COM_EASYDISCUSS_OR') . ' <a href="' . $rejectURL . '" style="color:#477fda">' . JText::_('COM_EASYDISCUSS_REJECT') . '</a>'; $emailData['moderation'] .= '</div>'; $emailData['emailTemplate'] = 'email.subscription.site.moderate.php'; $emailData['emailSubject'] = JText::sprintf('COM_EASYDISCUSS_NEW_QUESTION_MODERATE', $post->id, $post->title); } else { // If this is a private post, do not notify anyone if (!$post->private && $category->canPublicAccess()) { // Notify site subscribers if ($config->get('main_sitesubscription') && ($isNew || $prevPostStatus == DISCUSS_ID_PENDING) && $post->published == DISCUSS_ID_PUBLISHED && !$config->get('notify_all')) { DiscussHelper::getHelper('Mailer')->notifySubscribers($emailData, array($my->email)); } // Notify category subscribers if ($config->get('main_ed_categorysubscription') && ($isNew || $prevPostStatus == DISCUSS_ID_PENDING) && $post->published == DISCUSS_ID_PUBLISHED && !$config->get('notify_all')) { DiscussHelper::getHelper('Mailer')->notifySubscribers($emailData, array($my->email)); } // Notify EVERYBODY if ($config->get('notify_all') && !$isModerate) { DiscussHelper::getHelper('Mailer')->notifyAllMembers($emailData, array($my->email)); } } } // Notify admins and category moderators if ($isNew || $prevPostStatus == DISCUSS_ID_PENDING) { DiscussHelper::getHelper('Mailer')->notifyAdministrators($emailData, array($my->email), $config->get('notify_admin'), $config->get('notify_moderator')); } // @rule: Jomsocial activity integrations & points & ranking if (($isNew || $prevPostStatus == DISCUSS_ID_PENDING) && $post->published == DISCUSS_ID_PUBLISHED && !$post->private) { DiscussHelper::getHelper('jomsocial')->addActivityQuestion($post); DiscussHelper::getHelper('easysocial')->createDiscussionStream($post); // Add notification to subscribers DiscussHelper::getHelper('easysocial')->notify('new.discussion', $post); // Add logging for user. DiscussHelper::getHelper('History')->log('easydiscuss.new.discussion', $my->id, JText::sprintf('COM_EASYDISCUSS_BADGES_HISTORY_NEW_POST', $post->title), $post->id); DiscussHelper::getHelper('Badges')->assign('easydiscuss.new.discussion', $my->id); DiscussHelper::getHelper('Points')->assign('easydiscuss.new.discussion', $my->id); // Assign badge for EasySocial DiscussHelper::getHelper('EasySocial')->assignBadge('create.question', $my->id, JText::sprintf('COM_EASYDISCUSS_BADGES_HISTORY_NEW_POST', $post->title)); // assign new ranks. DiscussHelper::getHelper('ranks')->assignRank($my->id, $config->get('main_ranking_calc_type')); // aup DiscussHelper::getHelper('Aup')->assign(DISCUSS_POINTS_NEW_DISCUSSION, $my->id, $post->title); } $message = $isNew ? JText::_('COM_EASYDISCUSS_POST_STORED') : JText::_('COM_EASYDISCUSS_EDIT_SUCCESS'); $state = 'success'; // Let's set our custom message here. if (!$post->isPending()) { DiscussHelper::setMessageQueue($message, $state); } $redirect = JRequest::getVar('redirect', ''); if (!empty($redirect)) { $redirect = base64_decode($redirect); return $this->setRedirect($redirect); } $redirectionOption = $config->get('main_post_redirection'); switch ($redirectionOption) { case 'default': $redirect = DiscussRouter::getPostRoute($post->id, false); break; case 'home': $redirect = DiscussRouter::_('index.php?option=com_easydiscuss&view=index', false); break; case 'mainCategory': $redirect = DiscussRouter::_('index.php?option=com_easydiscuss&view=categories', false); break; case 'currentCategory': $redirect = DiscussRouter::getCategoryRoute($post->category_id, false); break; default: $redirect = DiscussRouter::getPostRoute($post->id, false); break; } $this->setRedirect($redirect); }
function spamfilter($comment = null) { global $vars, $defaultpage; // Through if GET (Check only POST) if ($_SERVER['REQUEST_METHOD'] === 'GET') { return; } // Through if POST is from akismet plugin (submitHam) if (isset($vars['cmd']) && $vars['cmd'] == 'akismet') { return; } // Through if in IGNORE list $cmd = isset($vars['cmd']) ? $vars['cmd'] : (isset($vars['plugin']) ? $vars['plugin'] : 'read'); if (defined('PLUGIN_AKISMET_IGNORE_PLUGINS')) { if (in_array($cmd, explode(',', PLUGIN_AKISMET_IGNORE_PLUGINS))) { return; } } // Through if already known he is a human $use_authlevel = PLUGIN_AKISMET_THROUGH_IF_ENROLLEE ? ROLE_AUTH : (PLUGIN_AKISMET_THROUGH_IF_ADMIN ? ROLE_ADM_CONTENTS : 0); if (is_human(NULL, PLUGIN_AKISMET_USE_SESSION, $use_authlevel)) { return; } // Initialize $comment if (!isset($comment)) { // special case (now only supports edit plugin) if ($vars['cmd'] === 'edit' || $vars['plugin'] === 'edit') { $body = $vars['msg']; } else { $body = implode("\n", $vars); } $comment = array('author' => '', 'email' => '', 'website' => '', 'body' => $body, 'permalink' => '', 'user_ip' => $_SERVER['REMOTE_ADDR'], 'user_agent' => $_SERVER['HTTP_USER_AGENT']); } $is_spam = TRUE; if (PLUGIN_AKISMET_USE_AKISMET) { // Through if no body (Akismet recognizes as a spam if no body) if ($comment['body'] == '') { return; } // instantiate an instance of the class $akismet = new Akismet(get_script_uri(), PLUGIN_AKISMET_API_KEY, $comment); // test for errors if ($akismet->errorsExist()) { // returns TRUE if any errors exist if ($akismet->isError('AKISMET_INVALID_KEY')) { die_message('akismet : APIキーが不正です.'); } elseif ($akismet->isError('AKISMET_RESPONSE_FAILED')) { //die_message('akismet : レスポンスの取得に失敗しました'); } elseif ($akismet->isError('AKISMET_SERVER_NOT_FOUND')) { //die_message('akismet : サーバへの接続に失敗しました.'); } $is_spam = FALSE; // through if akismet.com is not available. } else { $is_spam = $akismet->isSpam(); } if ($is_spam) { $detail = PLUGIN_AKISMET_SPAMLOG_DETAIL ? $comment : array(); PluginAkismet::spamlog_write($vars, $detail, PLUGIN_AKISMET_SPAMLOG_FILENAME); } } if ($is_spam) { if (PLUGIN_AKISMET_RECAPTCHA_LOG) { PluginAkismet::spamlog_write($vars, array('body' => 'hit'), LOG_DIR . 'captchalog.txt'); } $form = PluginAkismet::get_captcha_form($vars, $comment); // die_message('</strong>' . $form . '<strong>'); $title = $page = 'キャプチャ認証'; pkwk_common_headers(); catbody($title, $page, $form); exit; } }
private function check_data($data, $save = false) { if ($this->comments_closed != false) { $this->errors[] = 'comment_error_closed'; } if (empty($this->errors) && $save) { if (empty($_SESSION[$this->_form_session])) { $this->errors[] = 'comment_error_invalid_request'; } else { if (time() - $_SESSION[$this->_form_session] < 2) { $this->errors[] = 'comment_error_too_fast'; } } } if (empty($this->errors)) { // check for not accepted words: $joined_message = mb_strtolower($data['name'] . ' ' . $data['email_hp'] . ' ' . $data['comment_text']); $not_accepted_words = get_not_accepted_words($joined_message); if ($not_accepted_words != false) { $not_accepted_words_listing = htmlspecialchars(implode(', ', $not_accepted_words)); if (count($not_accepted_words) == 1) { $this->errors[] = 'error_not_accepted_word'; #$this->assign_lang_placeholder('not_accepted_word', $not_accepted_words_listing, 'error_not_accepted_word'); $this->_localization->replacePlaceholder('not_accepted_word', $not_accepted_words_listing, 'error_not_accepted_word'); } else { $this->errors[] = 'error_not_accepted_words'; #$this->assign_lang_placeholder('not_accepted_words', $not_accepted_words_listing, 'error_not_accepted_words'); $this->_localization->replacePlaceholder('not_accepted_words', $not_accepted_words_listing, 'error_not_accepted_words'); } } if (empty($data['name'])) { $this->errors[] = 'comment_error_no_name'; } if (empty($data['comment_text'])) { $this->errors[] = 'comment_error_no_text'; } if (mb_strlen($data['name']) > $this->name_maxlength) { $this->errors[] = 'comment_error_name_too_long'; } if (mb_strlen($data['email_hp']) > $this->email_hp_maxlength) { $this->errors[] = 'comment_error_email_hp_too_long'; } if (!empty($data['email_hp'])) { if (strpos($data['email_hp'], ' ') !== false || strpos($data['email_hp'], '.') === false) { $this->errors[] = 'comment_error_email_hp_invalid'; } } if (mb_strlen($data['comment_text']) > $this->comment_maxlength) { $text_length = mb_strlen($data['comment_text']); $this->errors[] = 'comment_error_text_too_long'; $this->_localization->replacePlaceholder('characters', $text_length, 'comment_error_text_too_long'); $this->_localization->replacePlaceholder('max_characters', $this->comment_maxlength, 'comment_error_text_too_long'); } } if (empty($this->errors)) { if ($too_long_words = too_long_words(strip_tags($this->format_comment($data['comment_text'])), $this->word_maxlength)) { foreach ($too_long_words as $too_long_word) { $stripped_too_long_words[] = htmlspecialchars(mb_substr($too_long_word, 0, $this->word_maxlength)) . '...'; } $too_long_words_listing = implode(', ', $stripped_too_long_words); if (count($too_long_words) == 1) { $this->errors[] = 'comment_error_too_long_word'; #$this->assign_lang_placeholder('word', $too_long_words_listing, 'comment_error_too_long_word'); $this->_localization->replacePlaceholder('word', $too_long_words_listing, 'comment_error_too_long_word'); } else { $this->errors[] = 'comment_error_too_long_words'; #$this->assign_lang_placeholder('words', $too_long_words_listing, 'comment_error_too_long_words'); $this->_localization->replacePlaceholder('words', $too_long_words_listing, 'comment_error_too_long_words'); } } // check for double and repeated entries: $dbr = Database::$entries->prepare("SELECT COUNT(*) FROM " . Database::$db_settings['comment_table'] . " WHERE time>:time AND comment_id=:comment_id AND name=:name AND email_hp=:email_hp AND comment=:comment"); $time = time() - 300; // last 5 minutes $dbr->bindParam(':time', $time, PDO::PARAM_INT); $dbr->bindParam(':comment_id', $this->comment_id, PDO::PARAM_INT); $dbr->bindParam(':name', $data['name'], PDO::PARAM_STR); $dbr->bindParam(':email_hp', $data['email_hp'], PDO::PARAM_STR); $dbr->bindParam(':comment', $data['comment_text'], PDO::PARAM_STR); $dbr->execute(); if ($dbr->fetchColumn() > 0) { $this->errors[] = 'comment_error_entry_exists'; } if ($this->prevent_repeated_posts_minutes > 0) { $dbr = Database::$entries->prepare("SELECT COUNT(*) FROM " . Database::$db_settings['comment_table'] . " WHERE time>:time AND comment_id=:comment_id AND ip=:ip"); $time = time() - $this->prevent_repeated_posts_minutes * 60; $dbr->bindParam(':time', $time, PDO::PARAM_INT); $dbr->bindParam(':comment_id', $this->comment_id, PDO::PARAM_INT); $dbr->bindParam(':ip', $_SERVER["REMOTE_ADDR"], PDO::PARAM_STR); $dbr->execute(); if ($dbr->fetchColumn() > 0) { $this->errors[] = 'comment_error_repeated_post'; } } if ($save) { // Akismet spam check: if ($this->akismet_key != '' && $this->akismet_entry_check == 1) { #require('./cms/modules/akismet/akismet.class.php'); $check_posting['author'] = $data['name']; if ($data['email_hp'] != '') { if (preg_match("/^[^@]+@.+\\.\\D{2,5}\$/", $email_hp)) { $check_posting['email'] = $data['email_hp']; } else { $check_posting['website'] = $data['email_hp']; } } $check_posting['body'] = $data['comment_text']; $akismet = new Akismet(BASE_URL, $this->akismet_key, $check_posting); // test for errors if ($akismet->errorsExist()) { if ($akismet->isError(AKISMET_INVALID_KEY)) { $this->errors[] = 'akismet_error_api_key'; } elseif ($akismet->isError(AKISMET_RESPONSE_FAILED)) { $this->errors[] = 'akismet_error_connection'; } elseif ($akismet->isError(AKISMET_SERVER_NOT_FOUND)) { $this->errors[] = 'akismet_error_connection'; } } else { // No errors, check for spam if ($akismet->isSpam()) { $this->errors[] = 'akismet_spam_suspicion'; } } } } // end if($save) } }