<?php
	set_time_limit(0);
	!defined('DIRCMS_MANAGE') && exit('Access Denied!');
	if(!$module->roleid_check('upgrade',$_roleid))showmsg_nourl($lang['RETURN_NOPRI']);

	$action=empty($action)?'setting':trim($action);

	include_once DIRCMS_ROOT.'upgrade/data/config.inc.php';

	require substr(dirname(__FILE__),0,-6).'/include/upgrade.class.php';
	$upgrade=new upgrade();

	include_once DIRCMS_ROOT.'/include/cnspell.class.php';
	$cnspell=new cnspell();

	switch($action)
	{
		case 'setting':
			if(isset($do_submit))
			{	
				if(!isset($m))
				{
					$patchfile=strtolower(DIRCMS_DATA.'patch/'.DIRCMS_VERSION.DIRCMS_RELEASE.'.zip');
					
					$checkrs=$upgrade->check(DIRCMS_VERSION,DIRCMS_RELEASE);
					if($checkrs===true)
					{
						/*
							删除历史补丁文件 2012-06-08 17:19
						*/
						rmdirs(DIRCMS_ROOT.'data/tmp/'.md5($_userid).'/');
						$patchpath=$upgrade->getpatch($patchfile);
						if(!$patchpath)
						{
							exit('<script language="javascript">alert("在线更新失败, 请手动更新!");history.back();</script>');
						}
						$patchs=$upgrade->listfile($patchpath);
						$err=filesize($patchs[0])?false:true;
						cache_write('user'.$_userid.'-upgrade.cache.php',$patchs,DIRCMS_ROOT.'data/tmp/');
						include admin_tlp('lis','upgrade');
					}
					else if($checkrs==-3)
					{
						exit('由于当前程序升级幅度较大, 请<a href="'.$patchfile.'" target="_blank">手动下载更新包</a>进行更新!');
					}
					else if($checkrs==-2)
					{
						exit('<script language="javascript">alert("当前程序已是最新版本, 无需升级!");history.back();</script>');
					}
					else if($checkrs==-1)
					{
						exit('<script language="javascript">alert("无法链接升级服务器, 请稍后再试!");history.back();</script>');
					}
					else
					{
						exit('<script language="javascript">alert("在线更新失败, 请手动更新!");history.back();</script>');
					}
				}
				else
				{
					$patchs=cache_read('user'.$_userid.'-upgrade.cache.php',DIRCMS_ROOT.'data/tmp/');
					if($patchs)
					{
						$patch=array_shift($patchs);
						cache_write('user'.$_userid.'-upgrade.cache.php',$patchs,DIRCMS_ROOT.'data/tmp/');
						if(is_file($patch))
						{
							if(basename($patch)=='upgrade.sql')
							{
								showmsg('跳过文件 '.$destfile.' ...<br />还有 <font color="#ff0000">'.max(1,intval($count)-1).'</font> 个文件待更新...','?mod=upgrade&file=upgrade&action=setting&do_submit=1&m=1&count='.max(1,intval($count)-1));
							}
							else
							{
								$destfile=substr($patch,strlen(DIRCMS_ROOT.'data/tmp/'.md5($_userid).'/'));
								if(is_file(DIRCMS_ROOT.$destfile) && !is_writeable(DIRCMS_ROOT.$destfile))
								{
									showmsg_nourl('文件 '.$destfile.' 不可写, 请设置为0777后重新点击在线更新按钮!');
								}
								else
								{
									makedir(dirname($destfile));
									@copy($patch,DIRCMS_ROOT.$destfile);
									showmsg('文件 '.$destfile.' 已更新<br />还有 <font color="#ff0000">'.max(1,intval($count)-1).'</font> 个文件待更新...','?mod=upgrade&file=upgrade&action=setting&do_submit=1&m=1&count='.max(1,intval($count)-1));
								}
							}
						}
					}
					else
					{
						/*
							更改数据库结构
						*/
						if(file_exists(DIRCMS_ROOT.'data/tmp/'.md5($_userid).'/upgrade.sql'))
						{
							$sqls=file_get_contents(DIRCMS_ROOT.'data/tmp/'.md5($_userid).'/upgrade.sql');
							if($sqls)
							{
								$sqls=explode(";",trim($sqls));
								if($sqls)foreach($sqls as $sql)
								{
									$sql=trim($sql);
									if(!empty($sql) && $sql)
									{
										$db->query(str_replace('dircms_',DB_PRE,$sql),true);
									}
								}
							}
						}

						if(is_file(DIRCMS_ROOT.'data/tmp/'.md5($_userid).'/upgrade.php'))
						{
							@copy(DIRCMS_ROOT.'data/tmp/'.md5($_userid).'/upgrade.php',DIRCMS_ROOT.'upgrade.php');

							showmsg_nourl('文件升级完毕, <a href="'.SITE_URL.'upgrade.php"><u>点此升级数据库</u></a>!');
						}
						else
						{
							/*
								删除临时数据
							*/
							if(!file_exists(DIRCMS_ROOT.'data/tmp/'.md5($_userid).'/msg.txt'))
							{
								$endmsg='当前程序已升级到最新版本!';
							}
							else
							{
								$endmsg=file_get_contents(DIRCMS_ROOT.'data/tmp/'.md5($_userid).'/msg.txt');
							}
							$endmsg=trim($endmsg)?trim($endmsg):'当前程序已升级到最新版本!';
							$endmsg=strip_tags($endmsg);

							rmdirs(DIRCMS_ROOT.'data/tmp/'.md5($_userid).'/');
							cache_delete('user'.$_userid.'-upgrade.cache.php',DIRCMS_ROOT.'data/tmp/');

							showmsg_nourl($endmsg);
						}
					}
				}
			}
			else
			{
				include admin_tlp('setting','upgrade');
			}
			break;
		case 'initdb':
			if(isset($do_submit))
			{	
				if($upgrade->initdb($info))
				{
					header("location:".ADMIN_FILE."?mod=upgrade&file=upgrade&action=init&version=".$version);
					exit();
				}
				else
				{
					showmsg($upgrade->msg);
				}
			}
			include admin_tlp('initdb','upgrade');
			break;
		case 'init':
			$initdb=new mysql();
			$initdb->connect(VER_DB_HOST,VER_DB_USER,VER_DB_PSW,VER_DB_NAME,DB_PCONNECT,DB_CHARSET);

			if(isset($do_submit))
			{	
				if($data=='article')
				{
					/*
						获取旧附加表
					*/
					if(!isset($m))
					{
						if(!$catid || !$initcatid)
						{
							showmsg('请选择需要转换的栏目ID!');
						}

						$initcatinfo=$initdb->fetch_one("SELECT modelid FROM ".VER_DB_PRE."category WHERE id=".$initcatid);

						$pretable=VER_DB_PRE.'article';
						if($version=='dircms2011sp1' || $version=='dircms2011sp2')
						{
							$initmodelinfo=$initdb->fetch_one("SELECT name FROM ".VER_DB_PRE."model WHERE id=".$initcatinfo['modelid']);
							$pretable=VER_DB_PRE.$initmodelinfo['name'];
						}
						else
						{
							$initmodelinfo=$initdb->fetch_one("SELECT `table` FROM ".VER_DB_PRE."model WHERE id=".$initcatinfo['modelid']);
							$pretable=VER_DB_PRE.$initmodelinfo['table'];
						}
						$r=$initdb->fetch_one("SELECT count(*) as rows FROM ".VER_DB_PRE."content WHERE catid=".$initcatid);
						showmsg('准备工作结束，开始转换指定栏目数据!',ADMIN_FILE.'?mod=upgrade&file=upgrade&action=init&total='.$r['rows'].'&catid='.$catid.'&initcatid='.$initcatid.'&data=article&data='.$data.'&version='.$version.'&do_submit=1&m=1&pretable='.$pretable.'&start=0');
					}
					else
					{
						$coninfo=$initdb->fetch_all("SELECT * FROM ".VER_DB_PRE."content a LEFT JOIN ".$pretable." b ON a.id=b.contentid WHERE a.catid=".$initcatid." LIMIT ".$start.",20");
						
						if($coninfo)
						{
							/*
								获取新附加表
							*/
							$catinfo=getcatinfo($catid);
							$modelinfo=cache_read('model'.$catinfo['modelid'].'.cache.php',DIRCMS_ROOT.'data/c/');
							
							foreach($coninfo as $con)
							{
								$initcontentid=$con['id'];

								/*
									转换内容评论
								*/
								$cominfo=$initdb->fetch_all("SELECT * FROM ".VER_DB_PRE."comment WHERE contentid=".$initcontentid);
							
								$newdb=new mysql();
								$newdb->connect(DB_HOST,DB_USER,DB_PSW,DB_NAME,DB_PCONNECT,DB_CHARSET);
				
								/*
									转换内容数据
								*/
								unset($con['id']);
								$con['catid']=$catid;
								$con['userid']=$_userid;
								$con['username']=$_username;
								$con['modelid']=$catinfo['modelid'];
								$con['siteid']=SITEID;
								$con['template']=$catinfo['setting']['temparticle'];
								$contentid=$newdb->insert(DB_PRE.'content',$con);
								$con['contentid']=$contentid;
								
								$updateinfo=array();
								if($catinfo['setting']['ishtml']==1 || $catinfo['setting']['ishtml']==2)
								{
									$catinfo['setting']['urlrule']=strpos($catinfo['setting']['urlrule'],'.')?trim($catinfo['setting']['urlrule']):'{sitedir}html/{Y}{M}/content_{cid}'.HTMLEXT;
									$updateinfo['url']=str_replace('{sitedir}',SITEDIR?SITEDIR.'/':'',$catinfo['setting']['urlrule']);
									$updateinfo['url']=str_replace('{catdir}',$catinfo['catdir'],$updateinfo['url']);
									$updateinfo['url']=str_replace('{Y}',date('Y',$info['inputtime']),$updateinfo['url']);
									$updateinfo['url']=str_replace('{M}',date('m',$info['inputtime']),$updateinfo['url']);
									$updateinfo['url']=str_replace('{D}',date('d',$info['inputtime']),$updateinfo['url']);
									$updateinfo['url']=str_replace('{timestamp}',$info['inputtime'],$updateinfo['url']);
									$updateinfo['url']=str_replace('{cid}',intval($contentid),$updateinfo['url']);
									$updateinfo['url']=str_replace('{pinyin}',$cnspell->getcnSpell($coninfo['title'],'GBK',0).intval($contentid),$updateinfo['url']);
									$updateinfo['url']=str_replace('{py}',$cnspell->getcnSpell($coninfo['title'],'GBK',1).intval($contentid),$updateinfo['url']);
									$updateinfo['url']=str_replace('\\','/',$updateinfo['url']);
									$updateinfo['url']=str_replace('//','/',$updateinfo['url']);
								}
								else
								{
									$updateinfo['url']='show.php?id='.$contentid;
								}
								$newdb->update(DB_PRE.'content',$updateinfo,'id='.$contentid);
								$newdb->insert(DB_PRE.$modelinfo['table'],$con);
								
								foreach($cominfo as $com)
								{
									unset($com['id']);
									$com['contentid']=$contentid;
									$com['siteid']=SITEID;
									$newdb->insert(DB_PRE.'comment',$com);
								}

								$initdb=new mysql();
								$initdb->connect(VER_DB_HOST,VER_DB_USER,VER_DB_PSW,VER_DB_NAME,DB_PCONNECT,DB_CHARSET);
							}
							showmsg("数据已转换".($start+20)."条! 继续...",ADMIN_FILE.'?mod=upgrade&catid='.$catid.'&initcatid='.$initcatid.'&file=upgrade&data='.$data.'&action=init&total='.$r['rows'].'&data=article&version='.$version.'&do_submit=1&m=1&pretable='.$pretable.'&start='.($start+20));
						}
						else
						{
							showmsg("栏目【".catname($catid)."】数据转换成功!",ADMIN_FILE.'?mod=upgrade&file=upgrade&action=init&data=article&data='.$data.'&version='.$version);
						}
					}
				}
				elseif($data=='member')
				{
					$meminfo=array();
					if($version=='dircms2011sp1' || $version=='dircms2011sp2')
					{
						$nomalinfo=$initdb->fetch_all("SELECT * FROM ".VER_DB_PRE."member a LEFT JOIN ".VER_DB_PRE."nomalmember b ON a.id=b.userid WHERE a.modelid=1");
						$cominfo=$initdb->fetch_all("SELECT * FROM ".VER_DB_PRE."member a LEFT JOIN ".VER_DB_PRE."corporatemember b ON a.id=b.userid WHERE a.modelid=2");
					}
					else
					{
						$nomalinfo=$initdb->fetch_all("SELECT * FROM ".VER_DB_PRE."member a LEFT JOIN ".VER_DB_PRE."regular b ON a.id=b.userid WHERE a.modelid=1");
						$cominfo=$initdb->fetch_all("SELECT * FROM ".VER_DB_PRE."member a LEFT JOIN ".VER_DB_PRE."company b ON a.id=b.userid WHERE a.modelid=2");
					}
					$meminfo=array_merge($nomalinfo,$cominfo);

					$newdb=new mysql();
					$newdb->connect(DB_HOST,DB_USER,DB_PSW,DB_NAME,DB_PCONNECT,DB_CHARSET);
					
					$newmem=array();
					$newmemname=$newdb->fetch_all("SELECT username FROM ".DB_PRE."member WHERE 1");
					foreach($newmemname as $k => $r)
					{
						$newmem[$k]=$r['username'];
					}

					foreach($meminfo as $mem)
					{
						/*
							导入会员信息
						*/
						if(!in_array($mem['username'],$newmem))
						{
							$initmemid=$mem['id'];
							unset($mem['id']);
							unset($mem['userid']);
							$userid=$newdb->insert(DB_PRE.'member',$mem);
							$mem['userid']=$userid;
							$mem['level']=1;

							if($version=='dircms2011sp1' || $version=='dircms2011sp2')
							{
								if($mem['modelid']==1)
								{
									$newdb->insert(DB_PRE.'nomalmember',$mem);
								}
								else if($mem['modelid']==2)
								{
									$newdb->insert(DB_PRE.'corporatemember',$mem);
								}
								else
								{
									$newdb->mysql_delete(DB_PRE.'member',$userid);
								}
							}
							else
							{
								if($mem['modelid']==1)
								{
									$newdb->insert(DB_PRE.'regular',$mem);
								}
								else if($mem['modelid']==2)
								{
									$newdb->insert(DB_PRE.'company',$mem);
								}
								else
								{
									$newdb->mysql_delete(DB_PRE.'member',$userid);
								}
							}

							/*
								导入空间信息
							*/
							
							if($version=='dircms2011sp3')
							{
								$initdb=new mysql();
								$initdb->connect(VER_DB_HOST,VER_DB_USER,VER_DB_PSW,VER_DB_NAME,DB_PCONNECT,DB_CHARSET);

								$spaceinfo=$initdb->fetch_one("SELECT * FROM ".VER_DB_PRE."space WHERE userid=$initmemid");
								if($spaceinfo)
								{
									unset($spaceinfo['id']);
									$spaceinfo['template']='default';
									$spaceinfo['userid']=$userid;

									$newdb=new mysql();
									$newdb->connect(DB_HOST,DB_USER,DB_PSW,DB_NAME,DB_PCONNECT,DB_CHARSET);
									$newdb->insert(DB_PRE.'space',$spaceinfo);
								}
							}

							/*
								导入黄页信息
							*/
							if($version=='dircms2011sp3')
							{
								$initdb=new mysql();
								$initdb->connect(VER_DB_HOST,VER_DB_USER,VER_DB_PSW,VER_DB_NAME,DB_PCONNECT,DB_CHARSET);

								$ypinfo=$initdb->fetch_one("SELECT * FROM ".VER_DB_PRE."yp WHERE memberid=$initmemid");
								if($ypinfo)
								{
									$yid=$ypinfo['id'];
									unset($ypinfo['id']);
									$ypinfo['template']='default';
									$ypinfo['memberid']=$userid;
									$ypinfo['siteid']=SITEID;
									$ypinfo['dir']='temp';

									/*
										获取店铺动态
									*/
									$newsinfo=$initdb->fetch_all("SELECT * FROM ".VER_DB_PRE."yp_news WHERE ypid=".$yid);

									/*
										获取店铺产品
									*/
									$productinfo=$initdb->fetch_all("SELECT * FROM ".VER_DB_PRE."yp_product WHERE ypid=".$yid);

									$newdb=new mysql();
									$newdb->connect(DB_HOST,DB_USER,DB_PSW,DB_NAME,DB_PCONNECT,DB_CHARSET);
									$ypinfo['id']=$ypid=$newdb->insert(DB_PRE.'yp',$ypinfo,true);
									
									$ypup=array();

									$fields=$newdb->get_fields(DB_PRE.'yp');
									foreach($fields as $val)
									{
										if(!array_key_exists($val,$ypinfo))
										{
											$ypup[$val]=$mem[$val];
										}
									}
									
									$ypup['domain']=SITE_URL.'yp/web/';
									$ypup['url']='yp/web/index.php?u='.$ypid.'&siteid='.SITEID;
									$ypup['dir']=$ypid;
									$ypup['menu']='';
									$ypup['meta_title']=$ypinfo['name'];

									$newdb->update(DB_PRE.'yp',$ypup,'id='.$ypid);

									/*
										转换店铺动态
									*/
									foreach($newsinfo as $news)
									{
										$news['ypid']=$ypid;
										$news['ypdomain']=$ypup['domain'];
										$news['ypurl']=$ypup['url'];
										$news['siteid']=1;
										$newdb->insert(DB_PRE.'yp_news',$news);
									}

									/*
										转换店铺产品
									*/
									foreach($productinfo as $product)
									{
										$product['ypid']=$ypid;
										$product['ypdomain']=$ypup['domain'];
										$product['ypurl']=$ypup['url'];
										$product['siteid']=1;
										$newdb->insert(DB_PRE.'yp_product',$product);
									}
								}
							}
						}
					}
					showmsg("指定会员信息数据转换成功!",ADMIN_FILE.'?mod=upgrade&file=upgrade&action=init&data=member&version='.$version);
				}
				else
				{
					showmsg("请选择需转换数据类型!");
				}
			}

			$data=isset($data)?$data:'article';

			if($data=='article')
			{
				if(isset($version))
				{
					if($version=='dircms2011sp1' || $version=='dircms2011sp2')
					{
						if(in_array('categoryname',$initdb->get_fields(VER_DB_PRE."category")))
						{
							$initcatinfo=$initdb->fetch_all("SELECT id,parentid,categoryname as catname FROM ".VER_DB_PRE."category WHERE ispage=0 ORDER BY orderby ASC");
						}
					}
					else
					{
						if(in_array('catname',$initdb->get_fields(VER_DB_PRE."category")))
						{
							$initcatinfo=$initdb->fetch_all("SELECT id,parentid,catname FROM ".VER_DB_PRE."category WHERE type=1 ORDER BY orderby ASC");
						}
					}
				}
			}

			$catinfo=cache_read('cat.cache.php',DIRCMS_ROOT.'data/cache_category/');
			include admin_tlp('init','upgrade');
			break;
	}
?>