function sendQueue($pQueueMixed) { global $gBitSmarty, $gBitSystem, $gBitLanguage; static $body = array(); if (is_array($pQueueMixed)) { $pick = $pQueueMixed; } elseif (is_numeric($pQueueMixed)) { $pick = $this->mDb->GetRow("SELECT * FROM `" . BIT_DB_PREFIX . "mail_queue` mq WHERE `mail_queue_id` = ? " . $this->mDb->SQLForUpdate(), array($pQueueMixed)); } if (!empty($pick)) { $startTime = microtime(TRUE); $this->mDb->query("UPDATE `" . BIT_DB_PREFIX . "mail_queue` SET `begin_date`=? WHERE `mail_queue_id` = ? ", array(time(), $pick['mail_queue_id'])); if (!empty($pick['user_id'])) { $userHash = $this->mDb->getRow("SELECT * FROM `" . BIT_DB_PREFIX . "users_users` WHERE `user_id`=?", array($pick['user_id'])); $pick['full_name'] = BitUser::getDisplayName(FALSE, $userHash); } else { $pick['full_name'] = NULL; } if (!isset($body[$pick['content_id']])) { $gBitSmarty->assign('sending', TRUE); // We only support sending of newsletters currently $content = new BitNewsletterEdition(NULL, $pick['content_id']); if ($content->load()) { $body[$pick['content_id']]['body'] = $content->render(); $body[$pick['content_id']]['subject'] = $content->getTitle(); $body[$pick['content_id']]['reply_to'] = $content->getField('reply_to', $gBitSystem->getConfig('site_sender_email', $_SERVER['SERVER_ADMIN'])); $body[$pick['content_id']]['object'] = $content; } else { bit_error_log($this->mErrors); } // $content[$pick['content_id']] = LibertyBase::getLibertyObject(); } print "[ {$pick['mail_queue_id']} ] {$pick['content_id']} TO: {$pick['email']}\t"; $unsub = $this->getUnsubscription($pick['email'], $pick['nl_content_id']); if (!empty($unsub)) { print " SKIPPED (unsubscribed) <br/>\n"; $this->mDb->query("DELETE FROM `" . BIT_DB_PREFIX . "mail_queue` WHERE `mail_queue_id`=?", array($pick['mail_queue_id'])); } elseif (!empty($body[$pick['content_id']])) { $pick['url_code'] = md5($pick['content_id'] . $pick['email'] . $pick['queue_date']); $unsub = ''; if ($body[$pick['content_id']]['object']->mNewsletter->getField('unsub_msg')) { $gBitSmarty->assign('url_code', $pick['url_code']); } $gBitSystem->preDisplay(''); $gBitSmarty->assign('sending', TRUE); $gBitSmarty->assign('unsubMessage', $unsub); $gBitSmarty->assign('trackCode', $pick['url_code']); $gBitSmarty->assign('mid', 'bitpackage:newsletters/view_edition.tpl'); $htmlBody = $gBitSmarty->fetch('bitpackage:newsletters/mail_edition.tpl'); $htmlBody = bit_add_clickthrough($htmlBody, $pick['url_code']); $mailer = new PHPMailer(); if ($gBitSystem->getConfig('bitmailer_errors_to')) { $mailer->Sender = $gBitSystem->getConfig('bitmailer_errors_to'); $mailer->addCustomHeader("Errors-To: " . $gBitSystem->getConfig('bitmailer_errors_to')); } $mailer->From = $gBitSystem->getConfig('bitmailer_sender_email', $gBitSystem->getConfig('site_sender_email', $_SERVER['SERVER_ADMIN'])); $mailer->FromName = $gBitSystem->getConfig('bitmailer_from', $gBitSystem->getConfig('site_title')); $mailer->Host = $gBitSystem->getConfig('bitmailer_servers', $gBitSystem->getConfig('kernel_server_name', '127.0.0.1')); $mailer->Mailer = $gBitSystem->getConfig('bitmailer_protocol', 'smtp'); // Alternative to IsSMTP() $mailer->CharSet = 'UTF-8'; if ($gBitSystem->getConfig('bitmailer_smtp_username')) { $mailer->SMTPAuth = TRUE; $mailer->Username = $gBitSystem->getConfig('bitmailer_smtp_username'); } if ($gBitSystem->getConfig('bitmailer_smtp_password')) { $mailer->Password = $gBitSystem->getConfig('bitmailer_smtp_password'); } $mailer->WordWrap = $gBitSystem->getConfig('bitmailer_word_wrap', 75); if (!$mailer->SetLanguage($gBitLanguage->getLanguage(), UTIL_PKG_PATH . 'phpmailer/language/')) { $mailer->SetLanguage('en'); } $mailer->ClearReplyTos(); $mailer->AddReplyTo($body[$pick['content_id']]['reply_to'], $gBitSystem->getConfig('bitmailer_from')); $mailer->Body = $htmlBody; $mailer->Subject = $body[$pick['content_id']]['subject']; $mailer->IsHTML(TRUE); $mailer->AltBody = ''; $mailer->AddAddress($pick['email'], $pick["full_name"]); if ($mailer->Send()) { print " SENT " . round(microtime(TRUE) - $startTime, 2) . " secs<br/>\n"; flush(); $updateQuery = "UPDATE `" . BIT_DB_PREFIX . "mail_queue` SET `sent_date`=?,`url_code`=? WHERE `content_id`=? AND `email`=?"; $this->mDb->query($updateQuery, array(time(), $pick['url_code'], $pick['content_id'], $pick['email'])); } else { $updateQuery = "UPDATE `" . BIT_DB_PREFIX . "mail_queue` SET `mail_error`=?,`sent_date`=? WHERE `content_id`=? AND `email`=?"; $this->mDb->query($updateQuery, array($mailer->ErrorInfo, time(), $pick['content_id'], $pick['email'])); $pick['error'] = $mailer->ErrorInfo; $this->logError($pick); } } } }
/** * Sends an email to the specified recipients. * This is a convenience method for packages * to be able to use the email sending features * found in this package. * * $pSubject - The Subject of the Email * $pBody - The Body of the Email * $pRecipients - An associative array with keys for email and optionally login and real_name **/ function sendEmail($pSubject, $pBody, $pRecipients, $pHeaders = array()) { global $gBitSystem; $message = $pHeaders; $message['subject'] = $pSubject; if (is_string($pBody)) { $message['message'] = $pBody; } elseif (is_array($pBody)) { $message = array_merge($message, $pBody); } $mailer = $this->buildMailer($message); if (is_string($pRecipients)) { $pRecipients = array(array('email' => $pRecipients)); } foreach ($pRecipients as $to) { if (!empty($to['email'])) { if (isset($to['real_name']) || isset($to['login'])) { $mailer->AddAddress($to['email'], empty($to['real_name']) ? $to['login'] : $to['real_name']); } else { $mailer->AddAddress($to['email']); } if (!$mailer->Send()) { bit_error_log($mailer->ErrorInfo); } $mailer->ClearAddresses(); } } return $mailer->MessageID; }
function verifyPayment(&$pParamHash) { global $gBitUser; if (parent::verifyPayment($pParamHash)) { $sql = "SELECT cop.`orders_products_id`, cop.`products_commission` * cop.`products_quantity` AS products_commissions_total\n\t\t\t\t\tFROM " . TABLE_ORDERS . " co \n\t\t\t\t\t\tINNER JOIN\t" . TABLE_ORDERS_PRODUCTS . " cop ON (co.`orders_id`=cop.`orders_id`)\n\t\t\t\t\t\tINNER JOIN\t" . TABLE_PRODUCTS . " cp ON (cp.`products_id`=cop.`products_id`)\n\t\t\t\t\t\tINNER JOIN `" . BIT_DB_PREFIX . "liberty_content` lc ON (cp.`content_id`=lc.`content_id`)\n\t\t\t\t\tWHERE lc.`user_id`=? AND co.`date_purchased` > ? AND co.`date_purchased` <= ?"; $payedProducts = $this->mDb->getAssoc($sql, array($pParamHash['payment_store']['payee_user_id'], $pParamHash['payment_store']['period_start_date'], $pParamHash['payment_store']['period_end_date'])); $totalPayed = 0; foreach ($payedProducts as $ordersProductsId => $productsCommissionsTotal) { $this->mDb->query("UPDATE " . TABLE_ORDERS_PRODUCTS . " SET `commissions_payments_id`=? WHERE `orders_products_id`=?", array($pParamHash['commissions_payments_id'], $ordersProductsId)); $totalPayed += $productsCommissionsTotal; } if ((int) $totalPayed != (int) $pParamHash['payment_amount']) { $this->mErrors['commissions_payment'] = "Payment amount is not equal to products commissions ({$totalPayed} != {$pParamHash['payment_amount']} user " . $pParamHash['payment_store']['payee_user_id'] . ")"; bit_error_log($this->mErrors['commissions_payment']); } } return count($this->mErrors) == 0; }
/** * Sends an email to the specified recipients. * * @param array $pParamHash Array of message to be sent * * @param array $pParamHash['subject'] A string the message subject * @param array $pParamHash['message'] A HTML string or array of strings, the message itself aka body * @param array $pParamHash['alt_message'] A plain text string, the message itself * @param array $pParamHash['headers'] An Array of headers * @param array $pParamHash['recipients'] An Array of recipients, where each recipient is an array with key value pair of 'email' => emailaddress **/ function transport_email_send(&$pParamHash) { // convenience $headers = !empty($pParamHash['headers']) ? $pParamHash['headers'] : array(); $subject = $pParamHash['subject']; $body = !empty($pParamHash['message']) ? $pParamHash['message'] : NULL; $recipients = $pParamHash['recipients']; // assemble the email $message = $headers; $message['subject'] = $subject; if (is_string($body)) { $message['message'] = $body; } elseif (is_array($body)) { $message = array_merge($message, $body); } $message['alt_message'] = !empty($pParamHash['alt_message']) ? $pParamHash['alt_message'] : NULL; $mailer = transport_email_build_mailer($message); // Set these so the caller can know who the created mail(s) will appear to have come from $pParamHash['from'] = $mailer->From; $pParamHash['fromName'] = $mailer->FromName; // prep recipients if (is_string($recipients)) { $recipients = array(array('email' => $recipients)); } /* Send each message one by one. */ foreach ($recipients as $to) { if (!empty($to['email'])) { if (isset($to['real_name']) || isset($to['login'])) { $mailer->AddAddress($to['email'], empty($to['real_name']) ? $to['login'] : $to['real_name']); } else { $mailer->AddAddress($to['email']); } // send if (!$mailer->Send()) { bit_error_log($mailer->ErrorInfo); } $mailer->ClearAddresses(); } } // return a tracking value return $mailer->MessageID; }
function mime_default_verify(&$pStoreRow) { global $gBitSystem, $gBitUser; $ret = FALSE; // if we have a user_id set, we use that. if (!empty($pStoreRow['upload']['user_id'])) { $pStoreRow['user_id'] = $pStoreRow['upload']['user_id']; } else { // storage is always owned by the user that uploaded it! // er... or at least admin if somehow we have a NULL mUserId $pStoreRow['user_id'] = @BitBase::verifyId($gBitUser->mUserId) ? $gBitUser->mUserId : ROOT_USER_ID; if ($pStoreRow['user_id'] < 2) { bit_error_log('The user_id for the upload was not set. Defaulted to user_id = ' . $pStoreRow['user_id'] . ' where 1 = ROOT_USER_ID, -1 = ANONYMOUS_USER_ID, other values = big problem.'); } } if (!empty($pStoreRow['upload']['tmp_name']) && is_file($pStoreRow['upload']['tmp_name'])) { // attachment_id is only set when we are updating the file if (@BitBase::verifyId($pStoreRow['upload']['attachment_id'])) { // if a new file has been uploaded, we need to get some information from the database for the file update $fileInfo = $gBitSystem->mDb->getRow("\n\t\t\t\t\tSELECT la.`attachment_id`, lf.`file_id`, lf.`file_name`\n\t\t\t\t\tFROM `" . BIT_DB_PREFIX . "liberty_attachments` la\n\t\t\t\t\tINNER JOIN `" . BIT_DB_PREFIX . "liberty_files` lf ON ( lf.`file_id` = la.`foreign_id` )\n\t\t\t\t\tWHERE la.`attachment_id` = ?", array($pStoreRow['upload']['attachment_id'])); $pStoreRow = array_merge($pStoreRow, $fileInfo); } else { $pStoreRow['attachment_id'] = $gBitSystem->mDb->GenID('liberty_attachments_id_seq'); } // try to generate thumbnails for the upload if (isset($pStoreRow['upload']['thumbnail'])) { $pStoreRow['upload']['thumbnail'] = $pStoreRow['upload']['thumbnail']; } else { $pStoreRow['upload']['thumbnail'] = TRUE; } // Generic values needed by the storing mechanism $pStoreRow['upload']['source_file'] = $pStoreRow['upload']['tmp_name']; // Store all uploaded files in the users storage area if (empty($pStoreRow['upload']['dest_branch'])) { $pStoreRow['upload']['dest_branch'] = liberty_mime_get_storage_branch(array('sub_dir' => $pStoreRow['attachment_id'], 'user_id' => $pStoreRow['user_id'], 'package' => liberty_mime_get_storage_sub_dir_name($pStoreRow['upload']))); } $ret = TRUE; } else { $pStoreRow['errors']['upload'] = tra('There was a problem verifying the uploaded file.'); } return $ret; }
function spamurai_content_verify($pObject, $pParamHash) { global $gBitUser, $gBitSystem; // hardcode limit spamurai to BitBlogPost and BitUser. more enterprising person can write some cool admin config. // for now, these are the limits cause doing everything is slow and produces many false positives for content with limited text if ($gBitSystem->isPackageActive('spamurai') && !$gBitUser->hasPermission('p_spamurai_moderate') && (is_a($pObject, 'LibertyComment') || is_a($pObject, 'BitBlogPost') || is_a($pObject, 'BitUser'))) { $akismet = new Akismet(BOARDS_PKG_URI, $gBitSystem->getConfig('spamurai_api_key')); if (!empty($pParamHash) && !empty($akismet)) { $userInfo = $gBitUser->getUserInfo(array('user_id' => $pParamHash['user_id'])); $akismet->setCommentAuthor($userInfo['real_name'] . $userInfo['login']); $akismet->setCommentAuthorEmail($userInfo['email']); $checkTitle = ''; if (!empty($pParamHash['title'])) { $checkTitle .= $pParamHash['title']; } if (!empty($pParamHash['comment_title'])) { $checkTitle .= $pParamHash['comment_title']; } $checkString = ''; if (!empty($pParamHash['edit'])) { $checkString .= $pParamHash['edit']; } if (!empty($pParamHash['comment_data'])) { $checkString .= $pParamHash['comment_data']; } if (!empty($checkString) || !empty($checkTitle)) { $akismet->setCommentContent($checkTitle . $checkString); if ($akismet->isCommentSpam()) { if ($gBitUser->isRegistered()) { bit_error_log('SPAM ' . $pObject->getContentType() . ' for user ' . $userInfo['user_id']); } $insertSql = "INSERT INTO " . BIT_DB_PREFIX . "spamurai_log (user_id, email, subject, data, posted_date, ip) VALUES ( ?, ?, ?, ?, ?, ? )"; $bindVars = array($pParamHash['user_id'], $userInfo['email'], substr($checkTitle, 0, 255), $checkString, time(), $_SERVER['REMOTE_ADDR']); $gBitSystem->mDb->query($insertSql, $bindVars); $pObject->mErrors['spam'] = "This comment has been blocked as spam"; } } } } }
/** * $pMsgHeader is a imap_headerinfo generated array **/ function board_sync_process_message($pMbox, $pMsgNum, $pMsgHeader, $pMsgStructure, $pModerate = FALSE, $pLog = FALSE, $pDeliveredTo = NULL) { global $gBitSystem, $gBitDb; // vd( $pMsgHeader ); // Collect a bit of header information $message_id = board_sync_get_headerinfo($pMsgHeader, 'message_id'); // @TODO comment or clean up, not sure why this is here -wjames5 if (empty($message_id)) { $message_id = board_sync_get_headerinfo($pMsgHeader, 'message_id'); } $subject = board_sync_get_headerinfo($pMsgHeader, 'Subject'); if (empty($message_id)) { bit_error_log("Email sync for message: " . $subject . " failed: No Message Id in mail header."); } else { if ($pLog) { print "Processing: " . $message_id . "\n"; } if ($pLog) { print " Subject: " . $subject . "\n"; } $matches = array(); $toAddresses = array(); $allRecipients = ""; if (empty($pDeliveredTo)) { if (isset($pMsgHeader->toaddress)) { $allRecipients .= $pMsgHeader->toaddress; if ($pLog) { print " To addresses: " . $pMsgHeader->toaddress . "\n"; } } if (isset($pMsgHeader->ccaddress)) { $allRecipients .= ($allRecipients != "" ? "," : "") . $pMsgHeader->ccaddress; if ($pLog) { print " CC addresses: " . $pMsgHeader->ccaddress . "\n"; } } if ($pLog) { print " All Recipients: " . $allRecipients . "\n"; } $allSplit = split(',', $allRecipients); foreach ($allSplit as $s) { $s = trim($s); $matches = array(); if (strpos($s, '<') !== FALSE) { if (preg_match("/\\s*(.*)\\s*<\\s*(.*)\\s*>/", $s, $matches)) { $toAddresses[] = array('name' => $matches[1], 'email' => $matches[2]); } elseif (preg_match('/<\\s*(.*)\\s*>\\s*(.*)\\s*/', $s, $matches)) { $toAddresses[] = array('email' => $matches[1], 'name' => $matches[2]); } } elseif (validate_email_syntax($s)) { $toAddresses[] = array('email' => $s); } } } else { foreach ($pDeliveredTo as $address) { $toAddresses[] = array('email' => $address); } } if ($pLog) { print_r($toAddresses); } $date = board_sync_get_headerinfo($pMsgHeader, 'Date'); $from = board_sync_get_headerinfo($pMsgHeader, 'from'); $fromaddress = $from[0]->mailbox . "@" . $from[0]->host; // personal is not always defined. if (isset($from[0]->personal)) { $personal = ucwords($from[0]->personal); } else { $personal = null; } $in_reply_to = board_sync_get_headerinfo($pMsgHeader, 'in_reply_to'); if ($pLog) { print "\n---- " . date("Y-m-d HH:mm:ss") . " -------------------------\nImporting: " . $message_id . "\nDate: " . $date . "\nFrom: " . $fromaddress . "\nTo: " . $allRecipients . "\nSubject: " . $subject . "\nIn Reply To: " . $in_reply_to . "\nName: " . $personal . (is_array($pDeliveredTo) ? "\nDelivered-To:" . implode(", ", $pDeliveredTo) : '') . "\n"; } foreach ($toAddresses as $to) { if ($pLog) { print " Processing email: " . strtolower($to['email']) . "\n"; } // get a board match for the email address if ($boardContentId = cache_check_content_prefs('board_sync_list_address', strtolower($to['email']), TRUE)) { if ($pLog) { print "Found Board Content {$boardContentId} for {$to['email']}\n"; } // Do we already have this message in this board? $contentId = NULL; if ($message_id != NULL) { $sql = "SELECT `content_id` FROM `" . BIT_DB_PREFIX . "liberty_comments` WHERE `message_guid`=? AND `root_id`=?"; $contentId = $gBitDb->getOne($sql, array($message_id, $boardContentId)); } if (empty($contentId)) { if (!empty($in_reply_to)) { if ($parent = $gBitDb->GetRow("SELECT `content_id`, `root_id` FROM `" . BIT_DB_PREFIX . "liberty_comments` WHERE `message_guid`=?", array($in_reply_to))) { $replyId = $parent['content_id']; $rootId = $parent['root_id']; } else { if ($pLog) { print "WARNING: Reply to unfound message: " . $in_reply_to; } $replyId = $boardContentId; $rootId = $boardContentId; } // if no reply to message guid then match on title - this looks dangerous as titles could easily be duplicated -wjames } elseif ($parent = $gBitDb->GetRow("SELECT lcom.`content_id`, lcom.`root_id` FROM `" . BIT_DB_PREFIX . "liberty_comments` lcom INNER JOIN `" . BIT_DB_PREFIX . "liberty_content` lc ON(lcom.`content_id`=lc.`content_id`) WHERE lc.`title`=?", array(preg_replace('/re: /i', '', $subject)))) { $replyId = $parent['content_id']; $rootId = $parent['root_id']; // attach to board as first level comment e.g. new topic } else { $replyId = $boardContentId; $rootId = $boardContentId; } $userInfo = board_sync_get_user($fromaddress); // prep the storage hash $storeRow = array(); $storeRow['created'] = strtotime($date); $storeRow['last_modified'] = $storeRow['created']; $storeRow['user_id'] = $userInfo['user_id']; $storeRow['modifier_user_id'] = $userInfo['user_id']; $storeRow['title'] = $subject; $storeRow['message_guid'] = $message_id; if ($userInfo['user_id'] == ANONYMOUS_USER_ID && !empty($personal)) { $storeRow['anon_name'] = $personal; } $storeRow['root_id'] = $rootId; $storeRow['parent_id'] = $replyId; $partHash = array(); switch ($pMsgStructure->type) { case '0': if ($pLog) { print "Structure Type: text\n"; } board_parse_msg_parts($partHash, $pMbox, $pMsgNum, $pMsgStructure, 1, $pLog); break; case '1': if ($pLog) { print "Structure Type: multipart\n"; } if ($pModerate) { $prefix = '2.'; } else { $prefix = ''; } foreach ($pMsgStructure->parts as $partNum => $part) { board_parse_msg_parts($partHash, $pMbox, $pMsgNum, $part, $prefix . ($partNum + 1), $pLog); } break; } $plainBody = ""; $htmlBody = ""; foreach (array_keys($partHash) as $i) { if (!empty($partHash[$i]['plain'])) { $plainBody .= $partHash[$i]['plain']; } if (!empty($partHash[$i]['html'])) { $htmlBody .= $partHash[$i]['html']; } if (!empty($partHash[$i]['attachment'])) { $storeRow['_files_override'][] = array('tmp_name' => $partHash[$i]['attachment'], 'type' => $gBitSystem->verifyMimeType($partHash[$i]['attachment']), 'size' => filesize($partHash[$i]['attachment']), 'name' => basename($partHash[$i]['attachment']), 'user_id' => $userInfo['user_id']); } } if (!empty($htmlBody)) { $storeRow['edit'] = $htmlBody; $storeRow['format_guid'] = 'bithtml'; } elseif (!empty($plainBody)) { $storeRow['edit'] = nl2br($plainBody); $storeRow['format_guid'] = 'bithtml'; } // Nuke all email addresses from the body. if (!empty($storeRow['edit'])) { $storeRow['edit'] = ereg_replace('[-!#$%&\\`*+\\./0-9=?A-Z^_`a-z{|}~]+' . '@' . '(localhost|[-!$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\\.' . '[-!$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+)', '', $storeRow['edit']); } // We trust the user from this source // and count on moderation to handle links global $gBitUser; $gBitUser->setPermissionOverride('p_liberty_trusted_editor', true); // Check to add attachments // NOTE: we temporarily change the gBitUser here! // This is so we can run a proper content permissions check // for attachment permission against the parent // board object. This is sort of a hack to deal // with the fact that LibertyContent does not have a // means to check the permissions of any user except gBitUser -wjames5 // Important store a reference so we can switch back when we are done $gBitUserOrg = $gBitUser; // Load the message sending user if ($userInfo['user_id'] != ANONYMOUS_USER_ID) { $userClass = $gBitSystem->getConfig('user_class', 'BitPermUser'); $newBitUser = new $userClass($userInfo['user_id']); $newBitUser->load(TRUE); } if (!empty($newBitUser) && $newBitUser->isValid()) { // flip gBitUser to our message sender $gBitUser = $newBitUser; } // Load the parent board $board = new BitBoard(NULL, $boardContentId); $board->load(); // Check the permission for the user on the board if ($gBitSystem->isFeatureActive('comments_allow_attachments') && $board->hasUserPermission('p_liberty_attach_attachments')) { // note we grant the permission to the anonymous user which will become gBitUser once again $gBitUserOrg->setPermissionOverride('p_liberty_attach_attachments', true); } // Clear the reference to this board so we dont mistakenly use it later unset($board); // Important: switch gBitUser back! $gBitUser = $gBitUserOrg; // End check to add attachments to comments to the parent board // Check for an empty body // Duplicate subject if we have it if (empty($storeRow['edit'])) { if (!empty($storeRow['title'])) { $storeRow['edit'] = $storeRow['title']; } else { $storeRow['edit'] = "."; } } $storeComment = new LibertyComment(NULL); $gBitDb->StartTrans(); if ($storeComment->storeComment($storeRow)) { // undo the attachment permission $gBitUser->setPermissionOverride('p_liberty_attach_attachments', false); // set moderation approval if (!$pModerate && $gBitSystem->isPackageActive('moderation') && $gBitSystem->isPackageActive('modcomments')) { global $gModerationSystem, $gBitUser; $moderation = $gModerationSystem->getModeration(NULL, $storeComment->mContentId); if (!empty($moderation)) { // Allow to moderate $gBitUser->setPermissionOverride('p_admin', TRUE); $gModerationSystem->setModerationReply($moderation['moderation_id'], MODERATION_APPROVED); $gBitUser->setPermissionOverride('p_admin', FALSE); } } if (!empty($storeRow['message_guid'])) { // map the message guid to the comment $storeComment->mDb->query("UPDATE `" . BIT_DB_PREFIX . "liberty_comments` SET `message_guid`=? WHERE `content_id`=?", array($storeRow['message_guid'], $storeComment->mContentId)); // Store the confirm code if ($pModerate) { $storeComment->storePreference('board_confirm_code', $pModerate); } // done $gBitDb->CompleteTrans(); return TRUE; } else { bit_error_log("Email sync error: Message Id not set. You shouldn't have even gotten this far."); $gBitDb->RollbackTrans(); return FALSE; } } else { if (count($storeComment->mErrors) == 1 && !empty($storeComment->mErrors['store']) && $storeComment->mErrors['store'] == 'Duplicate comment.') { return TRUE; } else { foreach ($storeComment->mErrors as $error) { bit_error_log($error); } $gBitDb->RollbackTrans(); return FALSE; } } } else { if ($pLog) { print "Message Exists: {$contentId} : {$boardContentId} : {$message_id} : {$pModerate}\n"; } // If this isn't a moderation message if ($pModerate === FALSE) { // If the message exists it must have been approved via some // moderation mechanism, so make sure it is available if ($gBitSystem->isPackageActive('moderation') && $gBitSystem->isPackageActive('modcomments')) { global $gModerationSystem, $gBitUser; $storeComment = new LibertyComment(NULL, $contentId); $storeComment->loadComment(); if ($storeComment->mInfo['content_status_id'] > 0) { if ($pLog) { print "Already approved: {$contentId}\n"; } } else { $moderation = $gModerationSystem->getModeration(NULL, $contentId); // vd($moderation); if (!empty($moderation)) { $gBitUser->setPermissionOverride('p_admin', TRUE); if ($pLog) { print "Setting approved: {$contentId}\n"; } $gModerationSystem->setModerationReply($moderation['moderation_id'], MODERATION_APPROVED); $gBitUser->setPermissionOverride('p_admin', FALSE); if ($pLog) { print "Done"; } } else { if ($pLog) { print "ERROR: Unable to find moderation to approve for: {$contentId}"; } } } } } else { // Store the approve code; if ($pLog) { print "Storing approval code: " . $contentId . ":" . $pModerate . "\n"; } $storeComment = new LibertyComment(NULL, $contentId); $storeComment->storePreference('board_confirm_code', $pModerate); } return TRUE; } } else { if ($pLog) { print "No Board match found for {$to['email']}\n"; } } } } return FALSE; }
} } elseif (!empty($_REQUEST['save_attribute'])) { $productManager->storeOptionsValue($_REQUEST, $_FILES); bit_redirect(BITCOMMERCE_PKG_URL . 'admin/products_options.php'); } elseif (!empty($_REQUEST['save_attribute_map'])) { $gBitProduct->expungeAllAttributes(); if (!empty($_REQUEST['products_options'])) { foreach ($_REQUEST['products_options'] as $optionId) { $gBitProduct->storeAttributeMap($optionId); } } bit_redirect(BITCOMMERCE_PKG_URL . 'admin/products_options.php?products_id=' . $gBitProduct->getField('products_id')); } elseif (!empty($_REQUEST['save_option'])) { if ($productManager->storeOption($_REQUEST, $_FILES)) { bit_redirect(BITCOMMERCE_PKG_URL . 'admin/products_options.php'); } else { bit_error_log('option store failed'); bit_error_log($_REQUEST); } } $listHash = array(); $groups = $gBitUser->getAllGroups($listHash); $groupList[] = ''; foreach ($groups as $group) { $groupList[$group['group_id']] = $group['group_name']; } $gBitSmarty->assign_by_ref('groupList', $groupList); if (!empty($editTpl)) { $gBitSmarty->assign_by_ref('editTpl', $editTpl); } $gBitSystem->display('bitpackage:bitcommerce/admin_products_options.tpl', 'Product Options', array('display_mode' => 'admin'));
function tendQueue() { // Get the list of pending deliveries $msg_to_deliver = $this->listPendingDeliveries(); // If we have any if (count($msg_to_deliver)) { // Fetch the data about the messages $messages = $this->listMessages(array_keys($msg_to_deliver)); // And figure out how to deliver them foreach ($msg_to_deliver as $message_id => $deliveries) { foreach ($delivereis as $delivery_style => $users) { $func = $this->mTransports[$delivery_style]['send_function']; if (function_exists($func)) { $func($event, $users); } else { bit_error_log(tra("Package registered a non-existant function listener:") . " " . $this->mTransports[$delivery_style]['send_function'] . " => {$func}"); } } } } }
$_REQUEST['auto_only'] = TRUE; $feedsList = $reblog->getList($_REQUEST); $log = array(); $total = date('U'); $currTime = $gBitSystem->getUTCTime(); foreach (array_keys($feedsList) as $key) { $feedHash = $feedsList[$key]; if ($feedHash['last_updated'] + $feedHash['refresh'] <= $currTime) { $feed = new BitReBlog($feedHash['feed_id']); $feed->load(); $begin = date('U'); if (!$feed->updateFeed()) { $error = TRUE; $log[$key]['message'] = ' ERROR: ' . implode(',', $feed->mErrors['reblog']); } $log[$key]['time'] = date('d/M/Y:H:i:s O'); $log[$key]['duration'] = date('U') - $begin; $log[$key]['delay'] = date('U') - $total; } } foreach (array_keys($log) as $feedHash) { // generate something that kinda looks like apache common log format $logLine = $feedHash . ' - - [' . $log[$feedHash]['time'] . '] "' . $log[$feedHash]['message'] . '" ' . $log[$feedHash]['duration'] . "seconds <br/>\n"; if (isset($log[$feedHash['message']]) and strpos($log[$feedHash['message']], 'ERROR') !== FALSE) { bit_error_log($logLine); } print $logLine; } if (count($feedsList)) { print '# ' . count($feedsList) . " rss feeds processed in " . (date('U') - $total) . " seconds<br/>\n"; }
function parse_feeds($pParamHash) { //set path to rss feed cache $cache_path = TEMP_PKG_PATH . 'rss/simplepie'; //we do this earlier instead of later because if we can't cache the source we shouldn't be pulling the rss feed. if (!is_dir($cache_path) && !mkdir_p($cache_path)) { bit_error_log('Can not create the cache directory: ' . $cache_path); return FALSE; } else { //load up parser SimplePie require_once UTIL_PKG_PATH . 'simplepie/simplepie.inc'; if (!is_array($pParamHash['id'])) { $ids = explode(",", $pParamHash['id']); } else { $ids = $pParamHash['id']; } $urls = array(); foreach ($ids as $id) { if (@BitBase::verifyId($id)) { $feedHash = $this->get_rss_module($id); $urls[] = $feedHash['url']; } else { //todo assign this as an error //$repl = '<b>rss can not be found, id must be a number</b>'; } } $feed = new SimplePie(); //Instead of only passing in one feed url, we'll pass in an array of multiple feeds $feed->set_feed_url($urls); $feed->set_cache_location($cache_path); //set cache time $cache_time = !empty($pParamHash['cache_time']) ? $pParamHash['cache_time'] : 1; $feed->set_cache_duration($cache_time); //not sure - we may want to eventually use this //$feed->set_stupidly_fast(TRUE); // Initialize the feed object $feed->init(); // This will work if all of the feeds accept the same settings. $feed->handle_content_type(); $items = $feed->get_items(); return $items; } }
function debugOutput($pString) { global $gDebug; if ($gDebug || !defined('IS_LIVE') || !IS_LIVE) { if (empty($this->mLastOutputTime)) { $elapsed = (double) 0.0; } else { $elapsed = microtime(1) - (double) $this->mLastOutputTime; } if (!empty($this->mDebugMicrotime)) { $pString = "ELAPSED TIME: " . round((double) (microtime(1) - $this->mDebugMicrotime), 3) . ' sec, +' . round($elapsed, 3) . ' ' . $pString; } bit_error_log($pString); $this->mLastOutputTime = microtime(1); } }
function switchboard_aim_error($pErrorMsg) { bit_error_log($pErrorMsg); }
/** * verifyMX * * @param array $pEmail * @param array $pValidate * @access public * @return TRUE on success, FALSE on failure - mErrors will contain reason for failure */ function verifyMX($pEmail, &$pErrors) { global $gBitSystem, $gDebug; $HTTP_HOST = $_SERVER['SERVER_NAME']; $ret = false; if (validate_email_syntax($pEmail)) { list($Username, $domain) = preg_split("/@/", $pEmail); //checkdnsrr will check to see if there are any MX records for the domain if (!is_windows() and checkdnsrr($domain, "MX")) { bitdebug("Confirmation : MX record for {$domain} exists."); $MXWeights = array(); getmxrr($domain, $MXHost, $MXWeights); $hosts = array(); //create an array that combines the MXWeights with their associated hosts for ($i = 0; $i < count($MXHost); $i++) { $hosts[$MXHost[$i]] = $MXWeights[$i]; } //sorts the hosts by weight asort($hosts); if (!empty($hosts)) { //hosts shouldn't be empty here, since we passed the checkdnsrr check, but the server COULD have died between the first and second check. $Connect = ''; foreach ($hosts as $host => $priority) { $Connect = @fsockopen($host, 25, $errNo, $errStr, 10); // 10 second timeout to open each MX server, seems adequate to me, increase as necessary // Success in fsockopen if ($Connect) { bitdebug("Connection succeeded to {$host} SMTP."); stream_set_timeout($Connect, 30); $out = $this->getSmtpResponse($Connect); // Judgment is that a service preparing to begin a transaction will send a 220 string after a succesful handshake if (preg_match("/^220/", $out)) { // Inform client's reaching to server who connect. if ($gBitSystem->hasValidSenderEmail()) { $senderEmail = $gBitSystem->getConfig('site_sender_email'); fputs($Connect, "HELO {$HTTP_HOST}\r\n"); bitdebug("Run : HELO {$HTTP_HOST}"); // Receive server's answering cord. $out = $this->getSmtpResponse($Connect); // Inform sender's address to server. fputs($Connect, "MAIL FROM: <{$senderEmail}>\r\n"); bitdebug("Run : MAIL FROM: <{$senderEmail}>"); // Receive server's answering cord. $from = $this->getSmtpResponse($Connect); // Inform listener's address to server. fputs($Connect, "RCPT TO: <{$pEmail}>\r\n"); bitdebug("Run : RCPT TO: <{$pEmail}>"); // Receive server's answering cord. $to = $this->getSmtpResponse($Connect); // Finish connection. fputs($Connect, "QUIT\r\n"); bitdebug("Run : QUIT"); fclose($Connect); //Checks if we received a 250 OK from the server. If we did not, the server is telling us that this address is not a valid mailbox. if (!preg_match("/^250/", $from) || !preg_match("/^250/", $to) && !preg_match("/Please use your ISP relay/", $to)) { $pErrors['email'] = $pEmail . " is not recognized by the mail server. Try double checking the address for typos."; bit_error_log("INVALID EMAIL : " . $pEmail . " SMTP FROM : " . $from . " SMTP TO: " . $to); $ret = false; break; //break out of foreach and fall through to the end of function } else { $ret = true; //address has been verified by the server, no more checking necessary break; } } } elseif (preg_match("/^420/", $out)) { // Yahoo has a bad, bad habit of issuing 420's bit_error_log("UNKNOWN EMAIL : " . $pEmail . " SMTP response: " . $out); $ret = true; } else { $pErrors['email'] = 'Connection rejected by MX server'; bit_error_log("INVALID EMAIL : " . $pEmail . " SMTP response: " . $out); $ret = false; } } else { //fsockopen failed if (!$gBitSystem->getConfig('users_validate_email_role')) { //will ONLY stuff mErrors if you have not set a default role for verifiable emails, otherwise this is not a game breaking case $pErrors['email'] = "One or more mail servers not responding"; } $ret = -1; //-1 implies ambiguity, MX servers found, but unable to be reached. } } } else { $pErrors['email'] = "Mail server not found"; $ret = false; } } else { $pErrors['email'] = "Mail server not found"; $ret = false; } } else { $pErrors['email'] = "Invalid email syntax"; $ret = false; } return $ret; }
/** * liberty_magickwand_convert_colorspace * * @param array $pFileHash * @param string $pColorSpace - target color space, only 'grayscale' is currently supported * @access public * @return TRUE on success, FALSE on failure - mErrors will contain reason for failure */ function liberty_magickwand_convert_colorspace_image(&$pFileHash, $pColorSpace) { $ret = FALSE; if (!empty($pFileHash['source_file']) && is_file($pFileHash['source_file'])) { $magickWand = NewMagickWand(); if ($error = liberty_magickwand_check_error(MagickReadImage($magickWand, $pFileHash['source_file']), $magickWand)) { bit_error_log("MagickReadImage Failed:{$error} ( {$pFileHash['source_file']} )"); } else { MagickRemoveImageProfile($magickWand, "ICC"); switch (strtolower($pColorSpace)) { case 'grayscale': if (MagickGetImageColorspace($magickWand) == MW_GRAYColorspace) { $ret = TRUE; } else { MagickSetImageColorspace($magickWand, MW_GRAYColorspace); if (empty($pFileHash['dest_file'])) { $pFileHash['dest_file'] = STORAGE_PKG_PATH . $pFileHash['dest_branch'] . $pFileHash['name']; } if ($error = liberty_magickwand_check_error(MagickWriteImage($magickWand, $pFileHash['dest_file']), $magickWand)) { bit_error_log("MagickWriteImage Failed:{$error} ( {$pFileHash['source_file']} )"); } else { $ret = TRUE; } } break; } } DestroyMagickWand($magickWand); } return $ret; }
function htmlpure_filter(&$pString, &$pFilterHash, $pObject) { global $gHtmlPurifier, $gBitSystem; if (!isset($gHtmlPurifier)) { $pear_version = false; if (@(include_once "PEAR.php")) { if (@(include_once "HTMLPurifier.php")) { // for backward compatibility checks $htmlp_version = NULL; // If using 3.10+ if (!class_exists("HTMLPurifier_Config")) { @(include_once "HTMLPurifier.auto.php"); $auto_config = true; $htmlp_version = 3.1; } $config = htmlpure_getDefaultConfig($htmlp_version, $pObject); // As suggested here: http://www.bitweaver.org/forums/index.php?t=8554 $gHtmlPurifier = new HTMLPurifier($config); // how plugins are registered changed in v3.1 // old way of adding plugins before v3.1 if (!$htmlp_version >= 3.1) { htmlpure_legacyAddFilters(); } } } } // Did we manage to create one? if (isset($gHtmlPurifier)) { /* Clean up the paragraphs a bit */ // $start = $pData; $pString = htmlpure_cleanupPeeTags($pString); // $pee = $pString; // $pString = html_entity_decode( $pString ); if (empty($pFilterHash['htmlp_config'])) { $pString = $gHtmlPurifier->purify($pString); } else { $htmlp_version = $gHtmlPurifier->version; $config = htmlpure_getDefaultConfig($htmlp_version, $pObject); /* if we've received custom configurations for the particular parse then we deal with them for now were expecting config data that htmlpurfier doesn't really handle in a nice way so we stuff it into the 'info' hash under a 'bitweaver' name space. @TODO ideally this might also look for native htmlpurifier config values in the keys and then adjust as necessary which is why $config is passed in here. -wjames5 */ foreach ($pFilterHash['htmlp_config'] as $key => $val) { $config->def->info['bitweaver'][$key] = $val; } $pString = $gHtmlPurifier->purify($pString, $config); } // If we have another parse step they may be escaping // entities so change quotes back. if (empty($pFilterHash['format_guid']) || $pFilterHash['format_guid'] != 'bithtml') { $pString = preg_replace('|"|', '"', $pString); $pString = preg_replace('|'|', "'", $pString); } /* echo "<br/><hr/><br/>".$start; include_once( 'Text/Diff.php' ); include_once( 'Text/Diff/Renderer/inline.php' ); $diff = &new Text_Diff(explode("\n", $start), explode("\n",$pee)); $renderer = &new Text_Diff_Renderer_inline(); echo "<br/><hr/><br/>". $renderer->render($diff); echo "<br/><hr/><br/>".$pString; include_once( 'Text/Diff.php' ); include_once( 'Text/Diff/Renderer/inline.php' ); $diff = &new Text_Diff(explode("\n", $pee), explode("\n",$pString)); $renderer = &new Text_Diff_Renderer_inline(); echo "<br/><hr/><br/>". $renderer->render($diff); */ } else { bit_error_log("HTMLPurifier not installed. Install with: pear channel-discover htmlpurifier.org; pear install hp/HTMLPurifier;"); } return $pString; }
function mailman_command($pCommand, &$output, $pOptions = NULL) { $ret_code = NULL; if ($fullCommand = mailman_get_command($pCommand)) { $cmd = $fullCommand . ' ' . $pOptions; if (!defined('IS_LIVE') || !IS_LIVE) { bit_error_log('mailman LOG: ' . $cmd); } exec($cmd, $output, $ret_code); if ($ret_code) { bit_error_log('Error running command: ' . $cmd . ' Command returned: ' . $ret_code); } } else { bit_error_log('Groups mailman command failed (' . $pCommand . '): File not found: ' . $fullCommand); } return $ret_code; }