/** * Get an array of ALL available Fileroots (not just the cached ones). * * @todo fp> it would probably make sense to refactor this as the constructor for the file roots * and initialize the whole cache at construction time * * @param string Special file root ID (Used e.g. to view file root of the special user) * @return array of FileRoots (key being the FileRoot's ID) */ static function get_available_FileRoots($special_root_ID = NULL) { global $current_User; global $collections_Module; $r = array(); $FileRootCache =& get_FileRootCache(); if (!empty($special_root_ID) && ($special_FileRoot =& $FileRootCache->get_by_ID($special_root_ID, true)) && $current_User->check_perm('files', 'edit_allowed', false, $special_FileRoot)) { // Try to add special file root if current user has an access $r[$special_FileRoot->ID] =& $special_FileRoot; } // The user's blog (if available) is the default/first one: $user_FileRoot =& $FileRootCache->get_by_type_and_ID('user', $current_User->ID, true); if ($user_FileRoot) { // We got a user media dir: $r[$user_FileRoot->ID] =& $user_FileRoot; } if (isset($collections_Module)) { // Blog/collection media dirs: $BlogCache =& get_BlogCache(); $bloglist = $BlogCache->load_user_blogs('blog_media_browse', $current_User->ID); foreach ($bloglist as $blog_ID) { if ($Root =& $FileRootCache->get_by_type_and_ID('collection', $blog_ID, true)) { $r[$Root->ID] =& $Root; } } } // Shared root: $shared_FileRoot =& $FileRootCache->get_by_type_and_ID('shared', 0, true); if ($shared_FileRoot) { // We got a shared dir: $r[$shared_FileRoot->ID] =& $shared_FileRoot; } if (isset($collections_Module)) { // Skins root: $skins_FileRoot =& $FileRootCache->get_by_type_and_ID('skins', 0, false); if ($skins_FileRoot) { // We got a skins dir: $r[$skins_FileRoot->ID] =& $skins_FileRoot; } } // Import root: $import_FileRoot =& $FileRootCache->get_by_type_and_ID('import', 0, true); if ($import_FileRoot) { // We got an import dir: $r[$import_FileRoot->ID] =& $import_FileRoot; } return $r; }
/** * Import user's avatar * * @param integer User ID (from b2evo) * @param string Path avatars * @param string File name of user's avatar */ function phpbb_import_avatar($user_ID, $path_avatars, $user_avatar) { global $DB, $tableprefix; if (!empty($user_avatar) && file_exists($path_avatars . $user_avatar)) { // Import user's avatar $FileRootCache =& get_FileRootCache(); $root_ID = FileRoot::gen_ID('user', $user_ID); $imported_file_ID = copy_file($path_avatars . $user_avatar, $root_ID, 'profile_pictures', false); if (!empty($imported_file_ID)) { // Update user's avatar mysql_query('UPDATE ' . $tableprefix . 'users SET user_avatar_file_ID = ' . $DB->quote($imported_file_ID) . ' WHERE user_ID = ' . $DB->quote($user_ID) . ' AND user_avatar_file_ID IS NULL', $DB->dbhandle); } } }
$message = array(); require_once dirname(__FILE__) . '/../conf/_config.php'; require_once $inc_path . '_main.inc.php'; // Do not append Debuglog to response! $debug = false; // Do not append Debug JSlog to response! $debug_jslog = false; global $current_User; param('upload', 'boolean', true); param('root_and_path', 'string', true); // Check that this action request is not a CSRF hacked request: $Session->assert_received_crumb('file'); $upload_path = false; if (strpos($root_and_path, '::')) { list($root, $path) = explode('::', $root_and_path, 2); $FileRootCache =& get_FileRootCache(); $fm_FileRoot = $FileRootCache->get_by_ID($root); $non_canonical_list_path = $fm_FileRoot->ads_path . $path; $upload_path = get_canonical_path($non_canonical_list_path); } if ($upload_path === false) { $message['text'] = '<span class="result_error">Bad request. Unknown upload location!</span>'; // NO TRANS!! out_echo($message, $specialchars); exit; } if ($upload && !$current_User->check_perm('files', 'add', false, $fm_FileRoot)) { $message['text'] = '<span class="result_error">' . T_('You don\'t have permission to upload on this file root.') . '</span>'; out_echo($message, $specialchars); exit; }
/** * metaWeblog.newMediaObject image upload * wp.uploadFile * * Supplied image is encoded into the struct as bits * * @see http://www.xmlrpc.com/metaWeblogApi#metaweblognewmediaobject * @see http://codex.wordpress.org/XML-RPC_wp#wp.uploadFile * * @param xmlrpcmsg XML-RPC Message * 0 blogid (string): Unique identifier of the blog the post will be added to. * Currently ignored in b2evo, in favor of the category. * 1 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). * 2 password (string): Password for said username. * 3 struct (struct) * - name : filename * - type : mimetype * - bits : base64 encoded file * @return xmlrpcresp XML-RPC Response */ function _wp_mw_newmediaobject($m) { global $Settings, $Plugins, $force_upload_forbiddenext; // CHECK LOGIN: /** * @var User */ if (!($current_User =& xmlrpcs_login($m, 1, 2))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } // GET BLOG: /** * @var Blog */ if (!($Blog =& xmlrpcs_get_Blog($m, 0))) { // Login failed, return (last) error: return xmlrpcs_resperror(); } // CHECK PERMISSION: if (!$current_User->check_perm('files', 'add', false, $Blog->ID)) { // Permission denied return xmlrpcs_resperror(3); // User error 3 } logIO('Permission granted.'); if (!$Settings->get('upload_enabled')) { return xmlrpcs_resperror(2, 'Object upload not allowed'); } $xcontent = $m->getParam(3); // Get the main data - and decode it properly for the image - sorry, binary object logIO('Decoding content...'); $contentstruct = xmlrpc_decode_recurse($xcontent); $data = $contentstruct['bits']; $file_mimetype = isset($contentstruct['type']) ? $contentstruct['type'] : '(none)'; logIO('Received MIME type: ' . $file_mimetype); $overwrite = false; if (isset($contentstruct['overwrite'])) { $overwrite = (bool) $contentstruct['overwrite']; } logIO('Overwrite if exists: ' . ($overwrite ? 'yes' : 'no')); load_funcs('files/model/_file.funcs.php'); $filesize = evo_bytes($data); if (($maxfilesize = $Settings->get('upload_maxkb') * 1024) && $filesize > $maxfilesize) { return xmlrpcs_resperror(4, sprintf(T_('The file is too large: %s but the maximum allowed is %s.'), bytesreadable($filesize, false), bytesreadable($maxfilesize, false))); } logIO('File size is OK: ' . bytesreadable($filesize, false)); $FileRootCache =& get_FileRootCache(); $fm_FileRoot =& $FileRootCache->get_by_type_and_ID('collection', $Blog->ID, true); if (!$fm_FileRoot) { // fileRoot not found: return xmlrpcs_resperror(14, 'File root not found'); } $rf_filepath = $contentstruct['name']; logIO('Received filepath: ' . $rf_filepath); // Split into path + name: $filepath_parts = explode('/', $rf_filepath); $filename = array_pop($filepath_parts); logIO('Original file name: ' . $filename); // Validate and sanitize filename if ($error_filename = process_filename($filename, true)) { return xmlrpcs_resperror(5, $error_filename); } logIO('Sanitized file name: ' . $filename); // Check valid path parts: $rds_subpath = ''; foreach ($filepath_parts as $filepath_part) { if (empty($filepath_part) || $filepath_part == '.') { // self ref not useful continue; } if ($error = validate_dirname($filepath_part)) { // invalid relative path: logIO($error); return xmlrpcs_resperror(6, $error); } $rds_subpath .= $filepath_part . '/'; } logIO('Subpath: ' . $rds_subpath); // Create temporary file and insert contents into it. $tmpfile_name = tempnam(sys_get_temp_dir(), 'fmupload'); if ($tmpfile_name) { if (save_to_file($data, $tmpfile_name, 'wb')) { $image_info = @getimagesize($tmpfile_name); } else { return xmlrpcs_resperror(13, 'Error while writing to temp file.'); } } if (!empty($image_info)) { // This is an image file, let's check mimetype and correct extension if ($image_info['mime'] != $file_mimetype) { // Invalid file type $FiletypeCache =& get_FiletypeCache(); // Get correct file type based on mime type $correct_Filetype = $FiletypeCache->get_by_mimetype($image_info['mime'], false, false); $file_mimetype = $image_info['mime']; // Check if file type is known by us, and if it is allowed for upload. // If we don't know this file type or if it isn't allowed we don't change the extension! The current extension is allowed for sure. if ($correct_Filetype && $correct_Filetype->is_allowed()) { // A FileType with the given mime type exists in database and it is an allowed file type for current User // The "correct" extension is a plausible one, proceed... $correct_extension = array_shift($correct_Filetype->get_extensions()); $path_info = pathinfo($filename); $current_extension = $path_info['extension']; // change file extension to the correct extension, but only if the correct extension is not restricted, this is an extra security check! if (strtolower($current_extension) != strtolower($correct_extension) && !in_array($correct_extension, $force_upload_forbiddenext)) { // change the file extension to the correct extension $old_filename = $filename; $filename = $path_info['filename'] . '.' . $correct_extension; } } } } // Get File object for requested target location: $FileCache =& get_FileCache(); $newFile =& $FileCache->get_by_root_and_path($fm_FileRoot->type, $fm_FileRoot->in_type_ID, trailing_slash($rds_subpath) . $filename, true); if ($newFile->exists()) { if ($overwrite && $newFile->unlink()) { // OK, file deleted // Delete thumb caches from old location: logIO('Old file deleted'); $newFile->rm_cache(); } else { return xmlrpcs_resperror(8, sprintf(T_('The file «%s» already exists.'), $filename)); } } // Trigger plugin event if ($Plugins->trigger_event_first_false('AfterFileUpload', array('File' => &$newFile, 'name' => &$filename, 'type' => &$file_mimetype, 'tmp_name' => &$tmpfile_name, 'size' => &$filesize))) { // Plugin returned 'false'. // Abort upload for this file: @unlink($tmpfile_name); return xmlrpcs_resperror(16, 'File upload aborted by a plugin.'); } if (!mkdir_r($newFile->get_dir())) { // Dir didn't already exist and could not be created return xmlrpcs_resperror(9, 'Error creating sub directories: ' . $newFile->get_rdfs_rel_path()); } if (!@rename($tmpfile_name, $newFile->get_full_path())) { return xmlrpcs_resperror(13, 'Error while writing to file.'); } // chmod the file $newFile->chmod(); // Initializes file properties (type, size, perms...) $newFile->load_properties(); // Load meta data AND MAKE SURE IT IS CREATED IN DB: $newFile->meta == 'unknown'; $newFile->load_meta(true); // Resize and rotate logIO('Running file post-processing (resize and rotate)...'); prepare_uploaded_files(array($newFile)); logIO('Done'); $url = $newFile->get_url(); logIO('URL of new file: ' . $url); $struct = new xmlrpcval(array('file' => new xmlrpcval($filename, 'string'), 'url' => new xmlrpcval($url, 'string'), 'type' => new xmlrpcval($file_mimetype, 'string')), 'struct'); logIO('OK.'); return new xmlrpcresp($struct); }
/** * Update user avatar file to the currently uploaded file * * @return mixed true on success, allowed action otherwise. */ function update_avatar_from_upload() { global $current_User, $Messages, $Settings; if (!$current_User->can_moderate_user($this->ID) && $this->ID != $current_User->ID) { // user is only allowed to update him/herself $Messages->add(T_('You are only allowed to update your own profile!'), 'error'); return 'view'; } // process upload $FileRootCache =& get_FileRootCache(); $root = FileRoot::gen_ID('user', $this->ID); $result = process_upload($root, 'profile_pictures', true, false, true, false, $Settings->get('min_picture_size')); if (empty($result)) { $Messages->add(T_('You don\'t have permission to selected user file root.'), 'error'); return 'view'; } $uploadedFiles = $result['uploadedFiles']; if (!empty($uploadedFiles)) { // upload was successful $File = $uploadedFiles[0]; $duplicated_files = $File->get_duplicated_files(array('root_ID' => $this->ID)); if (!empty($duplicated_files)) { // The file is the duplicate of other profile picture, we should delete it $File->dbdelete(); $Messages->add(T_('It seems you are trying to upload the same profile picture twice.'), 'error'); return 'edit'; } elseif ($File->is_image()) { // uploaded file is an image $LinkOwner = new LinkUser($this); $File->link_to_Object($LinkOwner); $avatar_changed = false; if (empty($this->avatar_file_ID)) { // set uploaded image as avatar $this->set('avatar_file_ID', $File->ID, true); // update profileupdate_date, because a publicly visible user property was changed $this->set_profileupdate_date(); $this->dbupdate(); $avatar_changed = true; $Messages->add(T_('Profile picture has been changed.'), 'success'); } else { // User already has the avatar $Messages->add(T_('New picture has been uploaded.'), 'success'); } // Clear previous Links to load new uploaded file $LinkOwner->clear_Links(); // Send notification email about the changes of user account $this->send_account_changed_notification($avatar_changed, $File->ID); return true; } else { // uploaded file is not an image, delete the file $Messages->add(T_('The file you uploaded does not seem to be an image.')); $File->unlink(); } } $failedFiles = $result['failedFiles']; if (!empty($failedFiles)) { $Messages->add($failedFiles[0]); } return 'edit'; }
/** * Import user's avatar * * @param integer User ID (from b2evo) * @param string Path avatars * @param string File name of user's avatar */ function phpbb_import_avatar($user_ID, $path_avatars, $user_avatar) { global $DB, $tableprefix; if (!empty($user_avatar) && file_exists($path_avatars . $user_avatar)) { // Import user's avatar $FileRootCache =& get_FileRootCache(); $root_ID = FileRoot::gen_ID('user', $user_ID); $imported_file_ID = copy_file($path_avatars . $user_avatar, $root_ID, 'profile_pictures', false); if (!empty($imported_file_ID)) { // Update user's avatar mysqli_query($DB->dbhandle, 'UPDATE ' . $tableprefix . 'users SET user_avatar_file_ID = ' . $DB->quote($imported_file_ID) . ' WHERE user_ID = ' . $DB->quote($user_ID) . ' AND user_avatar_file_ID IS NULL'); // Insert a link with new file global $localtimenow; mysql_query($DB->dbhandle, 'INSERT INTO ' . $tableprefix . 'links ( link_datecreated, link_datemodified, link_creator_user_ID, link_lastedit_user_ID, link_usr_ID, link_file_ID ) VALUES ( ' . $DB->quote(date('Y-m-d H:i:s', $localtimenow)) . ', ' . $DB->quote(date('Y-m-d H:i:s', $localtimenow)) . ', ' . $DB->quote($user_ID) . ', ' . $DB->quote($user_ID) . ', ' . $DB->quote($user_ID) . ', ' . $DB->quote($imported_file_ID) . ' )'); } } }
/** * Create links between users and image files from the users profile_pictures folder */ function create_profile_picture_links() { global $DB; load_class('files/model/_filelist.class.php', 'Filelist'); load_class('files/model/_fileroot.class.php', 'FileRoot'); $path = 'profile_pictures'; $FileRootCache =& get_FileRootCache(); $UserCache =& get_UserCache(); // SQL query to get all users and limit by page below $users_SQL = new SQL(); $users_SQL->SELECT('*'); $users_SQL->FROM('T_users'); $users_SQL->ORDER_BY('user_ID'); $page = 0; $page_size = 100; while (count($UserCache->cache) > 0 || $page == 0) { // Load users by 100 at one time to avoid errors about memory exhausting $users_SQL->LIMIT($page * $page_size . ', ' . $page_size); $UserCache->clear(); $UserCache->load_by_sql($users_SQL); while (($iterator_User =& $UserCache->get_next()) != NULL) { // Iterate through UserCache) $FileRootCache->clear(); $user_FileRoot =& $FileRootCache->get_by_type_and_ID('user', $iterator_User->ID); if (!$user_FileRoot) { // User FileRoot doesn't exist continue; } $ads_list_path = get_canonical_path($user_FileRoot->ads_path . $path); // Previously uploaded avatars if (!is_dir($ads_list_path)) { // profile_picture folder doesn't exists in the user root dir continue; } $user_avatar_Filelist = new Filelist($user_FileRoot, $ads_list_path); $user_avatar_Filelist->load(); if ($user_avatar_Filelist->count() > 0) { // profile_pictures folder is not empty $info_content = ''; $LinkOwner = new LinkUser($iterator_User); while ($lFile =& $user_avatar_Filelist->get_next()) { // Loop through all Files: $fileName = $lFile->get_name(); if (process_filename($fileName)) { // The file has invalid file name, don't create in the database // TODO: asimo> we should collect each invalid file name here, and send an email to the admin continue; } $lFile->load_meta(true); if ($lFile->is_image()) { $lFile->link_to_Object($LinkOwner); } } } } // Increase page number to get next portion of users $page++; } // Clear cache data $UserCache->clear(); $FileRootCache->clear(); }
/** * Display a button to quick upload the files by drag&drop method * * @param integer ID of FileRoot object */ function display_dragdrop_upload_button($params = array()) { global $htsrv_url, $blog, $current_User; $params = array_merge(array('before' => '', 'after' => '', 'fileroot_ID' => 0, 'path' => '', 'list_style' => 'list', 'template_button' => '<div class="qq-uploader">' . '<div class="qq-upload-drop-area"><span>' . TS_('Drop files here to upload') . '</span></div>' . '<div class="qq-upload-button">#button_text#</div>' . '<ul class="qq-upload-list"></ul>' . '</div>', 'template_filerow' => '<li>' . '<span class="qq-upload-file"></span>' . '<span class="qq-upload-spinner"></span>' . '<span class="qq-upload-size"></span>' . '<a class="qq-upload-cancel" href="#">' . TS_('Cancel') . '</a>' . '<span class="qq-upload-failed-text">' . TS_('Failed') . '</span>' . '</li>', 'display_support_msg' => true, 'additional_dropzone' => '', 'filename_before' => '', 'LinkOwner' => NULL, 'display_status_success' => true, 'status_conflict_place' => 'default', 'conflict_file_format' => 'simple', 'resize_frame' => false, 'table_headers' => ''), $params); $FileRootCache =& get_FileRootCache(); $fm_FileRoot = $FileRootCache->get_by_ID($params['fileroot_ID']); if (!is_logged_in() || !$current_User->check_perm('files', 'add', false, $fm_FileRoot)) { // Don't display the button if current user has no permission to upload to the selected file root: return; } $root_and_path = $params['fileroot_ID'] . '::' . $params['path']; $quick_upload_url = $htsrv_url . 'quick_upload.php?upload=true' . (empty($blog) ? '' : '&blog=' . $blog); echo $params['before']; ?> <div id="file-uploader" style="width:100%"> <noscript> <p><?php echo T_('Please enable JavaScript to use file uploader.'); ?> </p> </noscript> </div> <input id="saveBtn" type="submit" style="display:none" name="saveBtn" value="<?php echo T_('Save modified files'); ?> " class="ActionButton" /> <script type="text/javascript"> if( 'draggable' in document.createElement('span') ) { var button_text = '<?php echo TS_('Drag & Drop files to upload here <br /><span>or click to manually select files...</span>'); ?> '; var file_uploader_note_text = '<?php echo TS_('Your browser supports full upload functionality.'); ?> '; } else { var button_text = '<?php echo TS_('Click to manually select files...'); ?> '; var file_uploader_note_text = '<?php echo TS_('Your browser does not support full upload functionality: You can only upload files one by one and you cannot use Drag & Drop.'); ?> '; } var url = <?php echo '"' . $quick_upload_url . '&' . url_crumb('file') . '"'; ?> ; var root_and_path = '<?php echo $root_and_path; ?> '; jQuery( '#fm_dirtree input[type=radio]' ).click( function() { url = "<?php echo $quick_upload_url; ?> "+"&root_and_path="+this.value+"&"+"<?php echo url_crumb('file'); ?> "; root_and_path = this.value; uploader.setParams({root_and_path: root_and_path}); } ); <?php if ($params['LinkOwner'] !== NULL) { // Add params to link a file right after uploading global $b2evo_icons_type; $link_owner_type = $params['LinkOwner']->type; $link_owner_ID = $link_owner_type == 'item' ? $params['LinkOwner']->Item->ID : $params['LinkOwner']->Comment->ID; echo 'url += "&link_owner=' . $link_owner_type . '_' . $link_owner_ID . '&b2evo_icons_type=' . $b2evo_icons_type . '"'; } ?> jQuery( document ).ready( function() { uploader = new qq.FileUploader( { element: document.getElementById( 'file-uploader' ), list_style: '<?php echo $params['list_style']; ?> ', additional_dropzone: '<?php echo $params['additional_dropzone']; ?> ', action: url, debug: true, onSubmit: function( id, fileName ) { var noresults_row = jQuery( 'tr.noresults' ); if( noresults_row.length ) { // Add table headers and remove "No results" row <?php if ($params['table_headers'] != '') { // Append table headers if they are defined ?> noresults_row.parent().parent().prepend( '<?php echo str_replace(array("'", "\n"), array("\\'", ''), $params['table_headers']); ?> ' ); <?php } ?> noresults_row.remove(); } }, onComplete: function( id, fileName, responseJSON ) { if( responseJSON.success != undefined ) { if( responseJSON.success.status == 'fatal' ) { var text = responseJSON.success.text; } else { var text = base64_decode( responseJSON.success.text ); if( responseJSON.success.specialchars == 1 ) { text = htmlspecialchars_decode( text ); } } <?php if ($params['list_style'] == 'list') { // List view ?> if( responseJSON.success.status != undefined && responseJSON.success.status == 'rename' ) { jQuery('#saveBtn').show(); } <?php } ?> } <?php if ($params['list_style'] == 'table') { // Table view ?> var this_row = jQuery( 'tr[rel=file_upload_' + id + ']' ); if( responseJSON.success == undefined || responseJSON.success.status == 'error' || responseJSON.success.status == 'fatal' ) { // Failed this_row.find( '.qq-upload-status' ).html( '<span class="red"><?php echo TS_('Upload ERROR'); ?> </span>' ); if( typeof( text ) == 'undefined' || text == '' ) { // Message for unknown error text = '<?php echo TS_('Server dropped the connection.'); ?> '; } this_row.find( '.qq-upload-file' ).append( ' <span class="result_error">' + text + '</span>' ); this_row.find( '.qq-upload-image, td.size' ).prepend( '<?php echo get_icon('warning_yellow'); ?> ' ); } else { // Success/Conflict var table_view = typeof( responseJSON.success.link_ID ) != 'undefined' ? 'link' : 'file'; var filename_before = '<?php echo str_replace("'", "\\'", $params['filename_before']); ?> '; if( filename_before != '' ) { filename_before = filename_before.replace( '$file_path$', responseJSON.success.path ); } var warning = ''; if( responseJSON.success.warning != '' ) { warning = '<div class="orange">' + responseJSON.success.warning + '</div>'; } // File name or url to view file var file_name = ( typeof( responseJSON.success.link_url ) != 'undefined' ) ? responseJSON.success.link_url : responseJSON.success.newname; if( responseJSON.success.status == 'success' ) { // Success upload <?php if ($params['display_status_success']) { // Display this message only if it is enabled ?> this_row.find( '.qq-upload-status' ).html( '<span class="green"><?php echo TS_('Upload OK'); ?> </span>' ); <?php } else { ?> this_row.find( '.qq-upload-status' ).html( '' ); <?php } ?> this_row.find( '.qq-upload-image' ).html( text ); this_row.find( '.qq-upload-file' ).html( filename_before + '<input type="hidden" value="' + responseJSON.success.newpath + '" />' + '<span class="fname">' + file_name + '</span>' + warning ); } else if( responseJSON.success.status == 'rename' ) { // Conflict on upload <?php $status_conflict_message = '<span class="orange">' . TS_('Upload Conflict') . '</span>'; if ($params['status_conflict_place'] == 'default') { // Default place for a conflict message ?> this_row.find( '.qq-upload-status' ).html( '<?php echo $status_conflict_message; ?> ' ); <?php } else { ?> this_row.find( '.qq-upload-status' ).html( '' ); <?php } ?> this_row.find( '.qq-upload-image' ).append( htmlspecialchars_decode( responseJSON.success.file ) ); this_row.find( '.qq-upload-file' ).html( filename_before + '<input type="hidden" value="' + responseJSON.success.newpath + '" />' + '<span class="fname">' + file_name + '</span>' <?php echo $params['status_conflict_place'] == 'before_button' ? "+ ' - " . $status_conflict_message . "'" : ''; ?> + ' - <a href="#" ' + 'class="<?php echo button_class('text'); ?> roundbutton_text_noicon qq-conflict-replace" ' + 'old="' + responseJSON.success.oldpath + '" ' + 'new="' + responseJSON.success.newpath + '">' + '<div><?php echo TS_('Use this new file to replace the old file'); ?> </div>' + '<div style="display:none"><?php echo TS_('Revert'); ?> </div>' + '</a>' + warning ); var old_file_obj = jQuery( 'input[type=hidden][value="' + responseJSON.success.oldpath + '"]' ); if( old_file_obj.length > 0 ) { old_file_obj.parent().append( ' <span class="orange"><?php echo TS_('(Old File)'); ?> </span>' ); } } if( table_view == 'link' ) { // Update the cells for link view, because these data exist in response this_row.find( '.qq-upload-link-id' ).html( responseJSON.success.link_ID ); this_row.find( '.qq-upload-link-actions' ).prepend( responseJSON.success.link_actions ); this_row.find( '.qq-upload-link-position' ).html( responseJSON.success.link_position ); } } <?php } else { // Simple list ?> jQuery( uploader._getItemByFileId( id ) ).append( text ); if( responseJSON.success == undefined && responseJSON != '' ) { // Disppay the fatal errors jQuery( uploader._getItemByFileId( id ) ).append( responseJSON ); } <?php } if ($params['resize_frame']) { // Resize frame after upload new image ?> update_iframe_height(); jQuery( 'img' ).on( 'load', function() { update_iframe_height(); } ); <?php } ?> }, template: '<?php echo str_replace('#button_text#', "' + button_text + '", $params['template_button']); ?> ', fileTemplate: '<?php echo $params['template_filerow']; ?> ', params: { root_and_path: root_and_path } } ); } ); <?php if ($params['resize_frame']) { // Resize frame after upload new image ?> function update_iframe_height() { var wrapper_height = jQuery( 'body' ).height(); jQuery( 'div#attachmentframe_wrapper', window.parent.document ).css( { 'height': wrapper_height, 'max-height': wrapper_height } ); } <?php } ?> <?php if ($params['list_style'] == 'table') { // A click event for button to replace old file with name ?> jQuery( document ).on( 'click', '.qq-conflict-replace', function() { var this_obj = jQuery( this ); var is_replace = this_obj.children( 'div:first' ).is( ':visible' ); var old_file_name = this_obj.attr( 'old' ); var old_file_obj = jQuery( 'input[type=hidden][value="' + old_file_name + '"]' ); // Element found with old file name on the page var old_file_exists = ( old_file_obj.length > 0 ); this_obj.hide(); // Highlight the rows with new and old files var tr_rows = this_obj.parent().parent().children( 'td' ); if( old_file_exists ) { tr_rows = tr_rows.add( old_file_obj.parent().parent().children( 'td' ) ); } tr_rows.css( 'background', '#FFFF00' ); // Remove previous errors tr_rows.find( 'span.error' ).remove(); jQuery.ajax( { // Replace old file name with new type: 'POST', url: '<?php echo get_secure_htsrv_url(); ?> async.php', data: { action: 'conflict_files', fileroot_ID: '<?php echo $params['fileroot_ID']; ?> ', path: '<?php echo $params['path']; ?> ', oldfile: old_file_name.replace( /^(.+\/)?([^\/]+)$/, '$2' ), newfile: this_obj.attr( 'new' ).replace( /^(.+\/)?([^\/]+)$/, '$2' ), format: '<?php echo $params['conflict_file_format']; ?> ', crumb_conflictfiles: '<?php echo get_crumb('conflictfiles'); ?> ' }, success: function( result ) { var data = jQuery.parseJSON( result ); if( typeof data.error == 'undefined' ) { // Success this_obj.show(); var new_filename_obj = this_obj.parent().find( 'span.fname' ); if( is_replace ) { // The replacing was executed, Change data of html elements this_obj.children( 'div:first' ).hide(); this_obj.children( 'div:last' ).show(); } else { // The replacing was reverting, Put back the data of html elements this_obj.children( 'div:first' ).show(); this_obj.children( 'div:last' ).hide(); } if( old_file_exists ) { // If old file element exists on the page, we can: // Swap old and new names var old_filename_obj = old_file_obj.parent().find( 'span.fname' ); var old_filename_obj_html = old_filename_obj.html(); old_filename_obj.html( new_filename_obj.html() ); new_filename_obj.html( old_filename_obj_html ); var old_icon_link = old_filename_obj.prev(); if( old_icon_link.length == 0 || old_icon_link.get(0).tagName != 'A' ) { old_icon_link = old_filename_obj.parent().prev(); } if( old_icon_link.length > 0 && old_icon_link.get(0).tagName == 'A' ) { // The icons exist to link files, We should swap them var old_href = old_icon_link.attr( 'href' ); old_icon_link.attr( 'href', new_filename_obj.prev().attr( 'href' ) ); new_filename_obj.prev().attr( 'href', old_href ); } } else { // No old file element, Get data from request new_filename_obj.html( is_replace ? data.old : data.new ); } } else { // Failed this_obj.show(); this_obj.parent().append( '<span class="error"> - ' + data.error + '</span>' ); } tr_rows.css( 'background', '' ); } } ); return false; } ); <?php } ?> <?php if ($params['display_support_msg']) { // Display a message about the dragdrop supproting by current browser ?> document.write( '<p class="note">' + file_uploader_note_text + '</p>' ); <?php } ?> </script> <?php echo $params['after']; }
/** * Save to disk and attach to user * * @param object User (User MUST BE created in DB) * @param string content of image file * @param boolean TRUE - to expand photos to a square */ function userimg_attach_photo(&$User, $image_content, $expand_pics) { if (empty($image_content)) { // No image content: return; } // Load FileRoot class: load_class('files/model/_fileroot.class.php', 'FileRoot'); // Try to create FileRoot for the user: $FileRootCache =& get_FileRootCache(); $fileroot_ID = FileRoot::gen_ID('user', $User->ID); $user_FileRoot =& $FileRootCache->get_by_ID($fileroot_ID, true); if (!$user_FileRoot) { // Impossible to create FileRoot for the User $this->debug_log(sprintf('FileRoot cannot be created for User #%s', $User->ID)); // Exit here: return; } // Try to create a folder for image: $folder_name = 'profile_pictures'; // Folder name in user dir where we should store image file $image_name = 'ldap.jpg'; // File name of the image file $folder_path = $user_FileRoot->ads_path . $folder_name; $image_path = $folder_path . '/' . $image_name; if (!mkdir_r($folder_path)) { // Folder cannot be created $this->debug_log(sprintf('Cannot create image folder <b>%s</b>', $folder_path)); // Exit here: return; } // Create/rewrite image file: $image_handle = fopen($image_path, 'w+'); if ($image_handle === false) { // File cannot be created $this->debug_log(sprintf('Cannot create image file <b>%s</b>', $image_path)); // Exit here: return; } // Write image content in the file: fwrite($image_handle, $image_content); fclose($image_handle); // Create file object to work with image: $File = new File('user', $User->ID, $folder_name . '/' . $image_name); $File->rm_cache(); $File->load_meta(true); if ($expand_pics) { // Expand a photo to a square: $this->userimg_expand_to_square($File); } // Link image file to the user: $LinkOwner = new LinkUser($User); $File->link_to_Object($LinkOwner); $avatar_file_ID = $User->get('avatar_file_ID'); if (empty($avatar_file_ID)) { // If user has no main avatar yet then use this new one: $User->set('avatar_file_ID', $File->ID); $User->dbupdate(); } }
/** * Delete a blog and dependencies from database * * @param boolean true if you want to echo progress */ function dbdelete($echo = false) { global $DB, $Messages, $Plugins, $Settings; // Try to obtain some serious time to do some serious processing (5 minutes) set_max_execution_time(300); if ($echo) { echo 'Delete collection with all of it\'s content... '; } // remember ID, because parent method resets it to 0 $old_ID = $this->ID; // Delete main (blog) object: if (!parent::dbdelete()) { $Messages->add('Blog has not been deleted.', 'error'); return false; } // Delete the blog cache folder - try to delete even if cache is disabled load_class('_core/model/_pagecache.class.php', 'PageCache'); $PageCache = new PageCache($this); $PageCache->cache_delete(); // Delete blog's media folder recursively: $FileRootCache =& get_FileRootCache(); if ($root_directory = $FileRootCache->get_root_dir('collection', $old_ID)) { // Delete the folder only when it is detected rmdir_r($root_directory); $Messages->add(T_('Deleted blog\'s files'), 'success'); } // re-set the ID for the Plugin event $this->ID = $old_ID; $Plugins->trigger_event('AfterCollectionDelete', $params = array('Blog' => &$this)); $this->ID = 0; if (isset($Settings)) { // Reset settings related to the deleted blog if ($Settings->get('default_blog_ID') == $old_ID) { // Reset default blog ID $Settings->set('default_blog_ID', 0); } if ($Settings->get('info_blog_ID') == $old_ID) { // Reset info blog ID $Settings->set('info_blog_ID', 0); } if ($Settings->get('login_blog_ID') == $old_ID) { // Reset login blog ID $Settings->set('login_blog_ID', 0); } if ($Settings->get('msg_blog_ID') == $old_ID) { // Reset messaging blog ID $Settings->set('msg_blog_ID', 0); } $Settings->dbupdate(); } if ($echo) { echo '<br />Done.</p>'; } return true; }
/** * Import WordPress data from XML file into b2evolution database */ function wpxml_import() { global $DB, $tableprefix; // Load classes: load_class('regional/model/_country.class.php', 'Country'); load_class('regional/model/_region.class.php', 'Region'); load_class('regional/model/_subregion.class.php', 'Subregion'); load_class('regional/model/_city.class.php', 'City'); // Set Blog from request blog ID $wp_blog_ID = param('wp_blog_ID', 'integer', 0); $BlogCache =& get_BlogCache(); $wp_Blog =& $BlogCache->get_by_ID($wp_blog_ID); // The import type ( replace | append ) $import_type = param('import_type', 'string', 'replace'); // Should we delete files on 'replace' mode? $delete_files = param('delete_files', 'integer', 0); $XML_file_path = get_param('wp_file'); $XML_file_name = basename($XML_file_path); if (preg_match('/\\.(xml|txt)$/i', $XML_file_name)) { // XML format // Check WordPress XML file if (!wpxml_check_xml_file($XML_file_path)) { // Errors are in XML file return; } // Use this folder to upload files if they exist in subfolder "/b2evolution_export_files" $attached_files_path = dirname($XML_file_path); } else { if (preg_match('/\\.zip$/i', $XML_file_name)) { // ZIP format // Extract ZIP and check WordPress XML file global $media_path; $ZIP_folder_path = $media_path . 'import/temp-' . md5(rand()); if (!unpack_archive($XML_file_path, $ZIP_folder_path, true, $XML_file_name)) { // Errors on unpack ZIP file return; } // Find valid XML file in ZIP package $ZIP_files_list = scandir($ZIP_folder_path); $xml_exists_in_zip = false; foreach ($ZIP_files_list as $ZIP_file) { if (preg_match('/\\.(xml|txt)$/i', $ZIP_file)) { // XML file is found in ZIP package if (wpxml_check_xml_file($ZIP_folder_path . '/' . $ZIP_file)) { // XML file is valid $XML_file_path = $ZIP_folder_path . '/' . $ZIP_file; $xml_exists_in_zip = true; break; } } } if (!$xml_exists_in_zip) { // No XML is detected in ZIP package echo '<p style="color:red">' . T_('XML file is not detected in your ZIP package.') . '</p>'; // Delete temporary folder that contains the files from extracted ZIP package rmdir_r($ZIP_folder_path); return; } // Use this folder to upload files, $ZIP_folder_path must be deleted after import $attached_files_path = $ZIP_folder_path; } else { // Unrecognized extension echo '<p style="color:red">' . sprintf(T_('%s has an unrecognized extension.'), '<b>' . $xml_file['name'] . '</b>') . '</p>'; return; } } // Parse WordPress XML file into array $xml_data = wpxml_parser($XML_file_path); $DB->begin(); if ($import_type == 'replace') { // Remove data from selected blog // Get existing categories $SQL = new SQL(); $SQL->SELECT('cat_ID'); $SQL->FROM('T_categories'); $SQL->WHERE('cat_blog_ID = ' . $DB->quote($wp_blog_ID)); $old_categories = $DB->get_col($SQL->get()); if (!empty($old_categories)) { // Get existing posts $SQL = new SQL(); $SQL->SELECT('post_ID'); $SQL->FROM('T_items__item'); $SQL->WHERE('post_main_cat_ID IN ( ' . implode(', ', $old_categories) . ' )'); $old_posts = $DB->get_col($SQL->get()); } echo T_('Removing the comments... '); evo_flush(); if (!empty($old_posts)) { $SQL = new SQL(); $SQL->SELECT('comment_ID'); $SQL->FROM('T_comments'); $SQL->WHERE('comment_item_ID IN ( ' . implode(', ', $old_posts) . ' )'); $old_comments = $DB->get_col($SQL->get()); $DB->query('DELETE FROM T_comments WHERE comment_item_ID IN ( ' . implode(', ', $old_posts) . ' )'); if (!empty($old_comments)) { $DB->query('DELETE FROM T_comments__votes WHERE cmvt_cmt_ID IN ( ' . implode(', ', $old_comments) . ' )'); $DB->query('DELETE FROM T_links WHERE link_cmt_ID IN ( ' . implode(', ', $old_comments) . ' )'); } } echo T_('OK') . '<br />'; echo T_('Removing the posts... '); evo_flush(); if (!empty($old_categories)) { $DB->query('DELETE FROM T_items__item WHERE post_main_cat_ID IN ( ' . implode(', ', $old_categories) . ' )'); if (!empty($old_posts)) { // Remove the post's data from related tables if ($delete_files) { // Get the file IDs that should be deleted from hard drive $SQL = new SQL(); $SQL->SELECT('DISTINCT link_file_ID'); $SQL->FROM('T_links'); $SQL->WHERE('link_itm_ID IN ( ' . implode(', ', $old_posts) . ' )'); $deleted_file_IDs = $DB->get_col($SQL->get()); } $DB->query('DELETE FROM T_items__item_settings WHERE iset_item_ID IN ( ' . implode(', ', $old_posts) . ' )'); $DB->query('DELETE FROM T_items__prerendering WHERE itpr_itm_ID IN ( ' . implode(', ', $old_posts) . ' )'); $DB->query('DELETE FROM T_items__subscriptions WHERE isub_item_ID IN ( ' . implode(', ', $old_posts) . ' )'); $DB->query('DELETE FROM T_items__version WHERE iver_itm_ID IN ( ' . implode(', ', $old_posts) . ' )'); $DB->query('DELETE FROM T_postcats WHERE postcat_post_ID IN ( ' . implode(', ', $old_posts) . ' )'); $DB->query('DELETE FROM T_slug WHERE slug_itm_ID IN ( ' . implode(', ', $old_posts) . ' )'); $DB->query('DELETE l, lv FROM T_links AS l LEFT JOIN T_links__vote AS lv ON lv.lvot_link_ID = l.link_ID WHERE l.link_itm_ID IN ( ' . implode(', ', $old_posts) . ' )'); $DB->query('DELETE FROM T_users__postreadstatus WHERE uprs_post_ID IN ( ' . implode(', ', $old_posts) . ' )'); } } echo T_('OK') . '<br />'; echo T_('Removing the categories... '); evo_flush(); $DB->query('DELETE FROM T_categories WHERE cat_blog_ID = ' . $DB->quote($wp_blog_ID)); echo T_('OK') . '<br />'; echo T_('Removing the tags that are no longer used... '); evo_flush(); if (!empty($old_posts)) { // Remove the tags // Get tags from selected blog $SQL = new SQL(); $SQL->SELECT('itag_tag_ID'); $SQL->FROM('T_items__itemtag'); $SQL->WHERE('itag_itm_ID IN ( ' . implode(', ', $old_posts) . ' )'); $old_tags_this_blog = array_unique($DB->get_col($SQL->get())); if (!empty($old_tags_this_blog)) { // Get tags from other blogs $SQL = new SQL(); $SQL->SELECT('itag_tag_ID'); $SQL->FROM('T_items__itemtag'); $SQL->WHERE('itag_itm_ID NOT IN ( ' . implode(', ', $old_posts) . ' )'); $old_tags_other_blogs = array_unique($DB->get_col($SQL->get())); $old_tags_other_blogs_sql = !empty($old_tags_other_blogs) ? ' AND tag_ID NOT IN ( ' . implode(', ', $old_tags_other_blogs) . ' )' : ''; // Remove the tags that are no longer used $DB->query('DELETE FROM T_items__tag WHERE tag_ID IN ( ' . implode(', ', $old_tags_this_blog) . ' )' . $old_tags_other_blogs_sql); } // Remove the links of tags with posts $DB->query('DELETE FROM T_items__itemtag WHERE itag_itm_ID IN ( ' . implode(', ', $old_posts) . ' )'); } echo T_('OK') . '<br />'; if ($delete_files) { // Delete the files echo T_('Removing the files... '); if (!empty($deleted_file_IDs)) { // Commit the DB changes before files deleting $DB->commit(); // Get the deleted file IDs that are linked to other objects $SQL = new SQL(); $SQL->SELECT('DISTINCT link_file_ID'); $SQL->FROM('T_links'); $SQL->WHERE('link_file_ID IN ( ' . implode(', ', $deleted_file_IDs) . ' )'); $linked_file_IDs = $DB->get_col($SQL->get()); // We can delete only the files that are NOT linked to other objects $deleted_file_IDs = array_diff($deleted_file_IDs, $linked_file_IDs); $FileCache =& get_FileCache(); foreach ($deleted_file_IDs as $deleted_file_ID) { if (!($deleted_File =& $FileCache->get_by_ID($deleted_file_ID, false, false))) { // Incorrect file ID echo '<p class="red">' . sprintf(T_('No file #%s found in DB. It cannot be deleted.'), $deleted_file_ID) . '</p>'; } if (!$deleted_File->unlink()) { // No permission to delete file echo '<p class="red">' . sprintf(T_('Could not delete the file «%s».'), $deleted_File->get_full_path()) . '</p>'; } // Clear cache to save memory $FileCache->clear(); } // Start new transaction for the data inserting $DB->begin(); } echo T_('OK') . '<br />'; } echo '<br />'; } /* Import authors */ $authors = array(); $authors_IDs = array(); if (isset($xml_data['authors']) && count($xml_data['authors']) > 0) { global $Settings, $UserSettings; echo T_('Importing the users... '); evo_flush(); // Get existing users $SQL = new SQL(); $SQL->SELECT('user_login, user_ID'); $SQL->FROM('T_users'); $existing_users = $DB->get_assoc($SQL->get()); $authors_count = 0; foreach ($xml_data['authors'] as $author) { if (empty($existing_users[(string) $author['author_login']])) { // Insert new user into DB if User doesn't exist with current login name $GroupCache =& get_GroupCache(); if (!empty($author['author_group'])) { // Set user group from xml data if (($UserGroup =& $GroupCache->get_by_name($author['author_group'], false)) === false) { // If user's group doesn't exist yet, we should create new $UserGroup = new Group(); $UserGroup->set('name', $author['author_group']); $UserGroup->dbinsert(); } } else { // Set default user group is it is not defined in xml if (($UserGroup =& $GroupCache->get_by_name('Normal Users', false)) === false) { // Exit from import of users, because we cannot set default user group break; } } unset($author_created_from_country); if (!empty($author['author_created_from_country'])) { // Get country ID from DB by code $CountryCache =& get_CountryCache(); if (($Country =& $CountryCache->get_by_name($author['author_created_from_country'], false)) !== false) { $author_created_from_country = $Country->ID; } } // Get regional IDs by their names $author_regions = wp_get_regional_data($author['author_country'], $author['author_region'], $author['author_subregion'], $author['author_city']); $User = new User(); $User->set('login', $author['author_login']); $User->set('email', $author['author_email']); $User->set('firstname', $author['author_first_name']); $User->set('lastname', $author['author_last_name']); $User->set('pass', $author['author_pass']); $User->set_Group($UserGroup); $User->set('status', !empty($author['author_status']) ? $author['author_status'] : 'autoactivated'); $User->set('nickname', $author['author_nickname']); $User->set('url', $author['author_url']); $User->set('level', $author['author_level']); $User->set('locale', $author['author_locale']); $User->set('gender', $author['author_gender'] == 'female' ? 'F' : ($author['author_gender'] == 'male' ? 'M' : '')); if ($author['author_age_min'] > 0) { $User->set('age_min', $author['author_age_min']); } if ($author['author_age_max'] > 0) { $User->set('age_max', $author['author_age_max']); } if (isset($author_created_from_country)) { // User was created from this country $User->set('reg_ctry_ID', $author_created_from_country); } if (!empty($author_regions['country'])) { // Country $User->set('ctry_ID', $author_regions['country']); if (!empty($author_regions['region'])) { // Region $User->set('rgn_ID', $author_regions['region']); if (!empty($author_regions['subregion'])) { // Subregion $User->set('subrg_ID', $author_regions['subregion']); } if (!empty($author_regions['city'])) { // City $User->set('city_ID', $author_regions['city']); } } } $User->set('source', $author['author_source']); $User->set_datecreated(empty($author['author_created_ts']) ? mktime() : intval($author['author_created_ts'])); $User->set('lastseen_ts', empty($author['author_lastseen_ts']) ? NULL : $author['author_lastseen_ts'], true); $User->set('profileupdate_date', empty($author['author_profileupdate_date']) ? date('Y-m-d', mktime()) : $author['author_profileupdate_date']); $User->dbinsert(); $user_ID = $User->ID; if (!empty($user_ID) && !empty($author['author_created_fromIPv4'])) { $UserSettings->set('created_fromIPv4', ip2int($author['author_created_fromIPv4']), $user_ID); } $authors_count++; } else { // Get ID of existing user $user_ID = $existing_users[(string) $author['author_login']]; } // Save user ID of current author $authors[$author['author_login']] = (string) $user_ID; $authors_IDs[$author['author_id']] = (string) $user_ID; } $UserSettings->dbupdate(); echo sprintf(T_('%d records'), $authors_count) . '<br />'; } /* Import files, Copy them all to media folder */ if (isset($xml_data['files']) && count($xml_data['files']) > 0) { echo T_('Importing the files... '); evo_flush(); if (!file_exists($attached_files_path . '/b2evolution_export_files')) { // Display an error if files are attached but folder doesn't exist echo '<p class="red">' . sprintf(T_('No folder %s found. It must exists to import the attached files properly.'), '<b>' . $attached_files_path . '/b2evolution_export_files' . '</b>') . '</p>'; } else { // The attached files are located in this subfolder $subfolder_path = '/b2evolution_export_files'; $files_count = 0; $files = array(); foreach ($xml_data['files'] as $file) { switch ($file['file_root_type']) { case 'shared': // Shared files $file_root_ID = 0; break; case 'user': // User's files if (isset($authors_IDs[$file['file_root_ID']])) { // If owner of this file exists in our DB $file_root_ID = $authors_IDs[$file['file_root_ID']]; break; } // Otherwise we should upload this file into blog's folder: // Otherwise we should upload this file into blog's folder: default: // 'collection', 'absolute', 'skins' // The files from other blogs and from other places must be moved in the folder of the current blog $file['file_root_type'] = 'collection'; $file_root_ID = $wp_blog_ID; break; } // Get FileRoot by type and ID $FileRootCache =& get_FileRootCache(); $FileRoot =& $FileRootCache->get_by_type_and_ID($file['file_root_type'], $file_root_ID); if (is_dir($attached_files_path . $subfolder_path . '/' . $file['zip_path'] . $file['file_path'])) { // Folder $file_destination_path = $FileRoot->ads_path; } else { // File $file_destination_path = $FileRoot->ads_path . $file['file_path']; } if (!file_exists($attached_files_path . $subfolder_path . '/' . $file['zip_path'] . $file['file_path'])) { // File doesn't exist echo '<p class="orange">' . sprintf(T_('Unable to copy file %s, because it does not exist.'), '<b>' . $file['zip_path'] . $file['file_path'] . '</b>') . '</p>'; // Skip it continue; } else { if (!copy_r($attached_files_path . $subfolder_path . '/' . $file['zip_path'] . $file['file_path'], $file_destination_path)) { // No permission to copy to this folder if (is_dir($attached_files_path . $subfolder_path . '/' . $file['zip_path'] . $file['file_path'])) { // Folder echo '<p class="orange">' . sprintf(T_('Unable to copy folder %s to %s. Please, check the permissions assigned to this folder.'), '<b>' . $file['zip_path'] . $file['file_path'] . '</b>', '<b>' . $file_destination_path . '</b>') . '</p>'; } else { // File echo '<p class="orange">' . sprintf(T_('Unable to copy file %s to %s. Please, check the permissions assigned to this folder.'), '<b>' . $file['zip_path'] . $file['file_path'] . '</b>', '<b>' . $file_destination_path . '</b>') . '</p>'; } // Skip it continue; } } // Create new File object, It will be linked to the items below $File = new File($file['file_root_type'], $file_root_ID, $file['file_path']); $File->set('title', $file['file_title']); $File->set('alt', $file['file_alt']); $File->set('desc', $file['file_desc']); $files[$file['file_ID']] = $File; $files_count++; } echo sprintf(T_('%d records'), $files_count) . '<br />'; if (isset($ZIP_folder_path) && file_exists($ZIP_folder_path)) { // This folder was created only to extract files from ZIP package, Remove it now rmdir_r($ZIP_folder_path); } } } /* Import categories */ $category_default = 0; load_class('chapters/model/_chapter.class.php', 'Chapter'); // Get existing categories $SQL = new SQL(); $SQL->SELECT('cat_urlname, cat_ID'); $SQL->FROM('T_categories'); $SQL->WHERE('cat_blog_ID = ' . $DB->quote($wp_blog_ID)); $categories = $DB->get_assoc($SQL->get()); if (isset($xml_data['categories']) && count($xml_data['categories']) > 0) { echo T_('Importing the categories... '); evo_flush(); load_funcs('locales/_charset.funcs.php'); $categories_count = 0; foreach ($xml_data['categories'] as $cat) { if (empty($categories[(string) $cat['category_nicename']])) { $Chapter = new Chapter(NULL, $wp_blog_ID); $Chapter->set('name', $cat['cat_name']); $Chapter->set('urlname', $cat['category_nicename']); $Chapter->set('description', $cat['category_description']); if (!empty($cat['category_parent']) && isset($categories[(string) $cat['category_parent']])) { // Set category parent ID $Chapter->set('parent_ID', $categories[(string) $cat['category_parent']]); } $Chapter->dbinsert(); // Save new category $categories[$cat['category_nicename']] = $Chapter->ID; if (empty($category_default)) { // Set first category as default $category_default = $Chapter->ID; } $categories_count++; } } echo sprintf(T_('%d records'), $categories_count) . '<br />'; } if (empty($category_default)) { // No categories in XML file, Try to use first category(from DB) as default foreach ($categories as $category_name => $category_ID) { $category_default = $category_ID; break; } } if (empty($category_default)) { // If category is still not defined then we should create default, because blog must has at least one category $new_Chapter = new Chapter(NULL, $wp_blog_ID); $new_Chapter->set('name', T_('Uncategorized')); $new_Chapter->set('urlname', $wp_Blog->get('urlname') . '-main'); $new_Chapter->dbinsert(); $category_default = $new_Chapter->ID; } /* Import tags */ $tags = array(); if (isset($xml_data['tags']) && count($xml_data['tags']) > 0) { echo T_('Importing the tags... '); evo_flush(); // Get existing tags $SQL = new SQL(); $SQL->SELECT('tag_name, tag_ID'); $SQL->FROM('T_items__tag'); $tags = $DB->get_assoc($SQL->get()); $tags_count = 0; foreach ($xml_data['tags'] as $tag) { if (empty($tags[(string) $tag['tag_name']])) { // Insert new tag into DB if tag doesn't exist with current name mysqli_query($DB->dbhandle, 'INSERT INTO ' . $tableprefix . 'items__tag ( tag_name ) VALUES ( ' . $DB->quote($tag['tag_name']) . ' )'); $tag_ID = mysqli_insert_id($DB->dbhandle); // Save new tag $tags[$tag['tag_name']] = (string) $tag_ID; $tags_count++; } } echo sprintf(T_('%d records'), $tags_count) . '<br />'; } /* Import posts */ $posts = array(); $comments = array(); if (isset($xml_data['posts']) && count($xml_data['posts']) > 0) { load_class('items/model/_item.class.php', 'Item'); // Set status's links between WP and b2evo names $post_statuses = array('publish' => 'published', 'pending' => 'review', 'draft' => 'draft', 'trash' => 'deprecated', 'community' => 'community', 'deprecated' => 'deprecated', 'protected' => 'protected', 'private' => 'private', 'review' => 'review', 'redirected' => 'redirected'); // Get post types $SQL = new SQL(); $SQL->SELECT('LOWER( ityp_name ), ityp_ID'); $SQL->FROM('T_items__type'); $post_types = $DB->get_assoc($SQL->get()); echo T_('Importing the posts... '); evo_flush(); foreach ($xml_data['posts'] as $post) { $author_ID = isset($authors[(string) $post['post_author']]) ? $authors[(string) $post['post_author']] : 1; $last_edit_user_ID = isset($authors[(string) $post['post_lastedit_user']]) ? $authors[(string) $post['post_lastedit_user']] : $author_ID; $post_main_cat_ID = $category_default; $post_extra_cat_IDs = array(); $post_tags = array(); if (!empty($post['terms'])) { // Set categories and tags foreach ($post['terms'] as $term) { switch ($term['domain']) { case 'category': if (isset($categories[(string) $term['slug']])) { if ($post_main_cat_ID == $category_default) { // Set main category $post_main_cat_ID = $categories[(string) $term['slug']]; } // Set extra categories $post_extra_cat_IDs[] = $categories[(string) $term['slug']]; } break; case 'post_tag': if (isset($tags[(string) $term['slug']])) { // Set tag $post_tags[] = $term['slug']; } break; } } } // Set post type ID $post_type_ID = isset($post_types[strtolower($post['post_type'])]) ? $post_types[strtolower($post['post_type'])] : '1'; // Get regional IDs by their names $item_regions = wp_get_regional_data($post['post_country'], $post['post_region'], $post['post_subregion'], $post['post_city']); $Item = new Item(); $Item->set('main_cat_ID', $post_main_cat_ID); $Item->set('creator_user_ID', $author_ID); $Item->set('lastedit_user_ID', $last_edit_user_ID); $Item->set('title', $post['post_title']); $Item->set('content', $post['post_content']); $Item->set('excerpt', $post['post_excerpt']); $Item->set('datestart', $post['post_date']); $Item->set('datecreated', !empty($post['post_datecreated']) ? $post['post_datecreated'] : $post['post_date']); $Item->set('datemodified', !empty($post['post_datemodified']) ? $post['post_datemodified'] : $post['post_date']); $Item->set('urltitle', !empty($post['post_urltitle']) ? $post['post_urltitle'] : $post['post_title']); $Item->set('url', $post['post_url']); $Item->set('status', isset($post_statuses[(string) $post['status']]) ? $post_statuses[(string) $post['status']] : 'review'); // If 'comment_status' has the unappropriate value set it to 'open' $Item->set('comment_status', in_array($post['comment_status'], array('open', 'closed', 'disabled')) ? $post['comment_status'] : 'open'); $Item->set('ityp_ID', $post_type_ID); if (empty($post['post_excerpt']) && !empty($post['post_content'])) { // Generate excerpt $Item->set('excerpt', excerpt($post['post_content'])); $Item->set('excerpt_autogenerated', '1'); } $Item->set('extra_cat_IDs', $post_extra_cat_IDs); $Item->set('dateset', $post['post_date_mode'] == 'set' ? 1 : 0); if (isset($authors[(string) $post['post_assigned_user']])) { $Item->set('assigned_user', $authors[(string) $post['post_assigned_user']]); } $Item->set('datedeadline', $post['post_datedeadline']); $Item->set('locale', $post['post_locale']); $Item->set('excerpt_autogenerated', $post['post_excerpt_autogenerated']); $Item->set('titletag', $post['post_titletag']); $Item->set('notifications_status', empty($post['post_notifications_status']) ? 'noreq' : $post['post_notifications_status']); $Item->set('renderers', array($post['post_renderers'])); $Item->set('priority', $post['post_priority']); $Item->set('featured', $post['post_featured']); $Item->set('order', $post['post_order']); if (!empty($item_regions['country'])) { // Country $Item->set('ctry_ID', $item_regions['country']); if (!empty($item_regions['region'])) { // Region $Item->set('rgn_ID', $item_regions['region']); if (!empty($item_regions['subregion'])) { // Subregion $Item->set('subrg_ID', $item_regions['subregion']); } if (!empty($item_regions['city'])) { // City $Item->set('city_ID', $item_regions['city']); } } } if (count($post_tags) > 0) { $Item->tags = $post_tags; } $Item->dbinsert(); $posts[$post['post_id']] = $Item->ID; if (!empty($files) && !empty($post['links'])) { // Link the files to the Item if it has them foreach ($post['links'] as $link) { if (isset($files[$link['link_file_ID']])) { // Link a file to Item $File = $files[$link['link_file_ID']]; $LinkOwner = new LinkItem($Item); $File->link_to_Object($LinkOwner, $link['link_order'], $link['link_position']); } } } if (!empty($post['comments'])) { // Set comments $comments[$Item->ID] = $post['comments']; } } foreach ($xml_data['posts'] as $post) { // Set post parents if (!empty($post['post_parent']) && isset($posts[(string) $post['post_parent']])) { mysqli_query($DB->dbhandle, 'UPDATE ' . $tableprefix . 'items__item SET post_parent_ID = ' . $DB->quote($posts[(string) $post['post_parent']]) . ' WHERE post_ID = ' . $DB->quote($posts[(string) $post['post_id']])); } } echo sprintf(T_('%d records'), count($xml_data['posts'])) . '<br />'; } /* Import comments */ if (!empty($comments)) { echo T_('Importing the comments... '); evo_flush(); $comments_count = 0; $comments_IDs = array(); foreach ($comments as $post_ID => $comments) { if (empty($comments)) { // Skip if no comments continue; } foreach ($comments as $comment) { $comment_author_user_ID = 0; if (!empty($comment['comment_user_id']) && isset($authors_IDs[(string) $comment['comment_user_id']])) { // Author ID $comment_author_user_ID = $authors_IDs[(string) $comment['comment_user_id']]; } $comment_parent_ID = 0; if (!empty($comment['comment_parent']) && isset($comments_IDs[(string) $comment['comment_parent']])) { // Parent comment ID $comment_parent_ID = $comments_IDs[(string) $comment['comment_parent']]; } unset($comment_IP_country); if (!empty($comment['comment_IP_country'])) { // Get country ID by code $CountryCache =& get_CountryCache(); if ($Country =& $CountryCache->get_by_name($comment['comment_IP_country'], false)) { $comment_IP_country = $Country->ID; } } $Comment = new Comment(); $Comment->set('item_ID', $post_ID); if (!empty($comment_parent_ID)) { $Comment->set('in_reply_to_cmt_ID', $comment_parent_ID); } $Comment->set('date', $comment['comment_date']); if (!empty($comment_author_user_ID)) { $Comment->set('author_user_ID', $comment_author_user_ID); } $Comment->set('author', utf8_substr($comment['comment_author'], 0, 100)); $Comment->set('author_IP', $comment['comment_author_IP']); $Comment->set('author_email', $comment['comment_author_email']); $Comment->set('content', $comment['comment_content']); if (empty($comment['comment_status'])) { // If comment status is empty (the export of wordpress doesn't provide this field) $Comment->set('status', $comment['comment_approved'] == '1' ? 'published' : 'draft'); } else { // Set status when we have predefined value $Comment->set('status', $comment['comment_status']); } if (!empty($comment_IP_country)) { // Country $Comment->set('IP_ctry_ID', $comment_IP_country); } $Comment->set('rating', $comment['comment_rating']); $Comment->set('featured', $comment['comment_featured']); $Comment->set('nofollow', $comment['comment_nofollow']); $Comment->set('helpful_addvotes', $comment['comment_helpful_addvotes']); $Comment->set('helpful_countvotes', $comment['comment_helpful_countvotes']); $Comment->set('spam_addvotes', $comment['comment_spam_addvotes']); $Comment->set('spam_countvotes', $comment['comment_spam_countvotes']); $Comment->set('karma', $comment['comment_karma']); $Comment->set('spam_karma', $comment['comment_spam_karma']); $Comment->set('allow_msgform', $comment['comment_allow_msgform']); $Comment->set('notif_status', empty($comment['comment_notif_status']) ? 'noreq' : $comment['comment_notif_status']); $Comment->dbinsert(); $comments_IDs[$comment['comment_id']] = $Comment->ID; $comments_count++; } } echo sprintf(T_('%d records'), $comments_count) . '<br />'; } echo '<p>' . T_('Import complete.') . '</p>'; $DB->commit(); }
/** * Move the file to another location * * Also updates meta data in DB * * @param string Root type: 'user', 'group', 'collection' or 'absolute' * @param integer ID of the user, the group or the collection the file belongs to... * @param string Subpath for this file/folder, relative the associated root (no trailing slash) * @return boolean true on success, false on failure */ function move_to($root_type, $root_ID, $rdfp_rel_path) { $old_file_name = $this->get_name(); // echo "relpath= $rel_path "; $rdfp_rel_path = str_replace('\\', '/', $rdfp_rel_path); $FileRootCache =& get_FileRootCache(); $new_FileRoot =& $FileRootCache->get_by_type_and_ID($root_type, $root_ID, true); $adfp_posix_path = $new_FileRoot->ads_path . $rdfp_rel_path; if (!@rename($this->_adfp_full_path, $adfp_posix_path)) { syslog_insert(sprintf('File %s could not be moved to %s', '<b>' . $old_file_name . '</b>', '<b>' . $rdfp_rel_path . '</b>'), 'info', 'file', $this->ID); return false; } // Delete thumb caches from old location: // Note: new location = new usage : there is a fair chance we won't need the same cache sizes in the new loc. $this->rm_cache(); // Get Meta data (before we change name) (we may need to update it later): $this->load_meta(); // Memorize new filepath: $this->_FileRoot =& $new_FileRoot; $this->_rdfp_rel_path = $rdfp_rel_path; $this->_adfp_full_path = $adfp_posix_path; $this->_name = basename($this->_adfp_full_path); $this->Filetype = NULL; // depends on name $this->_dir = dirname($this->_adfp_full_path) . '/'; $this->_md5ID = md5($this->_adfp_full_path); if ($this->meta == 'loaded') { // We have meta data, we need to deal with it: $this->set('root_type', $this->_FileRoot->type); $this->set('root_ID', $this->_FileRoot->in_type_ID); $this->set('path', $this->_rdfp_rel_path); // Record to DB: $this->dbupdate(); } else { // There might be some old meta data to *recycle* in the DB... // This can happen if there has been a file in the same location in the past and if that file // has been manually deleted or moved since then. When the new file arrives here, we'll recover // the zombie meta data and we don't reset it on purpose. Actually, we consider that the meta data // has been *accidentaly* lost and that the user is attempting to recover it by putting back the // file where it was before. Of course the logical way would be to put back the file manually, but // experience proves that users are inconsistent! $this->load_meta(); } syslog_insert(sprintf('File %s was moved to %s', '<b>' . $old_file_name . '</b>', '<b>' . $rdfp_rel_path . '</b>'), 'info', 'file', $this->ID); return true; }