diff --git a/bath.php b/bath.php new file mode 100644 index 0000000..9617a50 --- /dev/null +++ b/bath.php @@ -0,0 +1,226 @@ +prefix . 'batch_operations'; + + $charset_collate = $wpdb->get_charset_collate(); + + $sql = "CREATE TABLE $table_name ( + `id` bigint(20) NOT NULL AUTO_INCREMENT, + `operations` longtext NOT NULL, + PRIMARY KEY (`id`) + ) $charset_collate AUTO_INCREMENT=1;"; + + require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); + dbDelta( $sql ); + +} + +/** + * Add backend page without menu item + */ +function batch_operations_add_page() { + add_management_page( 'Batch operations', '', 'edit_posts', 'batch-operations', 'batch_operations_page_view' ); +} + +/** + * View batch operations page + */ +function batch_operations_page_view() { + //WP 3.3 + wp_enqueue_script( 'jquery' ); + wp_enqueue_script( 'batch_operations_script', plugin_dir_url('') . 'batch-operations/js/batch.min.js' ); + wp_enqueue_style( 'batch_operations_script', plugin_dir_url('') . 'batch-operations/css/batch.css' ); + $id = ( intval( $_REQUEST["id"] ) < 0 )? 0 : intval( $_REQUEST["id"] ); + ?> + +
+ +

+
+ +
+
+ +
+ $id ){ + wp_send_json( array( 'do' => 'finish' ) ); + } + + $carr = $wpdb->get_var( 'SELECT `operations` FROM `' . $wpdb->prefix . "batch_operations` WHERE `id` = $id;" ); + if ( empty( $carr ) ) { + wp_send_json( array( 'do' => 'finish' ) ); + } + + $result['do'] = ''; + $start = time() + 1; + $flag = true; + $carr = unserialize( $carr ); + + while ($flag) { + //make array of parameters for function + $arr = array(); + if ( isset( $carr['operations'][0][1] ) ) { + $arr = $carr['operations'][0][1]; + } + $arr[] = &$carr['context']; + //run function + call_user_func_array( $carr['operations'][0][0], $arr ); + + if ( true == $carr['context']['finished'] ) { + $carr['context']['sandbox'] = array(); + array_splice( $carr['operations'], 0, 1 ); + $carr['current']++; + } + + if ( time() > $start || 0 == count($carr['operations']) ) { + $flag=false; + } + } + + if ( 0 == count($carr['operations']) ) { + $result['do']='finish'; + } + + $result['percent'] = round( $carr['current'] / ($carr['count'] /100 ) ); + $result['message'] = $carr['context']['message']; + + if ( '' == $result['do'] ) { + $wpdb->update( + $wpdb->prefix . 'batch_operations', + array( 'operations' => serialize( $carr ) ), + array( 'id' => $id ), + array( '%s' ), + array( '%d' ) + ); + } else { + $wpdb->query( 'DELETE FROM `' . $wpdb->prefix . 'batch_operations' . "` WHERE `id`=$id ;" ); + } + + wp_send_json( $result ); +} + + +/** + * Start batch operations + * + *
+ * $batch = array(
+ *   'title' => t('Exporting'),
+ *   'operations' => array(
+ *     array('my_function_1', array(123, 'qwe')),
+ *     array('my_function_2', array()),
+ *   ),
+ *   'finished' => 'my_finished_callback',
+ * );
+ *
+ * BatchController::Start($batch);
+ * 
+ * + *