1 
  2 /**
  3  * @name	CeL function for Windows
  4  * @fileoverview
  5  * 本檔案包含了 Windows 系統管理專用的 functions。
  6  * @since	
  7  */
  8 
  9 
 10 
 11 if (typeof CeL === 'function')
 12 CeL.setup_module('application.OS.Windows',
 13 {
 14 require : 'data.code.compatibility.is_web|data.code.compatibility.is_HTA',
 15 code : function(library_namespace, load_arguments) {
 16 
 17 //	requiring
 18 var is_web,is_HTA;
 19 eval(library_namespace.use_function(this));
 20 
 21 
 22 
 23 /**
 24  * null module constructor
 25  * @class	web 的 functions
 26  */
 27 CeL.application.OS.Windows
 28 = function() {
 29 	//	null module constructor
 30 };
 31 
 32 /**
 33  * for JSDT: 有 prototype 才會將之當作 Class
 34  */
 35 CeL.application.OS.Windows
 36 .prototype = {
 37 };
 38 
 39 
 40 
 41 
 42 //initialization_WScript_Objects();
 43 //initialization_WScript_Objects[generateCode.dLK]='is_web,is_HTA,ScriptHost,dirSp'.split(',');
 44 //initialization_WScript_Objects[generateCode.dLK].push('*var args,WshShell,WinShell,WinShell,fso;initialization_WScript_Objects();');
 45 function initialization_WScript_Objects(onlyHTML) {
 46 	if (typeof library_namespace.WScript === 'object'
 47 			// && typeof WScript.constructor=='undefined'
 48 			) {
 49 		var i = (ScriptHost = WScript.FullName).lastIndexOf(dirSp);
 50 		if (i != -1)
 51 			ScriptHost = ScriptHost.slice(i + 1);
 52 		WshShell = WScript.CreateObject("WScript.Shell"), WinShell = WScript
 53 				.CreateObject("Shell.Application"), fso = WScript
 54 				.CreateObject("Scripting.FileSystemObject");
 55 		args = [];
 56 		for ( var i = 0, a=WScript.Arguments,l = a.length; i < l; i++)
 57 			args.push(a(i));
 58 	} else {
 59 		if ( // 用 IE 跑不能用 ActiveXObject
 60 		!(typeof onlyHTML === 'undefined' ? is_web() && !is_HTA() : onlyHTML)// !onlyHTML//
 61 				&& typeof ActiveXObject != 'undefined')
 62 			try { // 在.hta中typeof WScript=='undefined'
 63 				// http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/reference/objects/shell/application.asp
 64 				// http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_intro.asp
 65 				WshShell = new ActiveXObject("WScript.Shell"),
 66 						WinShell = new ActiveXObject("Shell.Application"),
 67 						fso = new ActiveXObject("Scripting.FileSystemObject");
 68 				if (is_HTA.HTA)
 69 					args = is_HTA.HTA.commandLine.split(/\s+/), args.shift();
 70 			} catch (e) {
 71 			}
 72 		//	判斷假如尚未load則排入以確定是否為HTA
 73 		else if (is_web(1) && !is_HTA()
 74 				&& !document.getElementsByTagName('body').length)
 75 			setTimeout('initialization_WScript_Objects();', 9);
 76 	}
 77 
 78 	//	if (typeof newXMLHttp == 'function') XMLHttp = newXMLHttp();
 79 
 80 /* @cc_on
 81 @if(@_jscript_version >= 5)
 82 // JScript gives us Conditional compilation, we can cope with old IE versions.
 83 // and security blocked creation of the objects.
 84  ;//else..
 85 @end@*/
 86 
 87 };
 88 
 89 
 90 
 91 
 92 
 93 
 94 /*	2007/11/17 23:3:53
 95 	使用 ADSI (Active Directory Service Interface) 存取資料
 96 	http://support.microsoft.com/kb/234001
 97 	http://www.dbworld.com.tw/member/article/010328b.htm
 98 	http://support.microsoft.com/kb/216393
 99 */
100 function addUser(name,pw,group,computer){
101  //	http://msdn.microsoft.com/library/en-us/script56/html/wsmthenumprinterconnections.asp
102  ;
103  //	連上伺服器
104  var oIADs,o;
105  //	利用Create指令,指定產生一個新的使用者類別,以及使用者帳號的名稱。使用SetInfo的指令將目錄服務中的資料更新。
106  try{oIADs=new Enumerator(GetObject(computer='WinNT://'+(computer||(new ActiveXObject('WScript.Network')).ComputerName)));}catch(e){}//WScript.CreateObject('WScript.Network')
107  if(oIADs){//try{
108   if(name){
109    try{o=oIADs.Create('user',name);}catch(e){o=new Enumerator(GetObject(computer+'/'+name));}
110    with(o)SetPassword(pw),/*FullName=name,Description=name,*/SetInfo();
111    //	Administrators
112    if(group)(new Enumerator(GetObject(computer+'/'+group))).Add(o.ADsPath);	//	o.ADsPath: computer+'/'+name
113    return o;	//	得到用戶
114   }
115 
116   //oIADs.Filter=['user'];//new VBArray('user');	//	no use, 改用.AccountDisabled
117   o={};
118   //	http://msdn2.microsoft.com/en-us/library/aa746343.aspx
119   //	對所有的oIADs,通常有Name,Description
120   for(var i,j,a,b,p='Name,AccountDisabled,Description,FullName,HomeDirectory,IsAccountLocked,LastLogin,LoginHours,LoginScript,MaxStorage,PasswordExpirationDate,PasswordMinimumLength,PasswordRequired,Profile'.split(',');!oIADs.atEnd();oIADs.moveNext())if(typeof oIADs.item().AccountDisabled=='boolean'){
121    for(i=oIADs.item(),j=0,a={};j<p.length;j++)if(b=p[j])try{
122     a[b]=i[b];
123     if(typeof a[b]=='date')a[b]=new Date(a[b]);
124    }catch(e){
125     //alert('addUser():\n['+i.name+'] does not has:\n'+b);
126     //	刪掉沒有的屬性。但僅少數不具有,所以不能全刪。XP中沒有(?):,AccountExpirationDate,BadLoginAddress,BadLoginCount,Department,Division,EmailAddress,EmployeeID,FaxNumber,FirstName,GraceLoginsAllowed,GraceLoginsRemaining,HomePage,Languages,LastFailedLogin,LastLogoff,LastName,LoginWorkstations,Manager,MaxLogins,NamePrefix,NameSuffix,OfficeLocations,OtherName,PasswordLastChanged,Picture,PostalAddresses,PostalCodes,RequireUniquePassword,SeeAlso,TelephoneHome,TelephoneMobile,TelephoneNumber,TelephonePager,Title
127     //p[j]=0;//delete p[j];
128    }
129    o[i.name]=a;
130   }
131 
132   return o;
133  }//catch(e){}
134 };
135 //a=addUser();for(i in a){d=[];for(j in a[i])d.push(j+': '+a[i][j]);alert(d.join('\n'));}
136 
137 
138 
139 
140 
141 //	特殊功能	-------------------------------------------------------
142 
143 /*	取得基本環境值
144 //	test
145 if(0){
146  var o=WinEnvironment;
147  if(typeof o=='object'){var i,t='';for(i in o)t+=i+'='+o[i]+'\n';alert(t);}
148  o=SpecialFolder;
149  if(typeof o=='object'){var i,t='';for(i in o)t+=i+'='+o[i]+'\n';alert(t);}
150  o=Network;
151  if(typeof o=='object'){var i,t='';for(i in o)t+=i+'='+o[i]+'\n';alert(t);}
152  o=NetDrive;
153  if(typeof o=='object'){var i,t='';for(i in o)t+=i+'='+o[i]+'\n';alert(t);}
154  o=NetPrinter;
155  if(typeof o=='object'){var i,t='';for(i in o)t+=i+'='+o[i]+'\n';alert(t);}
156 }
157 */
158 //setTool();
159 var WinEnvironment,SpecialFolder,Network,NetDrive,NetPrinter;
160 getEnvironment[generateCode.dLK]='WinEnvironment,SpecialFolder,Network,NetDrive,NetPrinter,*getEnvironment();';
161 function getEnvironment(){
162  if(typeof WshShell!='object'||typeof SpecialFolder=='object')return;
163 
164  WinEnvironment={},Network={},NetDrive={},NetPrinter={};
165  var i,j,k,o=new Enumerator(WshShell.Environment("Process"));/*	Win9x、NT(Administratorもしくはほかのユーザー)の区別なく、すべての場合でエラーが発生しないようにするには、strTypeに"PROCESS"を指定するとよいでしょう。
166 	機器上所有已定義的環境變數Windows environment variables	http://msdn2.microsoft.com/en-us/library/fd7hxfdd(VS.85).aspx	http://www.roy.hi-ho.ne.jp/mutaguchi/wsh/refer/lesson11.htm	http://nacelle.info/wsh/03001.php	http://www.cs.odu.edu/~wild/windowsNT/Spring00/wsh.htm
167 	usual:	ALLUSERSPROFILE,APPDATA,BLASTER,CLASSPATH,CLIENTNAME,CommonProgramFiles,COMPUTERNAME,ComSpec,DEVMGR_SHOW_NONPRESENT_DEVICES,HOMEDRIVE,HOMEPATH,INCLUDE,LIB,LOGONSERVER,NUMBER_OF_PROCESSORS,OS,Os2LibPath,Path,PATHEXT,PROCESSOR_ARCHITECTURE,PROCESSOR_IDENTIFIER,PROCESSOR_LEVEL,PROCESSOR_REVISION,ProgramFiles,PROMPT,QTJAVA,SESSIONNAME,SystemDrive,SystemRoot,TEMP,TMP,USERDOMAIN,USERNAME,USERPROFILE,VS71COMNTOOLS,VSCOMNTOOLS,windir,winbootdir
168 
169 	WshShell.ExpandEnvironmentStrings("%windir%\\notepad.exe");	WshShell.Environment("Process")("TMP")
170 	MyShortcut.IconLocation = WSHShell.ExpandEnvironmentStrings("%windir%\\notepad.exe, 0");
171 
172 	System	HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
173 	User	HKEY_CURRENT_USER\Environment
174 	Volatile	HKEY_CURRENT_USER\Volatile Environment	ログオフとともにクリアされる
175 	Process, or 98:'WshShell.Environment'==WshShell.Environment("Process"),NT:==WshShell.Environment("System")ただし、Administratorアカウントを持つユーザー以外は、strTypeに"SYSTEM"を指定、もしくは省略するとエラーになります。
176  */
177  while(!o.atEnd()){
178   i=o.item();
179   j=i.indexOf('=');//if((j=i.indexOf('='))!=-1)
180   WinEnvironment[i.slice(0,j)]=i.substr(j+1);	//	value以';'作為分隔,若有必要可使用.split(';')
181   o.moveNext();
182  }
183 
184  //	http://www.microsoft.com/japan/msdn/library/ja/script56/html/wsprospecialfolders.asp	HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders
185  //	VB中用For Each .. In可列舉出全部,但JS則不行-_-所以得自己列舉
186  // fso.GetSpecialFolder( 0: Windows 文件夾 1: System 文件夾 2: Temp 文件夾 )
187  setObjValue('SpecialFolder','AllUsersDesktop,AllUsersStartMenu,AllUsersPrograms,AllUsersStartup,AppData,Desktop,Favorites,Fonts,MyDocuments,NetHood,PrintHood,Programs,Recent,SendTo,StartMenu,Startup,Templates');
188  o=WshShell.SpecialFolders;
189  for(i in SpecialFolder)SpecialFolder[i]=o(i);
190  for(i=0;i<o.Count();i++)SpecialFolder[i]=o.item(i);
191 
192  o=new ActiveXObject("WScript.Network");//WScript.CreateObject("WScript.Network");
193  //	http://msdn.microsoft.com/library/en-us/script56/html/wsmthenumprinterconnections.asp
194  Network.ComputerName=o.ComputerName,Network.UserDomain=o.UserDomain,Network.UserName=o.UserName;
195  //	Network Drive & Printer mappings
196  j=o.EnumNetworkDrives(),k=1;
197  for(i=0;i<j.Count();i+=2)NetDrive[j.Item(i)?j.Item(i):'Volatile'+k++]=NetDrive[i/2]=j.Item(i+1);
198  j=o.EnumPrinterConnections(),k=1;
199  for(i=0;i<j.Count();i+=2)NetPrinter[j.Item(i)]=NetPrinter[i/2]=j.Item(i+1);
200 };	//	function getEnvironment()
201 
202 
203 
204 
205 CeL.application.OS.Windows
206 .
207 /**
208  * 取得 VB 的 Nothing
209  * @returns	VB 的 Nothing
210  * @memberOf	CeL.application.OS.Windows
211  */
212 VBNothing = function () {
213 	try {
214 		return (new ActiveXObject("ADODB.RecordSet")).ActiveConnection;
215 	} catch (e) {
216 	}
217 };
218 
219 CeL.application.OS.Windows
220 .
221 /**
222  * 轉換 VB 的 Safe Array 成為 JS Array.
223  * @param vba	VB 的 array
224  * @returns
225  * @memberOf	CeL.application.OS.Windows
226  */
227 VBA_to_JSA = function (vba) {
228 	try {
229 		return (new VBArray(vba)).toArray();
230 	} catch (e) {
231 	}
232 	return [];
233 };
234 
235 CeL.application.OS.Windows
236 .
237 /**
238  * 轉換JS Array成為VB的Safe Array.
239  * Safe Array To JS Array: plaese use new VBArray().
240  * JScriptの配列は実際にはCSV文字列だったりする。VBScriptのvartypeに食わせると8(VT_STRING)が返ってくることからもわかる。
241  * @param array
242  * @returns
243  * @see
244  * http://www.microsoft.com/japan/msdn/japan/msdn/library/ja/script56/html/js56jsobjvbarray.asp
245  * @memberOf	CeL.application.OS.Windows
246  */
247 JSA_to_VBA = function (array) {
248 	if (typeof array != 'object')
249 		array = [ array ];
250 	var i = 0, dic = new ActiveXObject("Scripting.Dictionary");
251 	for (; i < array.length; i++)
252 		dic.add(i, array[i]);
253 	return dic.items();
254 };
255 
256 
257 
258 
259 /*	http://www.eggheadcafe.com/forumarchives/scriptingVisualBasicscript/Mar2006/post26047035.asp
260 	Application.DoEvents();
261 */
262 function DoEvents() {
263 	// Triggers screen updates in an HTA...
264 	try {
265 		if (!DoEvents.w)
266 			DoEvents.w = typeof WshShell == 'object' ? WshShell
267 					: new ActiveXObject("WScript.Shell");
268 		DoEvents.w.Run("%COMSPEC% /c exit", 0, true);
269 	} catch (e) {
270 	}
271 }
272 ;
273 var DoNothing = DoEvents;
274 
275 function Sleep(_sec) {
276 	if (isNaN(_sec) || _sec < 0)
277 		_sec = 0;
278 	if (typeof WScript == 'object')
279 		try {
280 			// Win98的JScript沒有WScript.Sleep
281 			WScript.Sleep(_sec * 1e3);
282 		} catch (e) {
283 		}
284 		else
285 			// if(typeof window!='object')
286 			try {
287 				if (!Sleep.w)
288 					Sleep.w = typeof WshShell == 'object' ? WshShell
289 							: new ActiveXObject("WScript.Shell");
290 				Sleep.w.Run(_sec ? "%COMSPEC% /c ping -n " + (1 + _sec)
291 						+ " 127.0.0.1>nul 2>nul" : "%COMSPEC% /c exit", 0,
292 						true);
293 			} catch (e) {
294 			}
295 };
296 
297 
298 
299 
300 
301 /*
302 	送key到application	http://msdn.microsoft.com/library/en-us/script56/html/wsmthsendkeys.asp
303 	SendKeys('a')	送a
304 	SendKeys("a{1}4{2}5");	送a,等1/10s,送4,等2/10s,送5
305 	timeOut:	<0:loop, 0 or not set:1 time, >0:be the time(ms)
306 */
307 var SendKeysU;
308 SendKeys[generateCode.dLK]='Sleep';
309 function SendKeys(keys,appTitle,timeOut,timeInterval){
310  if(typeof WshShell!='object'||typeof WshShell!='object'&&typeof(WshShell=new ActiveXObject("WScript.Shell"))!='object')return 1;
311  if(isNaN(timeInterval)||timeInterval<1)timeInterval=100;	//	時間間隔
312  timeOut=timeOut?timeOut<0?-1:Math.floor(timeOut/timeInterval)+1:0;
313  if(appTitle)
314   while(!WshShell.AppActivate(appTitle))
315    if(timeOut--)Sleep(timeInterval);else return 2;
316  if(!SendKeysU)SendKeysU=100;	//	時間間隔單位
317  while(keys.match(/\{([.\d]+)\}/)){
318   WshShell.SendKeys(keys.substr(0,RegExp.index));
319   Sleep(SendKeysU*RegExp.$1);
320   keys=keys.substr(RegExp.lastIndex);
321  }
322  return WshShell.SendKeys(keys);
323 }
324 
325 
326 
327 
328 // Create an object reference: hack?!
329 //var windows=new WScript();
330 // Run the calculator program
331 //windows.explorer.run('calc.exe');
332 // Writing the local computer name to the screen
333 //document.write(windows.network.computerName);
334 // Copy files from one folder to another
335 //windows.fileSystem.copyFile('c:\\mydocuments\\*.txt', 'c:\\tempfolder\\');
336 
337 
338 
339 
340 
341 return (
342 	CeL.application.OS.Windows
343 );
344 }
345 
346 
347 });
348 
349