/** * Read messages from server and create posts * * @param resource $mbox created by pbm_connect() (by reference) * @param integer the number of messages to process * @return boolean true on success */ function pbm_process_messages(&$mbox, $limit) { global $Settings; global $pbm_item_files, $pbm_messages, $pbm_items, $post_cntr, $del_cntr, $is_cron_mode; // No execution time limit set_max_execution_time(0); // Are we in test mode? $test_mode_on = $Settings->get('eblog_test_mode'); $post_cntr = 0; $del_cntr = 0; for ($index = 1; $index <= $limit; $index++) { pbm_msg('<hr /><h3>Processing message #' . $index . ':</h3>'); $strbody = ''; $hasAttachment = false; $hasRelated = false; $pbm_item_files = array(); // reset the value for each new Item // Save email to hard drive, otherwise attachments may take a lot of RAM if (!($tmpMIME = tempnam(sys_get_temp_dir(), 'b2evoMail'))) { pbm_msg(T_('Could not create temporary file.'), true); continue; } imap_savebody($mbox, $tmpMIME, $index); // Create random temp directory for message parts $tmpDirMIME = pbm_tempdir(sys_get_temp_dir(), 'b2evo_'); $mimeParser = new mime_parser_class(); $mimeParser->mbox = 0; // Set to 0 for parsing a single message file $mimeParser->decode_headers = 1; $mimeParser->ignore_syntax_errors = 1; $mimeParser->extract_addresses = 0; $MIMEparameters = array('File' => $tmpMIME, 'SaveBody' => $tmpDirMIME, 'SkipBody' => 1); if (!$mimeParser->Decode($MIMEparameters, $decodedMIME)) { pbm_msg(sprintf('MIME message decoding error: %s at position %d.', $mimeParser->error, $mimeParser->error_position), true); rmdir_r($tmpDirMIME); unlink($tmpMIME); continue; } else { pbm_msg('MIME message decoding successful'); if (!$mimeParser->Analyze($decodedMIME[0], $parsedMIME)) { pbm_msg(sprintf('MIME message analyse error: %s', $mimeParser->error), true); rmdir_r($tmpDirMIME); unlink($tmpMIME); continue; } // Get message $subject and $post_date from headers (by reference) if (!pbm_process_header($parsedMIME, $subject, $post_date)) { // Couldn't process message headers rmdir_r($tmpDirMIME); unlink($tmpMIME); continue; } // TODO: handle type == "message" recursively // sam2kb> For some reason imap_qprint() demages HTML text... needs more testing if ($parsedMIME['Type'] == 'html') { // Mail is HTML if ($Settings->get('eblog_html_enabled')) { // HTML posting enabled pbm_msg('HTML message part saved as ' . $parsedMIME['DataFile']); $html_body = file_get_contents($parsedMIME['DataFile']); } foreach ($parsedMIME['Alternative'] as $alternative) { // First try to get HTML alternative (when possible) if ($alternative['Type'] == 'html' && $Settings->get('eblog_html_enabled')) { // HTML text pbm_msg('HTML alternative message part saved as ' . $alternative['DataFile']); // sam2kb> TODO: we may need to use $html_body here instead $strbody = file_get_contents($alternative['DataFile']); break; // stop after first alternative } elseif ($alternative['Type'] == 'text') { // Plain text pbm_msg('Text alternative message part saved as ' . $alternative['DataFile']); $strbody = imap_qprint(file_get_contents($alternative['DataFile'])); break; // stop after first alternative } } } elseif ($parsedMIME['Type'] == 'text') { // Mail is plain text pbm_msg('Plain-text message part saved as ' . $parsedMIME['DataFile']); $strbody = imap_qprint(file_get_contents($parsedMIME['DataFile'])); } // Check for attachments if (!empty($parsedMIME['Attachments'])) { $hasAttachment = true; foreach ($parsedMIME['Attachments'] as $file) { pbm_msg('Attachment: ' . $file['FileName'] . ' stored as ' . $file['DataFile']); } } // Check for inline images if (!empty($parsedMIME['Related'])) { $hasRelated = true; foreach ($parsedMIME['Related'] as $file) { pbm_msg('Related file with content ID: ' . $file['ContentID'] . ' stored as ' . $file['DataFile']); } } if (count($mimeParser->warnings) > 0) { pbm_msg(sprintf('<h4>%d warnings during decode:</h4>', count($mimeParser->warnings))); foreach ($mimeParser->warnings as $k => $v) { pbm_msg('Warning: ' . $v . ' at position ' . $k); } } } unlink($tmpMIME); if (empty($html_body)) { // Plain text message pbm_msg('Message type: TEXT'); pbm_msg('Message body: <pre style="font-size:10px">' . htmlspecialchars($strbody) . '</pre>'); // Process body. First fix different line-endings (dos, mac, unix), remove double newlines $content = str_replace(array("\r", "\n\n"), "\n", trim($strbody)); // First see if there's an <auth> tag with login and password if (($auth = pbm_get_auth_tag($content)) === false) { // No <auth> tag, let's detect legacy "username:password" on the first line $a_body = explode("\n", $content, 2); // tblue> splitting only into 2 parts allows colons in the user PW // Note: login and password cannot include '<' ! $auth = explode(':', strip_tags($a_body[0]), 2); // Drop the first line with username and password $content = $a_body[1]; } } else { // HTML message pbm_msg('Message type: HTML'); if (($parsed_message = pbm_prepare_html_message($html_body)) === false) { // No 'auth' tag provided, skip to the next message rmdir_r($tmpDirMIME); continue; } list($auth, $content) = $parsed_message; } // TODO: dh> should the password really get trimmed here?! $user_pass = isset($auth[1]) ? trim(remove_magic_quotes($auth[1])) : NULL; $user_login = trim(evo_strtolower(remove_magic_quotes($auth[0]))); if (empty($user_login) || empty($user_pass)) { pbm_msg(sprintf(T_('Please add username and password in message body in format %s.'), '"<auth>username:password</auth>"'), true); rmdir_r($tmpDirMIME); continue; } // Authenticate user pbm_msg('Authenticating user: «' . $user_login . '»'); $pbmUser =& pbm_validate_user_password($user_login, $user_pass); if (!$pbmUser) { pbm_msg(sprintf(T_('Authentication failed for user «%s»'), htmlspecialchars($user_login)), true); rmdir_r($tmpDirMIME); continue; } $pbmUser->get_Group(); // Load group if (!empty($is_cron_mode)) { // Assign current User if we are in cron mode. This is needed in order to check user permissions global $current_User; $current_User = duplicate($pbmUser); } // Activate User's locale locale_activate($pbmUser->get('locale')); pbm_msg('<b class="green">Success</b>'); if ($post_categories = xmlrpc_getpostcategories($content)) { $main_cat_ID = array_shift($post_categories); $extra_cat_IDs = $post_categories; pbm_msg('Extra categories: ' . implode(', ', $extra_cat_IDs)); } else { $main_cat_ID = $Settings->get('eblog_default_category'); $extra_cat_IDs = array(); } pbm_msg('Main category ID: ' . $main_cat_ID); $ChapterCache =& get_ChapterCache(); $pbmChapter =& $ChapterCache->get_by_ID($main_cat_ID, false, false); if (empty($pbmChapter)) { pbm_msg(sprintf(T_('Requested category %s does not exist!'), $main_cat_ID), true); rmdir_r($tmpDirMIME); continue; } $blog_ID = $pbmChapter->blog_ID; pbm_msg('Blog ID: ' . $blog_ID); $BlogCache =& get_BlogCache(); $pbmBlog =& $BlogCache->get_by_ID($blog_ID, false, false); if (empty($pbmBlog)) { pbm_msg(sprintf(T_('Requested blog %s does not exist!'), $blog_ID), true); rmdir_r($tmpDirMIME); continue; } // Check permission: pbm_msg(sprintf('Checking permissions for user «%s» to post to Blog #%d', $user_login, $blog_ID)); if (!$pbmUser->check_perm('blog_post!published', 'edit', false, $blog_ID)) { pbm_msg(T_('Permission denied.'), true); rmdir_r($tmpDirMIME); continue; } if (($hasAttachment || $hasRelated) && !$pbmUser->check_perm('files', 'add', false, $blog_ID)) { pbm_msg(T_('You have no permission to add/upload files.'), true); rmdir_r($tmpDirMIME); continue; } pbm_msg('<b class="green">Success</b>'); // Remove content after terminator $eblog_terminator = $Settings->get('eblog_body_terminator'); if (!empty($eblog_terminator) && ($os_terminator = evo_strpos($content, $eblog_terminator)) !== false) { $content = evo_substr($content, 0, $os_terminator); } $post_title = pbm_get_post_title($content, $subject); // Remove 'title' and 'category' tags $content = xmlrpc_removepostdata($content); // Remove <br> tags from string start and end // We do it here because there might be extra <br> left after deletion of <auth>, <category> and <title> tags $content = preg_replace(array('~^(\\s*<br[\\s/]*>\\s*){1,}~i', '~(\\s*<br[\\s/]*>\\s*){1,}$~i'), '', $content); if ($hasAttachment || $hasRelated) { // Handle attachments if (isset($GLOBALS['files_Module'])) { if ($mediadir = $pbmBlog->get_media_dir()) { if ($hasAttachment) { pbm_process_attachments($content, $parsedMIME['Attachments'], $mediadir, $pbmBlog->get_media_url(), $Settings->get('eblog_add_imgtag'), 'attach'); } if ($hasRelated) { pbm_process_attachments($content, $parsedMIME['Related'], $mediadir, $pbmBlog->get_media_url(), true, 'related'); } } else { pbm_msg(T_('Unable to access media directory. No attachments processed.'), true); } } else { pbm_msg(T_('Files module is disabled or missing!'), true); } } // CHECK and FORMAT content global $Plugins; $renderer_params = array('Blog' => &$pbmBlog, 'setting_name' => 'coll_apply_rendering'); $renderers = $Plugins->validate_renderer_list($Settings->get('eblog_renderers'), $renderer_params); pbm_msg('Applying the following text renderers: ' . implode(', ', $renderers)); // Do some optional filtering on the content // Typically stuff that will help the content to validate // Useful for code display // Will probably be used for validation also $Plugins_admin =& get_Plugins_admin(); $params = array('object_type' => 'Item', 'object_Blog' => &$pbmBlog); $Plugins_admin->filter_contents($post_title, $content, $renderers, $params); pbm_msg('Filtered post content: <pre style="font-size:10px">' . htmlspecialchars($content) . '</pre>'); $context = $Settings->get('eblog_html_tag_limit') ? 'commenting' : 'posting'; $post_title = check_html_sanity($post_title, $context, $pbmUser); $content = check_html_sanity($content, $context, $pbmUser); global $Messages; if ($Messages->has_errors()) { // Make it easier for user to find and correct the errors pbm_msg("\n" . sprintf(T_('Processing message: %s'), $post_title), true); pbm_msg($Messages->get_string(T_('Cannot post, please correct these errors:'), 'error'), true); $Messages->clear(); rmdir_r($tmpDirMIME); continue; } if ($test_mode_on) { // Test mode pbm_msg('<b class="green">It looks like the post can be successfully saved in the database. However we will not do it in test mode.</b>'); } else { load_class('items/model/_item.class.php', 'Item'); global $pbm_items, $DB, $localtimenow; $post_status = 'published'; pbm_msg(sprintf('<h4>Saving item "%s" in the database</h4>', $post_title)); // INSERT NEW POST INTO DB: $edited_Item = new Item(); $edited_Item->set_creator_User($pbmUser); $edited_Item->set($edited_Item->lasteditor_field, $pbmUser->ID); $edited_Item->set('title', $post_title); $edited_Item->set('content', $content); $edited_Item->set('datestart', $post_date); $edited_Item->set('datemodified', date('Y-m-d H:i:s', $localtimenow)); $edited_Item->set('main_cat_ID', $main_cat_ID); $edited_Item->set('extra_cat_IDs', $extra_cat_IDs); $edited_Item->set('status', $post_status); $edited_Item->set('locale', $pbmUser->locale); $edited_Item->set('renderers', $renderers); // INSERT INTO DB: $edited_Item->dbinsert('through_email'); pbm_msg(sprintf('Item created?: ' . (isset($edited_Item->ID) ? 'yes' : 'no'))); // Execute or schedule notifications & pings: $edited_Item->handle_post_processing(true); if (!empty($pbm_item_files)) { // Attach files $FileCache =& get_FileCache(); $order = 1; foreach ($pbm_item_files as $filename) { pbm_msg(sprintf('Saving file "%s" in the database', $filename)); $pbmFile =& $FileCache->get_by_root_and_path('collection', $pbmBlog->ID, $filename); $pbmFile->meta = 'notfound'; // Save time and don't try to load meta from DB, it's not there anyway $pbmFile->dbsave(); pbm_msg(sprintf('File saved?: ' . (isset($pbmFile->ID) ? 'yes' : 'no'))); pbm_msg(sprintf('Attaching file "%s" to the post', $filename)); // Let's make the link! $pbmLink = new Link(); $pbmLink->set('itm_ID', $edited_Item->ID); $pbmLink->set('file_ID', $pbmFile->ID); $pbmLink->set('position', 'aftermore'); $pbmLink->set('order', $order++); $pbmLink->dbinsert(); pbm_msg(sprintf('File attached?: ' . (isset($pbmLink->ID) ? 'yes' : 'no'))); } } // Save posted items sorted by author user for reports $pbm_items['user_' . $pbmUser->ID][] = $edited_Item; ++$post_cntr; } pbm_msg('Message posting successful'); // Delete temporary directory rmdir_r($tmpDirMIME); if (!$test_mode_on && $Settings->get('eblog_delete_emails')) { pbm_msg('Marking message for deletion from inbox: ' . $index); imap_delete($mbox, $index); ++$del_cntr; } } // Expunge messages marked for deletion imap_expunge($mbox); return true; }
/** * blogger.editPost changes the contents of a given post. * * Optionally, will publish the blog the post belongs to after changing the post. * (In b2evo, this means the changed post will be moved to published state). * On success, it returns a boolean true value. * On error, it will return a fault with an error message. * * @see http://www.blogger.com/developers/api/1_docs/xmlrpc_editPost.html * @see http://www.sixapart.com/developers/xmlrpc/blogger_api/bloggereditpost.html * * @param xmlrpcmsg XML-RPC Message * 0 appkey (string): Unique identifier/passcode of the application sending the post. * (See access info {@link http://www.blogger.com/developers/api/1_docs/#access} .) * 1 postid (string): Unique identifier of the post to be changed. * 2 username (string): Login for a Blogger user who has permission to edit the given * post (either the user who originally created it or an admin of the blog). * 3 password (string): Password for said username. * 4 content (string): New content of the post. * 5 publish (boolean): If true, the blog will be published immediately after the * post is made. (In b2evo,this means, the new post will be in 'published' state, * otherwise it would be in draft state). * @return xmlrpcresp XML-RPC Response * * @todo check current status and permission on it */ function blogger_editpost($m) { // CHECK LOGIN: /** * @var User */ if (!($current_User =& xmlrpcs_login($m, 2, 3))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } // GET POST: /** * @var Item */ if (!($edited_Item =& xmlrpcs_get_Item($m, 1))) { // Failed, return (last) error: return xmlrpcs_resperror(); } // We need to be able to edit this post: if (!$current_User->check_perm('item_post!CURSTATUS', 'edit', false, $edited_Item)) { return xmlrpcs_resperror(3); // Permission denied } $content = $m->getParam(4); $content = $content->scalarval(); $publish = $m->getParam(5); $publish = $publish->scalarval(); $status = $publish ? 'published' : 'draft'; logIO("Publish: {$publish} -> Status: {$status}"); $title = xmlrpc_getposttitle($content); $cat_IDs = xmlrpc_getpostcategories($content); // Cleanup content from extra tags like <category> and <title>: $content = xmlrpc_removepostdata($content); $params = array('title' => $title, 'content' => $content, 'cat_IDs' => $cat_IDs, 'status' => $status); // COMPLETE VALIDATION & INSERT: return xmlrpcs_edit_item($edited_Item, $params); }
/** * blogger.editPost changes the contents of a given post. * * Optionally, will publish the blog the post belongs to after changing the post. * (In b2evo, this means the changed post will be moved to published state). * On success, it returns a boolean true value. * On error, it will return a fault with an error message. * * @see http://www.blogger.com/developers/api/1_docs/xmlrpc_editPost.html * @see http://www.sixapart.com/developers/xmlrpc/blogger_api/bloggereditpost.html * * @param xmlrpcmsg XML-RPC Message * 0 appkey (string): Unique identifier/passcode of the application sending the post. * (See access info {@link http://www.blogger.com/developers/api/1_docs/#access} .) * 1 postid (string): Unique identifier of the post to be changed. * 2 username (string): Login for a Blogger user who has permission to edit the given * post (either the user who originally created it or an admin of the blog). * 3 password (string): Password for said username. * 4 content (string): New content of the post. * 5 publish (boolean): If true, the blog will be published immediately after the * post is made. (In b2evo,this means, the new post will be in 'published' state, * otherwise it would be in draft state). * @return xmlrpcresp XML-RPC Response * * @todo check current status and permission on it */ function blogger_editpost($m) { global $xmlrpcerruser; // import user errcode value global $DB; global $Messages; // CHECK LOGIN: /** * @var User */ if (!($current_User =& xmlrpcs_login($m, 2, 3))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } // GET POST: /** * @var Item */ if (!($edited_Item =& xmlrpcs_get_Item($m, 1))) { // Failed, return (last) error: return xmlrpcs_resperror(); } $content = $m->getParam(4); $content = $content->scalarval(); $publish = $m->getParam(5); $publish = $publish->scalarval(); $status = $publish ? 'published' : 'draft'; logIO("Publish: {$publish} -> Status: {$status}"); $cat_IDs = xmlrpc_getpostcategories($content); if (empty($cat_IDs)) { // There were no categories passed in the content: $main_cat = $edited_Item->main_cat_ID; $cat_IDs = array($main_cat); } else { $main_cat = $cat_IDs[0]; } // CHECK PERMISSION: (we need perm on all categories, especially if they are in different blogs) if (!$current_User->check_perm('cats_post!' . $status, 'edit', false, $cat_IDs)) { // Permission denied return xmlrpcs_resperror(3); // User error 3 } logIO('Permission granted.'); logIO('Main cat: ' . $main_cat); // Check if category exists if (get_the_category_by_ID($main_cat, false) === false) { // Cat does not exist: // fp> TODO use $Blog->get_default_cat_ID(); return xmlrpcs_resperror(11); // User error 11 } $post_date = NULL; $post_title = xmlrpc_getposttitle($content); $content = xmlrpc_removepostdata($content); // COMPLETE VALIDATION & UPDATE: return xmlrpcs_edit_item($edited_Item, $post_title, $content, $post_date, $main_cat, $cat_IDs, $status); }