<?php
global $wpdb;
global $upload_folder_path;
$tmppath = $upload_folder_path."csv/";
if($_POST)
{
	if($_FILES['bulk_upload_csv']['name']!='' && $_FILES['bulk_upload_csv']['error']=='0')
	{
		$filename = $_FILES['bulk_upload_csv']['name'];
		$filenamearr = explode('.',$filename);
		$extensionarr = array('csv','CSV');
		
		if(in_array($filenamearr[count($filenamearr)-1],$extensionarr))
		{
			$tmppath = $upload_folder_path."csv/";
			$destination_path = ABSPATH . "$tmppath";
			if (!file_exists($destination_path))
			{
				mkdir($destination_path, 0777);				
			}
			$target_path = $destination_path . $filename;
			$csv_target_path = $target_path;
			if(move_uploaded_file($_FILES['bulk_upload_csv']['tmp_name'], $target_path)) 
			{
				$fd = fopen ($target_path, "rt");

				$rowcount = 0;
				$customKeyarray = array();
				while (!feof ($fd))
				{
					$buffer = fgetcsv($fd, 4096);
					if($rowcount == 0)
					{
						for($k=0;$k<count($buffer);$k++)
						{
							$customKeyarray[$k] = $buffer[$k];
						}
						if($customKeyarray[0]=='')
						{
							$url = get_option('siteurl').'/wp-admin/admin.php';
							echo '<form action="'.$url.'" method="get" id="frm_bulk_upload" name="frm_bulk_upload">
							<input type="hidden" value="bulk" name="page"><input type="hidden" value="wrong" name="emsg">
							</form>
							<script>document.frm_bulk_upload.submit();</script>';exit;	
						}
					}else
					{
						$post_title = addslashes($buffer[0]);
						$post_desc = addslashes($buffer[1]);
						$post_cat = array();
						$catids_arr = array();
						$post_cat = trim($buffer[2]); // comma seperated category name
						if($post_cat)
						{
							$catids_arr = explode(',',$post_cat);
						}
						$post_tags = trim($buffer[3]); // comma seperated tags
						
						if($post_tags)
						{
							$tag_arr = explode(',',$post_tags);	
						}
						$post_author = trim($buffer[4]); // post author
						if(!$post_author)
						{
							$post_author = 1;
						}
						if($post_title!='')
						{
							$my_post['post_title'] = $post_title;
							$my_post['post_content'] = $post_desc;
							$my_post['post_author'] = $post_author;
							$my_post['post_status'] = 'publish';
							$my_post['post_category'] = $catids_arr;
							$my_post['tags_input'] = $tag_arr;
							$my_post['post_type'] = CUSTOM_POST_TYPE1;
							$last_postid = wp_insert_post( $my_post );
							wp_set_object_terms($last_postid, $catids_arr, CUSTOM_CATEGORY_TYPE1); //custom category
							wp_set_object_terms($last_postid, $tag_arr, CUSTOM_TAG_TYPE1); //custom tags
							for($c=5;$c<count($customKeyarray);$c++)
							{
								update_post_meta($last_postid, $customKeyarray[$c], addslashes($buffer[$c]));
								$menu_order = 0;
								if($customKeyarray[$c]=='IMAGE' && $buffer[$c])
								{
									$image_folder_name = CUSTOM_POST_TYPE1.'/';
									$image_name = $buffer[$c];
									$menu_order = $i+1;
									$image_name_arr = explode('/',$image_name);
									$img_name = $image_name_arr[count($image_name_arr)-1];
									$img_name_arr = explode('.',$img_name);
									$post_img = array();
									$post_img['post_title'] = $img_name_arr[0];
									$post_img['post_status'] = 'attachment';
									$post_img['post_parent'] = $last_postid;
									$post_img['post_type'] = 'attachment';
									$post_img['post_mime_type'] = 'image/jpeg';
									$post_img['menu_order'] = $menu_order;
									$last_postimage_id = wp_insert_post( $post_img );
									update_post_meta($last_postimage_id, '_wp_attached_file', $image_folder_name.$image_name);					
									$post_attach_arr = array(
														"width"	=>	580,
														"height" =>	480,
														"hwstring_small"=> "height='150' width='150'",
														"file"	=> $image_folder_name.$image_name,
														);
									wp_update_attachment_metadata( $last_postimage_id, $post_attach_arr );
								}
							}
						}
					}				
				$rowcount++;
				}
				@unlink($csv_target_path);
				$url = get_option('siteurl').'/wp-admin/admin.php';
				echo '<form action="'.$url.'" method="get" id="frm_bulk_upload" name="frm_bulk_upload">
				<input type="hidden" value="bulk" name="page"><input type="hidden" value="success" name="msg"><input type="hidden" value="'.$rowcount.'" name="rowcount">
				</form>
				<script>document.frm_bulk_upload.submit();</script>
				';exit;
			}
			else
			{
				$url = get_option('siteurl').'/wp-admin/admin.php';
				echo '<form action="'.$url.'" method="get" id="frm_bulk_upload" name="frm_bulk_upload">
				<input type="hidden" value="bulk" name="page"><input type="hidden" value="tmpfile" name="emsg">
				</form>
				<script>document.frm_bulk_upload.submit();</script>
				';exit;
			}
		}else
		{
			$url = get_option('siteurl').'/wp-admin/admin.php';
			echo '<form action="'.$url.'" method="get" id="frm_bulk_upload" name="frm_bulk_upload">
			<input type="hidden" value="bulk" name="page"><input type="hidden" value="csvonly" name="emsg">
			</form>
			<script>document.frm_bulk_upload.submit();</script>
			';exit;
			//wp_redirect(get_option('siteurl').'/wp-admin/admin.php?page=bulk&emsg=csvonly');exit;	
		}
	}else
	{
		$url = get_option('siteurl').'/wp-admin/admin.php';
		echo '<form action="'.$url.'" method="get" id="frm_bulk_upload" name="frm_bulk_upload">
		<input type="hidden" value="bulk" name="page"><input type="hidden" value="invalid_file" name="emsg">
		</form>
		<script>document.frm_bulk_upload.submit();</script>
		';exit;
		//wp_redirect(get_option('siteurl').'/wp-admin/admin.php?page=bulk&emsg=invalid_file');exit;
	}
}
?>

<form action="<?php echo get_option('siteurl')?>/wp-admin/admin.php?page=bulk" method="post" name="bukl_upload_frm" enctype="multipart/form-data">
  <style>
h2 { color:#464646;font-family:Georgia,"Times New Roman","Bitstream Charter",Times,serif;
font-size:24px;
font-size-adjust:none;
font-stretch:normal;
font-style:italic;
font-variant:normal;
font-weight:normal;
line-height:35px;
margin:0;
padding:14px 15px 3px 0;
text-shadow:0 1px 0 #FFFFFF;  }
</style>
  <h2><?php _e('Bulk Upload');?></h2>
  <p><?php _e('Have a '.get_option('blogname').' site somewhere else and you wish to import that data here? Simply  download <a href="'. get_template_directory_uri().'/sample_csv.csv">sample CSV file</a> and import your data accordingly.</p><p>It is advisable to create the same category in this Blog first and then use "Post Category" title accurate in CSV file.</p>');?>
 <?php if($_REQUEST['emsg']=='csvonly'){?>
 <div class="updated fade below-h2" id="message" style="background-color: rgb(255, 251, 204);" >
 <p><?php _e('Please upload CSV file only.');?></p>
 </div>
 <br />
 <?php }?>
 <?php if($_REQUEST['emsg']=='invalid_file'){?>
 <div class="updated fade below-h2" id="message" style="background-color: rgb(255, 251, 204);" >
 <p><?php _e('Please select valid CSV file only for listing bulk upload.');?></p>
 </div>
 <br />
 <?php }?>
  <?php if($_REQUEST['emsg']=='tmpfile'){?>
 <div class="updated fade below-h2" id="message" style="background-color: rgb(255, 251, 204);" >
 <p><?php echo $target_path;  _e('Cannot move the bulk upload file to Temporary system folder <b>"'.$tmppath.'"</b>. Please check folder permission should be 0777.');?></p>
 </div>
 <br />
 <?php }?>
  <?php if($_REQUEST['emsg']=='wrong'){?>
 <div class="updated fade below-h2" id="message" style="background-color: rgb(255, 251, 204);" >
 <p><?php echo $target_path;  _e('File you are uploading is not valid. First colum should be "Post Title".');?></p>
 </div>
 <br />
 <?php }?>
<?php
if($_REQUEST['msg']=='success'){
$rowcount = $_REQUEST['rowcount'];
$success_msg = '';
$success_msg .=  "<div id=message class=updated><p>".__('CSV uploaded successfully.')."</p>";
$rowcount = $rowcount-2;
$success_msg .= "<p><b>".__('Total of '.$rowcount.' records inserted.')."</b></p>";
echo $success_msg .= __("<p>Please create '".CUSTOM_POST_TYPE1."' folder in <b>'/".$upload_folder_path."'</b> and trasfer all images.</b></p></div><br>");
}
?>
  <table style=" width:40%" cellpadding="3" cellspacing="3" class="widefat post fixed" >
    <tr>
      <td width="24%"><?php _e('Select CSV file to upload');?></td>
      <td width="70%">:
        <input type="file" name="bulk_upload_csv" id="bulk_upload_csv"></td>
    </tr>
    <tr>
      <td>&nbsp;</td>
    <td><input type="submit" name="submit" value="<?php _e('Submit');?>" onClick="return check_frm();" class="button" >    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>    
    </tr>
    <tr><td></td>
      <td><?php _e('You can download');?> <a href="<?php echo get_template_directory_uri()?>/sample_csv.csv"><?php _e('sample CSV file');?></a></td>
          
    </tr>
  </table>
</form>
<script>
function check_frm()
{
	if(document.getElementById('bulk_upload_csv').value == '')
	{
		alert("<?php _e('Please select csv file to upload');?>");
		return false;
	}
	return true;
}
</script>