/** * Create a new Item and return an XML-RPC response * * @param array Item properties * @param object Blog where we are going to create a new Item * @return xmlrpcmsg */ function xmlrpcs_new_item($params, &$Blog = NULL) { global $current_User, $Settings, $Messages, $DB, $posttypes_perms; $params = array_merge(array('title' => '', 'content' => '', 'date' => '', 'main_cat_ID' => 0, 'extra_cat_IDs' => array(), 'cat_IDs' => array(), 'status' => 'published', 'tags' => '', 'excerpt' => '', 'item_typ_ID' => 1, 'comment_status' => 'open', 'urltitle' => '', 'featured' => 0, 'custom_fields' => array(), 'order' => '', 'parent_ID' => ''), $params); if (empty($Blog) && !empty($params['main_cat_ID'])) { // Get the blog by main category ID // Check if category exists and can be used $ChapterCache =& get_ChapterCache(); $main_Chapter =& $ChapterCache->get_by_ID($params['main_cat_ID'], false, false); if (empty($main_Chapter)) { // Cat does not exist: return xmlrpcs_resperror(11); // User error 11 } $BlogCache =& get_BlogCache(); $Blog =& $BlogCache->get_by_ID($main_Chapter->blog_ID, false, false); logIO('Requested Blog: ' . $Blog->ID . ' - ' . $Blog->name); } if (empty($Blog)) { // Blog does not exist: return xmlrpcs_resperror(); } if (empty($params['main_cat_ID'])) { if (is_array($params['cat_IDs']) && count($params['cat_IDs']) > 0) { // Let's use first cat for MAIN and others for EXTRA $params['main_cat_ID'] = array_shift($params['cat_IDs']); $params['extra_cat_IDs'] = $params['cat_IDs']; } else { if (!($main_cat = $Blog->get_default_cat_ID())) { // No default category found for requested blog return xmlrpcs_resperror(12); // User error 12 } $params['main_cat_ID'] = $main_cat; } } logIO('Main cat ID: ' . $params['main_cat_ID']); logIO('Extra cat IDs: ' . implode(', ', $params['extra_cat_IDs'])); if (empty($params['main_cat_ID'])) { // Main category does not exist: return xmlrpcs_resperror(11); // User error 11 } // Check if category exists and can be used if (!xmlrpcs_check_cats($params['main_cat_ID'], $Blog, $params['extra_cat_IDs'])) { // Permission denied return xmlrpcs_resperror(3); // User error 3 } /* * CHECK PERMISSION: (we need perm on all categories, especially if they are in different blogs) * NOTE: extra_cat_IDs array now includes main_cat_ID too, so we are actually checking ALL categories below */ if (!$current_User->check_perm('cats_post!' . $params['status'], 'edit', false, $params['extra_cat_IDs'])) { // Permission denied return xmlrpcs_resperror(3); // User error 3 } if (!empty($params['item_typ_ID'])) { if (!preg_match('~^[0-9]+$~', $params['item_typ_ID'])) { // Only accept numeric values, switch to default value $params['item_typ_ID'] = 1; } foreach ($posttypes_perms as $l_permname => $l_posttypes) { // "Reverse" the $posttypes_perms array: foreach ($l_posttypes as $ll_posttype) { $posttype2perm[$ll_posttype] = $l_permname; } } if (isset($posttype2perm[$params['item_typ_ID']])) { // Check permission for this post type if (!$current_User->check_perm('cats_' . $posttype2perm[$params['item_typ_ID']], 'edit', false, $params['extra_cat_IDs'])) { // Permission denied return xmlrpcs_resperror(3); // User error 3 } } } logIO('Post type: ' . $params['item_typ_ID']); logIO('Permission granted.'); // CHECK HTML SANITY: if (($params['title'] = check_html_sanity($params['title'], 'xmlrpc_posting')) === false) { return xmlrpcs_resperror(21, $Messages->get_string('Invalid post title, please correct these errors:', '')); } if (($params['content'] = check_html_sanity($params['content'], 'xmlrpc_posting')) === false) { return xmlrpcs_resperror(22, $Messages->get_string('Invalid post contents, please correct these errors:' . "\n", '', " // \n", 'xmlrpc')); } if (empty($params['date'])) { $params['date'] = date('Y-m-d H:i:s', time() + $Settings->get('time_difference')); } // INSERT NEW POST INTO DB: load_class('items/model/_item.class.php', 'Item'); $edited_Item = new Item(); $edited_Item->set('title', $params['title']); $edited_Item->set('content', $params['content']); $edited_Item->set('issue_date', $params['date']); $edited_Item->set('main_cat_ID', $params['main_cat_ID']); $edited_Item->set('extra_cat_IDs', $params['extra_cat_IDs']); $edited_Item->set('status', $params['status']); $edited_Item->set('ptyp_ID', $params['item_typ_ID']); $edited_Item->set('featured', $params['featured']); $edited_Item->set_tags_from_string($params['tags']); $edited_Item->set('locale', $current_User->locale); $edited_Item->set_creator_User($current_User); if ($params['excerpt'] != '') { $edited_Item->set('excerpt', $params['excerpt']); } if ($params['urltitle'] != '') { $edited_Item->set('urltitle', $params['urltitle']); } if ($params['parent_ID'] != '') { $edited_Item->set('parent_ID', $params['parent_ID']); } if (!empty($params['order'])) { $edited_Item->set('order', $params['order']); } // Do not set if order is 0 if ($Blog->get_setting('allow_comments') != 'never' && $Blog->get_setting('disable_comments_bypost')) { // Comment status $edited_Item->set('comment_status', $params['comment_status']); } $edited_Item->dbinsert('through_xmlrpc'); if (empty($edited_Item->ID)) { return xmlrpcs_resperror(99, 'Error while inserting item: ' . $DB->last_error); } logIO('Posted with ID: ' . $edited_Item->ID); if (!empty($params['custom_fields']) && is_array($params['custom_fields']) && count($params['custom_fields']) > 0) { // TODO sam2kb> Add custom fields foreach ($params['custom_fields'] as $field) { // id, key, value logIO('Custom field: ' . var_export($field, true)); } } // Execute or schedule notifications & pings: logIO('Handling notifications...'); $edited_Item->handle_post_processing(true); logIO('OK.'); return new xmlrpcresp(new xmlrpcval($edited_Item->ID)); }
/** * 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; }