code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
/* gaeproxy - GoAgent / WallProxy client App for Android
* Copyright (C) 2011 <max.c.lv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ___====-_ _-====___
* _--^^^#####// \\#####^^^--_
* _-^##########// ( ) \\##########^-_
* -############// |\^^/| \\############-
* _/############// (@::@) \\############\_
* /#############(( \\// ))#############\
* -###############\\ (oo) //###############-
* -#################\\ / VV \ //#################-
* -###################\\/ \//###################-
* _#/|##########/\######( /\ )######/\##########|\#_
* |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
* ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
* ` ` ` ` / | | | | \ ' ' ' '
* ( | | | | )
* __\ | | | | /__
* (vvv(VVV)(VVV)vvv)
*
* HERE BE DRAGONS
*
*/
package org.gaeproxy;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.gaeproxy.db.DNSResponse;
import org.gaeproxy.db.DatabaseHelper;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.telephony.TelephonyManager;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.google.analytics.tracking.android.EasyTracker;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
public class GAEProxy extends PreferenceActivity implements OnSharedPreferenceChangeListener {
private static final String TAG = "GAEProxy";
public static final String PREFS_NAME = "GAEProxy";
private String proxy;
private int port;
private String sitekey = "";
private String proxyType = "GoAgent";
private boolean isGlobalProxy = false;
private boolean isHTTPSProxy = false;
private boolean isGFWList = false;
private static final int MSG_CRASH_RECOVER = 1;
private static final int MSG_INITIAL_FINISH = 2;
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(GAEProxy.this);
Editor ed = settings.edit();
switch (msg.what) {
case MSG_CRASH_RECOVER:
Toast.makeText(GAEProxy.this, R.string.crash_alert, Toast.LENGTH_LONG).show();
ed.putBoolean("isRunning", false);
break;
case MSG_INITIAL_FINISH:
if (pd != null) {
pd.dismiss();
pd = null;
}
break;
}
ed.commit();
super.handleMessage(msg);
}
};
private static ProgressDialog pd = null;
private CheckBoxPreference isAutoConnectCheck;
private CheckBoxPreference isGlobalProxyCheck;
private EditTextPreference proxyText;
private EditTextPreference portText;
private EditTextPreference sitekeyText;
private ListPreference proxyTypeList;
private CheckBoxPreference isHTTPSProxyCheck;
private CheckBoxPreference isGFWListCheck;
private CheckBoxPreference isRunningCheck;
private AdView adView;
private Preference proxyedApps;
private Preference browser;
private void copyAssets(String path) {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list(path);
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
for (int i = 0; i < files.length; i++) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(files[i]);
out = new FileOutputStream("/data/data/org.gaeproxy/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
private void crash_recovery() {
Utils.runRootCommand(Utils.getIptables() + " -t nat -F OUTPUT");
Utils.runCommand(GAEProxyService.BASE + "proxy.sh stop");
}
private void dirChecker(String dir) {
File f = new File(dir);
if (!f.isDirectory()) {
f.mkdirs();
}
}
private void disableAll() {
proxyText.setEnabled(false);
portText.setEnabled(false);
sitekeyText.setEnabled(false);
proxyedApps.setEnabled(false);
isGFWListCheck.setEnabled(false);
isAutoConnectCheck.setEnabled(false);
isGlobalProxyCheck.setEnabled(false);
isHTTPSProxyCheck.setEnabled(false);
proxyTypeList.setEnabled(false);
}
private void enableAll() {
proxyText.setEnabled(true);
portText.setEnabled(true);
if (proxyTypeList.getValue().equals("WallProxy")
|| proxyTypeList.getValue().equals("GoAgent"))
sitekeyText.setEnabled(true);
if (!isGlobalProxyCheck.isChecked())
proxyedApps.setEnabled(true);
isGlobalProxyCheck.setEnabled(true);
isAutoConnectCheck.setEnabled(true);
isGFWListCheck.setEnabled(true);
isHTTPSProxyCheck.setEnabled(true);
proxyTypeList.setEnabled(true);
}
private boolean install() {
PowerManager.WakeLock mWakeLock;
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
| PowerManager.ON_AFTER_RELEASE, "GAEProxy");
String data_path = Utils.getDataPath(this);
try {
final InputStream pythonZip = getAssets().open("modules/python.mp3");
final InputStream extraZip = getAssets().open("modules/python-extras.mp3");
unzip(pythonZip, "/data/data/org.gaeproxy/");
unzip(extraZip, data_path + "/");
} catch (IOException e) {
Log.e(TAG, "unable to install python");
}
if (mWakeLock.isHeld())
mWakeLock.release();
return true;
}
private boolean isTextEmpty(String s, String msg) {
if (s == null || s.length() <= 0) {
showAToast(msg);
return true;
}
return false;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addPreferencesFromResource(R.xml.gae_proxy_preference);
// Create the adView
adView = new AdView(GAEProxy.this, AdSize.BANNER, "a14d8be8a284afc");
// Lookup your LinearLayout assuming it’s been given
// the attribute android:id="@+id/mainLayout"
FrameLayout layout = (FrameLayout) findViewById(R.id.ad);
// Add the adView to it
layout.addView(adView);
// Initiate a generic request to load it with an ad
AdRequest aq = new AdRequest();
// aq.setTesting(true);
adView.loadAd(aq);
proxyText = (EditTextPreference) findPreference("proxy");
portText = (EditTextPreference) findPreference("port");
sitekeyText = (EditTextPreference) findPreference("sitekey");
proxyedApps = findPreference("proxyedApps");
browser = findPreference("browser");
isRunningCheck = (CheckBoxPreference) findPreference("isRunning");
isAutoConnectCheck = (CheckBoxPreference) findPreference("isAutoConnect");
isHTTPSProxyCheck = (CheckBoxPreference) findPreference("isHTTPSProxy");
isGlobalProxyCheck = (CheckBoxPreference) findPreference("isGlobalProxy");
proxyTypeList = (ListPreference) findPreference("proxyType");
isGFWListCheck = (CheckBoxPreference) findPreference("isGFWList");
if (pd == null)
pd = ProgressDialog.show(this, "", getString(R.string.initializing), true, true);
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
new Thread() {
@Override
public void run() {
Utils.isRoot();
String versionName;
try {
versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
versionName = "NONE";
}
if (!settings.getBoolean(versionName, false)) {
Editor edit = settings.edit();
edit.putBoolean(versionName, true);
edit.commit();
File f = new File("/data/data/org.gaeproxy/certs");
if (f.exists() && f.isFile())
f.delete();
if (!f.exists())
f.mkdir();
File hosts = new File("/data/data/org.gaeproxy/hosts");
if (hosts.exists())
hosts.delete();
copyAssets("");
Utils.runCommand("chmod 755 /data/data/org.gaeproxy/iptables\n"
+ "chmod 755 /data/data/org.gaeproxy/redsocks\n"
+ "chmod 755 /data/data/org.gaeproxy/proxy.sh\n"
+ "chmod 755 /data/data/org.gaeproxy/localproxy.sh\n"
+ "chmod 755 /data/data/org.gaeproxy/localproxy_en.sh\n"
+ "chmod 755 /data/data/org.gaeproxy/python-cl\n");
install();
}
if (!(new File(Utils.getDataPath(GAEProxy.this) + "/python-extras")).exists()) {
install();
}
if (!Utils.isInitialized() && !GAEProxyService.isServiceStarted()) {
try {
URL aURL = new URL("http://myhosts.sinaapp.com/hosts");
HttpURLConnection conn = (HttpURLConnection) aURL.openConnection();
conn.setConnectTimeout(3 * 1000);
conn.setReadTimeout(6 * 1000);
conn.connect();
InputStream input = new BufferedInputStream(conn.getInputStream());
OutputStream output = new FileOutputStream("/data/data/org.gaeproxy/hosts");
byte data[] = new byte[1024];
int count = 0;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
// Nothing
}
}
handler.sendEmptyMessage(MSG_INITIAL_FINISH);
}
}.start();
}
// 点击Menu时,系统调用当前Activity的onCreateOptionsMenu方法,并传一个实现了一个Menu接口的menu对象供你使用
@Override
public boolean onCreateOptionsMenu(Menu menu) {
/*
* add()方法的四个参数,依次是: 1、组别,如果不分组的话就写Menu.NONE,
* 2、Id,这个很重要,Android根据这个Id来确定不同的菜单 3、顺序,那个菜单现在在前面由这个参数的大小决定
* 4、文本,菜单的显示文本
*/
menu.add(Menu.NONE, Menu.FIRST + 1, 1, getString(R.string.recovery)).setIcon(
android.R.drawable.ic_menu_delete);
menu.add(Menu.NONE, Menu.FIRST + 2, 2, getString(R.string.about)).setIcon(
android.R.drawable.ic_menu_info_details);
// return true才会起作用
return true;
}
/** Called when the activity is closed. */
@Override
public void onDestroy() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isConnected", GAEProxyService.isServiceStarted());
editor.commit();
if (pd != null) {
pd.dismiss();
pd = null;
}
adView.destroy();
super.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // 按下的如果是BACK,同时没有重复
try {
finish();
} catch (Exception ignore) {
// Nothing
}
return true;
}
return super.onKeyDown(keyCode, event);
}
// 菜单项被选择事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case Menu.FIRST + 1:
recovery();
break;
case Menu.FIRST + 2:
String versionName = "";
try {
versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
versionName = "";
}
showAToast(getString(R.string.about) + " (" + versionName + ")\n\n"
+ getString(R.string.copy_rights));
break;
}
return true;
}
@Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(
this);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (preference.getKey() != null && preference.getKey().equals("proxyedApps")) {
Intent intent = new Intent(this, AppManager.class);
startActivity(intent);
} else if (preference.getKey() != null && preference.getKey().equals("browser")) {
Intent intent = new Intent(this, org.gaeproxy.zirco.ui.activities.MainActivity.class);
startActivity(intent);
} else if (preference.getKey() != null && preference.getKey().equals("isRunning")) {
if (!serviceStart()) {
Editor edit = settings.edit();
edit.putBoolean("isRunning", false);
edit.commit();
}
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (settings.getBoolean("isGlobalProxy", false))
proxyedApps.setEnabled(false);
else
proxyedApps.setEnabled(true);
if (proxyTypeList.getValue().equals("WallProxy")
|| proxyTypeList.getValue().equals("GoAgent"))
sitekeyText.setEnabled(true);
else
sitekeyText.setEnabled(false);
Editor edit = settings.edit();
if (GAEProxyService.isServiceStarted()) {
edit.putBoolean("isRunning", true);
} else {
if (settings.getBoolean("isRunning", false)) {
new Thread() {
@Override
public void run() {
crash_recovery();
handler.sendEmptyMessage(MSG_CRASH_RECOVER);
}
}.start();
}
edit.putBoolean("isRunning", false);
}
edit.commit();
if (settings.getBoolean("isRunning", false)) {
isRunningCheck.setChecked(true);
disableAll();
browser.setEnabled(true);
} else {
browser.setEnabled(false);
isRunningCheck.setChecked(false);
enableAll();
}
// Setup the initial values
if (!settings.getString("sitekey", "").equals(""))
sitekeyText.setSummary(settings.getString("sitekey", ""));
if (!settings.getString("proxyType", "").equals(""))
proxyTypeList.setSummary(settings.getString("proxyType", ""));
if (!settings.getString("port", "").equals(""))
portText.setSummary(settings.getString("port", getString(R.string.port_summary)));
if (!settings.getString("proxy", "").equals(""))
proxyText.setSummary(settings.getString("proxy", getString(R.string.proxy_summary)));
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// Let's do something a preference value changes
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
if (key.equals("isConnecting")) {
if (settings.getBoolean("isConnecting", false)) {
Log.d(TAG, "Connecting start");
if (pd == null)
pd = ProgressDialog.show(this, "", getString(R.string.connecting), true, true);
} else {
Log.d(TAG, "Connecting finish");
if (pd != null) {
pd.dismiss();
pd = null;
}
}
}
if (key.equals("isMarketEnable")) {
if (settings.getBoolean("isMarketEnable", false)) {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();
try {
Log.d(TAG, "Location: " + countryCode);
if (countryCode.toLowerCase().equals("cn")) {
String command = "setprop gsm.sim.operator.numeric 31026\n"
+ "setprop gsm.operator.numeric 31026\n"
+ "setprop gsm.sim.operator.iso-country us\n"
+ "setprop gsm.operator.iso-country us\n"
+ "chmod 755 /data/data/com.android.vending/shared_prefs\n"
+ "chmod 666 /data/data/com.android.vending/shared_prefs/vending_preferences.xml\n"
+ "setpref com.android.vending vending_preferences boolean metadata_paid_apps_enabled true\n"
+ "chmod 660 /data/data/com.android.vending/shared_prefs/vending_preferences.xml\n"
+ "chmod 771 /data/data/com.android.vending/shared_prefs\n"
+ "setown com.android.vending /data/data/com.android.vending/shared_prefs/vending_preferences.xml\n"
+ "kill $(ps | grep vending | tr -s ' ' | cut -d ' ' -f2)\n"
+ "rm -rf /data/data/com.android.vending/cache/*\n";
Utils.runRootCommand(command);
}
} catch (Exception e) {
// Nothing
}
}
}
if (key.equals("isGlobalProxy")) {
if (settings.getBoolean("isGlobalProxy", false))
proxyedApps.setEnabled(false);
else
proxyedApps.setEnabled(true);
}
if (key.equals("isRunning")) {
if (settings.getBoolean("isRunning", false)) {
disableAll();
browser.setEnabled(true);
isRunningCheck.setChecked(true);
} else {
browser.setEnabled(false);
isRunningCheck.setChecked(false);
enableAll();
}
}
if (key.equals("proxyType")) {
proxyTypeList.setSummary(settings.getString("proxyType", ""));
if (settings.getString("proxyType", "").equals("WallProxy")
|| settings.getString("proxyType", "").equals("GoAgent"))
sitekeyText.setEnabled(true);
else
sitekeyText.setEnabled(false);
} else if (key.equals("port"))
if (settings.getString("port", "").equals(""))
portText.setSummary(getString(R.string.port_summary));
else
portText.setSummary(settings.getString("port", ""));
else if (key.equals("sitekey"))
if (settings.getString("sitekey", "").equals(""))
sitekeyText.setSummary(getString(R.string.sitekey_summary));
else
sitekeyText.setSummary(settings.getString("sitekey", ""));
else if (key.equals("proxy"))
if (settings.getString("proxy", "").equals("")) {
proxyText.setSummary(getString(R.string.proxy_summary));
} else {
String host = settings.getString("proxy", "");
Editor ed = settings.edit();
if (!host.startsWith("http://") && !host.startsWith("https://")) {
ed.putString("proxy", "http://" + host);
}
ed.commit();
proxyText.setSummary(settings.getString("proxy", ""));
}
}
@Override
public void onStart() {
super.onStart();
EasyTracker.getInstance().activityStart(this);
}
@Override
public void onStop() {
super.onStop();
EasyTracker.getInstance().activityStop(this);
}
private void recovery() {
if (pd == null)
pd = ProgressDialog.show(this, "", getString(R.string.recovering), true, true);
final Handler h = new Handler() {
@Override
public void handleMessage(Message msg) {
if (pd != null) {
pd.dismiss();
pd = null;
}
}
};
try {
stopService(new Intent(this, GAEProxyService.class));
} catch (Exception e) {
// Nothing
}
new Thread() {
@Override
public void run() {
Utils.runRootCommand(Utils.getIptables() + " -t nat -F OUTPUT");
Utils.runCommand(GAEProxyService.BASE + "proxy.sh stop");
try {
DatabaseHelper helper = OpenHelperManager.getHelper(GAEProxy.this,
DatabaseHelper.class);
Dao<DNSResponse, String> dnsCacheDao = helper.getDNSCacheDao();
List<DNSResponse> list = dnsCacheDao.queryForAll();
for (DNSResponse resp : list) {
dnsCacheDao.delete(resp);
}
OpenHelperManager.releaseHelper();
} catch (Exception ignore) {
// Nothing
}
File f = new File("/data/data/org.gaeproxy/certs");
if (f.exists() && f.isFile())
f.delete();
if (f.exists() && f.isDirectory()) {
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++)
if (!files[i].isDirectory())
files[i].delete();
f.delete();
}
if (!f.exists())
f.mkdir();
File hosts = new File("/data/data/org.gaeproxy/hosts");
if (hosts.exists())
hosts.delete();
copyAssets("");
Utils.runCommand("chmod 755 /data/data/org.gaeproxy/iptables\n"
+ "chmod 755 /data/data/org.gaeproxy/redsocks\n"
+ "chmod 755 /data/data/org.gaeproxy/proxy.sh\n"
+ "chmod 755 /data/data/org.gaeproxy/localproxy.sh\n"
+ "chmod 755 /data/data/org.gaeproxy/localproxy_en.sh\n"
+ "chmod 755 /data/data/org.gaeproxy/python-cl\n");
install();
h.sendEmptyMessage(0);
}
}.start();
}
/**
* Called when connect button is clicked.
*
* @throws Exception
*/
public boolean serviceStart() {
if (GAEProxyService.isServiceStarted()) {
try {
stopService(new Intent(this, GAEProxyService.class));
} catch (Exception e) {
// Nothing
}
return false;
}
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
proxyType = settings.getString("proxyType", "GoAgent");
proxy = settings.getString("proxy", "");
if (isTextEmpty(proxy, getString(R.string.proxy_empty)))
return false;
if (proxy.contains("proxyofmax.appspot.com")) {
final TextView message = new TextView(this);
message.setPadding(10, 5, 10, 5);
final SpannableString s = new SpannableString(getText(R.string.default_proxy_alert));
Linkify.addLinks(s, Linkify.WEB_URLS);
message.setText(s);
message.setMovementMethod(LinkMovementMethod.getInstance());
new AlertDialog.Builder(this)
.setTitle(R.string.warning)
.setCancelable(false)
.setIcon(android.R.drawable.ic_dialog_info)
.setNegativeButton(getString(R.string.ok_iknow),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).setView(message).create().show();
}
String portText = settings.getString("port", "");
if (isTextEmpty(portText, getString(R.string.port_empty)))
return false;
try {
port = Integer.valueOf(portText);
if (port <= 1024) {
this.showAToast(getString(R.string.port_alert));
return false;
}
} catch (Exception e) {
this.showAToast(getString(R.string.port_alert));
return false;
}
sitekey = settings.getString("sitekey", "");
isGlobalProxy = settings.getBoolean("isGlobalProxy", false);
isHTTPSProxy = settings.getBoolean("isHTTPSProxy", false);
isGFWList = settings.getBoolean("isGFWList", false);
try {
Intent it = new Intent(this, GAEProxyService.class);
Bundle bundle = new Bundle();
bundle.putString("proxy", proxy);
bundle.putInt("port", port);
bundle.putString("sitekey", sitekey);
bundle.putBoolean("isGlobalProxy", isGlobalProxy);
bundle.putBoolean("isHTTPSProxy", isHTTPSProxy);
bundle.putString("proxyType", proxyType);
bundle.putBoolean("isGFWList", isGFWList);
it.putExtras(bundle);
startService(it);
} catch (Exception e) {
// Nothing
return false;
}
return true;
}
private void showAToast(String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(msg)
.setCancelable(false)
.setNegativeButton(getString(R.string.ok_iknow),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void unzip(InputStream zip, String path) {
dirChecker(path);
try {
ZipInputStream zin = new ZipInputStream(zip);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
if (ze.getName().contains("__MACOSX"))
continue;
// Log.v("Decompress", "Unzipping " + ze.getName());
if (ze.isDirectory()) {
dirChecker(path + ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(path + ze.getName());
byte data[] = new byte[10 * 1024];
int count;
while ((count = zin.read(data)) != -1) {
fout.write(data, 0, count);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch (Exception e) {
Log.e("Decompress", "unzip", e);
}
}
} | zyh3290-proxy | src/org/gaeproxy/GAEProxy.java | Java | gpl3 | 25,882 |
package org.gaeproxy;
import com.google.analytics.tracking.android.EasyTracker;
import android.app.Application;
public class GAEProxyApplication extends Application {
@Override
public void onCreate() {
EasyTracker.getInstance().setContext(this);
}
}
| zyh3290-proxy | src/org/gaeproxy/GAEProxyApplication.java | Java | gpl3 | 274 |
/* gaeproxy - GAppProxy / WallProxy client App for Android
* Copyright (C) 2011 <max.c.lv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ___====-_ _-====___
* _--^^^#####// \\#####^^^--_
* _-^##########// ( ) \\##########^-_
* -############// |\^^/| \\############-
* _/############// (@::@) \\############\_
* /#############(( \\// ))#############\
* -###############\\ (oo) //###############-
* -#################\\ / VV \ //#################-
* -###################\\/ \//###################-
* _#/|##########/\######( /\ )######/\##########|\#_
* |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
* ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
* ` ` ` ` / | | | | \ ' ' ' '
* ( | | | | )
* __\ | | | | /__
* (vvv(VVV)(VVV)vvv)
*
* HERE BE DRAGONS
*
*/
package org.gaeproxy;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.Log;
public class APNManager {
/**
* Selection of few interesting columns from APN table
*/
private static final class ApnInfo {
final long id;
final String apn;
final String type;
final String proxy;
final String port;
public ApnInfo(long id, String apn, String type, String proxy,
String port) {
this.id = id;
this.apn = apn;
this.type = type;
this.proxy = proxy;
this.port = port;
}
}
private static final String ID = "_id";
private static final String APN = "apn";
private static final String TYPE = "type";
private static final String PROXY = "proxy";
private static final String PORT = "port";
private static final String TAG = "GAEProxyAPNManager";
private static final Uri CONTENT_URI = Uri
.parse("content://telephony/carriers");
public static void clearAPNProxy(String proxy, String port, Context context) {
Cursor cursor = null;
ContentResolver resolver = context.getContentResolver();
List<ApnInfo> apns = null;
try {
cursor = resolver.query(CONTENT_URI, new String[] { ID, APN, TYPE,
PROXY, PORT }, "proxy is not null", null, null);
if (cursor == null)
return;
apns = createApnList(cursor);
} catch (Exception ignore) {
// Nothing
}
if (cursor != null) {
cursor.close();
}
for (ApnInfo apnInfo : apns) {
if (apnInfo.proxy.equals(proxy) && apnInfo.port.equals(port)) {
ContentValues values = new ContentValues();
values.put(PROXY, "");
values.put(PORT, "");
resolver.update(CONTENT_URI, values, ID + "=?",
new String[] { String.valueOf(apnInfo.id) });
}
}
}
/**
* Creates list of apn dtos from a DB cursor
*
* @param mCursor
* db cursor with select result set
* @return list of APN dtos
*/
private static List<ApnInfo> createApnList(Cursor mCursor) {
List<ApnInfo> result = new ArrayList<ApnInfo>();
mCursor.moveToFirst();
while (!mCursor.isAfterLast()) {
long id = mCursor.getLong(0);
String apn = mCursor.getString(1);
String type = mCursor.getString(2);
String proxy = mCursor.getString(3);
String port = mCursor.getString(4);
result.add(new ApnInfo(id, apn, type, proxy, port));
mCursor.moveToNext();
}
return result;
}
public static boolean isCMWap(Context context) {
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo == null)
return false;
if (!networkInfo.getTypeName().equals("WIFI")) {
Log.d(TAG, networkInfo.getExtraInfo());
if (networkInfo.getExtraInfo() != null
&& networkInfo.getExtraInfo().toLowerCase().equals("cmwap"))
return true;
}
return false;
}
public static void setAPNProxy(String proxy, String port, Context context) {
Cursor cursor = null;
ContentResolver resolver = context.getContentResolver();
List<ApnInfo> apns = null;
try {
cursor = resolver
.query(CONTENT_URI,
new String[] { ID, APN, TYPE, PROXY, PORT },
"current is not null and (not lower(type)='mms' or type is null) and proxy is null",
null, null);
if (cursor == null)
return;
apns = createApnList(cursor);
} catch (Exception ignore) {
// Nothing
}
if (cursor != null) {
cursor.close();
}
for (ApnInfo apnInfo : apns) {
ContentValues values = new ContentValues();
values.put(PROXY, proxy);
values.put(PORT, port);
resolver.update(CONTENT_URI, values, ID + "=?",
new String[] { String.valueOf(apnInfo.id) });
}
}
}
| zyh3290-proxy | src/org/gaeproxy/APNManager.java | Java | gpl3 | 5,892 |
package org.gaeproxy;
/**
* <p>
* Encodes and decodes to and from Base64 notation.
* </p>
* <p>
* Homepage: <a href="http://iharder.net/base64">http://iharder.net/base64</a>.
* </p>
*
* <p>
* Example:
* </p>
*
* <code>String encoded = Base64.encode( myByteArray );</code> <br />
* <code>byte[] myByteArray = Base64.decode( encoded );</code>
*
* <p>
* The <tt>options</tt> parameter, which appears in a few places, is used to
* pass several pieces of information to the encoder. In the "higher level"
* methods such as encodeBytes( bytes, options ) the options parameter can be
* used to indicate such things as first gzipping the bytes before encoding
* them, not inserting linefeeds, and encoding using the URL-safe and Ordered
* dialects.
* </p>
*
* <p>
* Note, according to <a
* href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>, Section 2.1,
* implementations should not add line feeds unless explicitly told to do so.
* I've got Base64 set to this behavior now, although earlier versions broke
* lines by default.
* </p>
*
* <p>
* The constants defined in Base64 can be OR-ed together to combine options, so
* you might make a call like this:
* </p>
*
* <code>String encoded = Base64.encodeBytes( mybytes, Base64.GZIP | Base64.DO_BREAK_LINES );</code>
* <p>
* to compress the data before encoding it and then making the output have
* newline characters.
* </p>
* <p>
* Also...
* </p>
* <code>String encoded = Base64.encodeBytes( crazyString.getBytes() );</code>
*
*
*
* <p>
* Change Log:
* </p>
* <ul>
* <li>v2.3.7 - Fixed subtle bug when base 64 input stream contained the value
* 01111111, which is an invalid base 64 character but should not throw an
* ArrayIndexOutOfBoundsException either. Led to discovery of mishandling (or
* potential for better handling) of other bad input characters. You should now
* get an IOException if you try decoding something that has bad characters in
* it.</li>
* <li>v2.3.6 - Fixed bug when breaking lines and the final byte of the encoded
* string ended in the last column; the buffer was not properly shrunk and
* contained an extra (null) byte that made it into the string.</li>
* <li>v2.3.5 - Fixed bug in {@link #encodeFromFile} where estimated buffer size
* was wrong for files of size 31, 34, and 37 bytes.</li>
* <li>v2.3.4 - Fixed bug when working with gzipped streams whereby flushing the
* Base64.OutputStream closed the Base64 encoding (by padding with equals signs)
* too soon. Also added an option to suppress the automatic decoding of gzipped
* streams. Also added experimental support for specifying a class loader when
* using the
* {@link #decodeToObject(java.lang.String, int, java.lang.ClassLoader)} method.
* </li>
* <li>v2.3.3 - Changed default char encoding to US-ASCII which reduces the
* internal Java footprint with its CharEncoders and so forth. Fixed some
* javadocs that were inconsistent. Removed imports and specified things like
* java.io.IOException explicitly inline.</li>
* <li>v2.3.2 - Reduced memory footprint! Finally refined the "guessing" of how
* big the final encoded data will be so that the code doesn't have to create
* two output arrays: an oversized initial one and then a final, exact-sized
* one. Big win when using the {@link #encodeBytesToBytes(byte[])} family of
* methods (and not using the gzip options which uses a different mechanism with
* streams and stuff).</li>
* <li>v2.3.1 - Added {@link #encodeBytesToBytes(byte[], int, int, int)} and
* some similar helper methods to be more efficient with memory by not returning
* a String but just a byte array.</li>
* <li>v2.3 - <strong>This is not a drop-in replacement!</strong> This is two
* years of comments and bug fixes queued up and finally executed. Thanks to
* everyone who sent me stuff, and I'm sorry I wasn't able to distribute your
* fixes to everyone else. Much bad coding was cleaned up including throwing
* exceptions where necessary instead of returning null values or something
* similar. Here are some changes that may affect you:
* <ul>
* <li><em>Does not break lines, by default.</em> This is to keep in compliance
* with <a href="http://www.faqs.org/rfcs/rfc3548.html">RFC3548</a>.</li>
* <li><em>Throws exceptions instead of returning null values.</em> Because some
* operations (especially those that may permit the GZIP option) use IO streams,
* there is a possiblity of an java.io.IOException being thrown. After some
* discussion and thought, I've changed the behavior of the methods to throw
* java.io.IOExceptions rather than return null if ever there's an error. I
* think this is more appropriate, though it will require some changes to your
* code. Sorry, it should have been done this way to begin with.</li>
* <li><em>Removed all references to System.out, System.err, and the like.</em>
* Shame on me. All I can say is sorry they were ever there.</li>
* <li><em>Throws NullPointerExceptions and IllegalArgumentExceptions</em> as
* needed such as when passed arrays are null or offsets are invalid.</li>
* <li>Cleaned up as much javadoc as I could to avoid any javadoc warnings. This
* was especially annoying before for people who were thorough in their own
* projects and then had gobs of javadoc warnings on this file.</li>
* </ul>
* <li>v2.2.1 - Fixed bug using URL_SAFE and ORDERED encodings. Fixed bug when
* using very small files (~< 40 bytes).</li>
* <li>v2.2 - Added some helper methods for encoding/decoding directly from one
* file to the next. Also added a main() method to support command line
* encoding/decoding from one file to the next. Also added these Base64
* dialects:
* <ol>
* <li>The default is RFC3548 format.</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.URLSAFE_FORMAT) generates
* URL and file name friendly format as described in Section 4 of RFC3548.
* http://www.faqs.org/rfcs/rfc3548.html</li>
* <li>Calling Base64.setFormat(Base64.BASE64_FORMAT.ORDERED_FORMAT) generates
* URL and file name friendly format that preserves lexical ordering as
* described in http://www.faqs.org/qa/rfcc-1940.html</li>
* </ol>
* Special thanks to Jim Kellerman at <a
* href="http://www.powerset.com/">http://www.powerset.com/</a> for contributing
* the new Base64 dialects.</li>
*
* <li>v2.1 - Cleaned up javadoc comments and unused variables and methods.
* Added some convenience methods for reading and writing to and from files.</li>
* <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on
* systems with other encodings (like EBCDIC).</li>
* <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
* encoded data was a single byte.</li>
* <li>v2.0 - I got rid of methods that used booleans to set options. Now
* everything is more consolidated and cleaner. The code now detects when data
* that's being decoded is gzip-compressed and will decompress it automatically.
* Generally things are cleaner. You'll probably have to change some method
* calls that you were making to support the new options format (<tt>int</tt>s
* that you "OR" together).</li>
* <li>v1.5.1 - Fixed bug when decompressing and decoding to a byte[] using
* <tt>decode( String s, boolean gzipCompressed )</tt>. Added the ability to
* "suspend" encoding in the Output Stream so you can turn on and off the
* encoding if you need to embed base64 data in an otherwise "normal" stream
* (like an XML file).</li>
* <li>v1.5 - Output stream pases on flush() command but doesn't do anything
* itself. This helps when using GZIP streams. Added the ability to
* GZip-compress objects before encoding them.</li>
* <li>v1.4 - Added helper methods to read/write files.</li>
* <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
* <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input
* stream where last buffer being read, if not completely full, was not
* returned.</li>
* <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the
* wrong time.</li>
* <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
* </ul>
*
* <p>
* I am placing this code in the Public Domain. Do with it as you will. This
* software comes with no guarantees or warranties but with plenty of
* well-wishing instead! Please visit <a
* href="http://iharder.net/base64">http://iharder.net/base64</a> periodically
* to check for updates or to contribute improvements.
* </p>
*
* @author Robert Harder
* @author rob@iharder.net
* @version 2.3.7
*/
public class Base64 {
/* ******** P U B L I C F I E L D S ******** */
/**
* A {@link Base64.InputStream} will read data from another
* <tt>java.io.InputStream</tt>, given in the constructor, and encode/decode
* to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class InputStream extends java.io.FilterInputStream {
private boolean encode; // Encoding or decoding
private int position; // Current position in the buffer
private byte[] buffer; // Small buffer holding converted data
private int bufferLength; // Length of buffer (3 or 4)
private int numSigBytes; // Number of meaningful bytes in the buffer
private int lineLength;
private boolean breakLines; // Break lines at less than 80 characters
private int options; // Record options used to create the stream.
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.InputStream} in DECODE mode.
*
* @param in
* the <tt>java.io.InputStream</tt> from which to read data.
* @since 1.3
*/
public InputStream(java.io.InputStream in) {
this(in, DECODE);
} // end constructor
/**
* Constructs a {@link Base64.InputStream} in either ENCODE or DECODE
* mode.
* <p>
* Valid options:
*
* <pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DO_BREAK_LINES: break lines at 76 characters
* (only meaningful when encoding)</i>
* </pre>
* <p>
* Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
*
*
* @param in
* the <tt>java.io.InputStream</tt> from which to read data.
* @param options
* Specified options
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DO_BREAK_LINES
* @since 2.0
*/
public InputStream(java.io.InputStream in, int options) {
super(in);
this.options = options; // Record for later
this.breakLines = (options & DO_BREAK_LINES) > 0;
this.encode = (options & ENCODE) > 0;
this.bufferLength = encode ? 4 : 3;
this.buffer = new byte[bufferLength];
this.position = -1;
this.lineLength = 0;
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Reads enough of the input stream to convert to/from Base64 and
* returns the next byte.
*
* @return next byte
* @since 1.3
*/
@Override
public int read() throws java.io.IOException {
// Do we need to get data?
if (position < 0) {
if (encode) {
byte[] b3 = new byte[3];
int numBinaryBytes = 0;
for (int i = 0; i < 3; i++) {
int b = in.read();
// If end of stream, b is -1.
if (b >= 0) {
b3[i] = (byte) b;
numBinaryBytes++;
} else {
break; // out of for loop
} // end else: end of stream
} // end for: each needed input byte
if (numBinaryBytes > 0) {
encode3to4(b3, 0, numBinaryBytes, buffer, 0, options);
position = 0;
numSigBytes = 4;
} // end if: got data
else {
return -1; // Must be end of stream
} // end else
} // end if: encoding
// Else decoding
else {
byte[] b4 = new byte[4];
int i = 0;
for (i = 0; i < 4; i++) {
// Read four "meaningful" bytes:
int b = 0;
do {
b = in.read();
} while (b >= 0
&& decodabet[b & 0x7f] <= WHITE_SPACE_ENC);
if (b < 0) {
break; // Reads a -1 if end of stream
} // end if: end of stream
b4[i] = (byte) b;
} // end for: each needed input byte
if (i == 4) {
numSigBytes = decode4to3(b4, 0, buffer, 0, options);
position = 0;
} // end if: got four characters
else if (i == 0) {
return -1;
} // end else if: also padded correctly
else {
// Must have broken out from above.
throw new java.io.IOException(
"Improperly padded Base64 input.");
} // end
} // end else: decode
} // end else: get data
// Got data?
if (position >= 0) {
// End of relevant data?
if ( /* !encode && */position >= numSigBytes) {
return -1;
} // end if: got data
if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) {
lineLength = 0;
return '\n';
} // end if
else {
lineLength++; // This isn't important when decoding
// but throwing an extra "if" seems
// just as wasteful.
int b = buffer[position++];
if (position >= bufferLength) {
position = -1;
} // end if: end
return b & 0xFF; // This is how you "cast" a byte that's
// intended to be unsigned.
} // end else
} // end if: position >= 0
// Else error
else {
throw new java.io.IOException(
"Error in Base64 code reading stream.");
} // end else
} // end read
/**
* Calls {@link #read()} repeatedly until the end of stream is reached
* or <var>len</var> bytes are read. Returns number of bytes read into
* array or -1 if end of stream is encountered.
*
* @param dest
* array to hold values
* @param off
* offset for array
* @param len
* max number of bytes to read into array
* @return bytes read into array or -1 if end of stream is encountered.
* @since 1.3
*/
@Override
public int read(byte[] dest, int off, int len)
throws java.io.IOException {
int i;
int b;
for (i = 0; i < len; i++) {
b = read();
if (b >= 0) {
dest[off + i] = (byte) b;
} else if (i == 0) {
return -1;
} else {
break; // Out of 'for' loop
} // Out of 'for' loop
} // end for: each byte read
return i;
} // end read
} // end inner class InputStream
/**
* A {@link Base64.OutputStream} will write data to another
* <tt>java.io.OutputStream</tt>, given in the constructor, and
* encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class OutputStream extends java.io.FilterOutputStream {
private boolean encode;
private int position;
private byte[] buffer;
private int bufferLength;
private int lineLength;
private boolean breakLines;
private byte[] b4; // Scratch used in a few places
private boolean suspendEncoding;
private int options; // Record for later
private byte[] decodabet; // Local copies to avoid extra method calls
/**
* Constructs a {@link Base64.OutputStream} in ENCODE mode.
*
* @param out
* the <tt>java.io.OutputStream</tt> to which data will be
* written.
* @since 1.3
*/
public OutputStream(java.io.OutputStream out) {
this(out, ENCODE);
} // end constructor
/**
* Constructs a {@link Base64.OutputStream} in either ENCODE or DECODE
* mode.
* <p>
* Valid options:
*
* <pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DO_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)</i>
* </pre>
* <p>
* Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
*
* @param out
* the <tt>java.io.OutputStream</tt> to which data will be
* written.
* @param options
* Specified options.
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DO_BREAK_LINES
* @since 1.3
*/
public OutputStream(java.io.OutputStream out, int options) {
super(out);
this.breakLines = (options & DO_BREAK_LINES) != 0;
this.encode = (options & ENCODE) != 0;
this.bufferLength = encode ? 3 : 4;
this.buffer = new byte[bufferLength];
this.position = 0;
this.lineLength = 0;
this.suspendEncoding = false;
this.b4 = new byte[4];
this.options = options;
this.decodabet = getDecodabet(options);
} // end constructor
/**
* Flushes and closes (I think, in the superclass) the stream.
*
* @since 1.3
*/
@Override
public void close() throws java.io.IOException {
// 1. Ensure that pending characters are written
flushBase64();
// 2. Actually close the stream
// Base class both flushes and closes.
super.close();
buffer = null;
out = null;
} // end close
/**
* Method added by PHIL. [Thanks, PHIL. -Rob] This pads the buffer
* without closing the stream.
*
* @throws java.io.IOException
* if there's an error.
*/
public void flushBase64() throws java.io.IOException {
if (position > 0) {
if (encode) {
out.write(encode3to4(b4, buffer, position, options));
position = 0;
} // end if: encoding
else {
throw new java.io.IOException(
"Base64 input not properly padded.");
} // end else: decoding
} // end if: buffer partially full
} // end flush
/**
* Resumes encoding of the stream. May be helpful if you need to embed a
* piece of base64-encoded data in a stream.
*
* @since 1.5.1
*/
public void resumeEncoding() {
this.suspendEncoding = false;
} // end resumeEncoding
/**
* Suspends encoding of the stream. May be helpful if you need to embed
* a piece of base64-encoded data in a stream.
*
* @throws java.io.IOException
* if there's an error flushing
* @since 1.5.1
*/
public void suspendEncoding() throws java.io.IOException {
flushBase64();
this.suspendEncoding = true;
} // end suspendEncoding
/**
* Calls {@link #write(int)} repeatedly until <var>len</var> bytes are
* written.
*
* @param theBytes
* array from which to read bytes
* @param off
* offset for array
* @param len
* max number of bytes to read into array
* @since 1.3
*/
@Override
public void write(byte[] theBytes, int off, int len)
throws java.io.IOException {
// Encoding suspended?
if (suspendEncoding) {
this.out.write(theBytes, off, len);
return;
} // end if: supsended
for (int i = 0; i < len; i++) {
write(theBytes[off + i]);
} // end for: each byte written
} // end write
/**
* Writes the byte to the output stream after converting to/from Base64
* notation. When encoding, bytes are buffered three at a time before
* the output stream actually gets a write() call. When decoding, bytes
* are buffered four at a time.
*
* @param theByte
* the byte to write
* @since 1.3
*/
@Override
public void write(int theByte) throws java.io.IOException {
// Encoding suspended?
if (suspendEncoding) {
this.out.write(theByte);
return;
} // end if: supsended
// Encode?
if (encode) {
buffer[position++] = (byte) theByte;
if (position >= bufferLength) { // Enough to encode.
this.out.write(encode3to4(b4, buffer, bufferLength, options));
lineLength += 4;
if (breakLines && lineLength >= MAX_LINE_LENGTH) {
this.out.write(NEW_LINE);
lineLength = 0;
} // end if: end of line
position = 0;
} // end if: enough to output
} // end if: encoding
// Else, Decoding
else {
// Meaningful Base64 character?
if (decodabet[theByte & 0x7f] > WHITE_SPACE_ENC) {
buffer[position++] = (byte) theByte;
if (position >= bufferLength) { // Enough to output.
int len = Base64.decode4to3(buffer, 0, b4, 0, options);
out.write(b4, 0, len);
position = 0;
} // end if: enough to output
} // end if: meaningful base64 character
else if (decodabet[theByte & 0x7f] != WHITE_SPACE_ENC) {
throw new java.io.IOException(
"Invalid character in Base64 data.");
} // end else: not white space either
} // end else: decoding
} // end write
} // end inner class OutputStream
/** No options specified. Value is zero. */
public final static int NO_OPTIONS = 0;
/** Specify encoding in first bit. Value is one. */
public final static int ENCODE = 1;
/** Specify decoding in first bit. Value is zero. */
public final static int DECODE = 0;
/** Specify that data should be gzip-compressed in second bit. Value is two. */
public final static int GZIP = 2;
/**
* Specify that gzipped data should <em>not</em> be automatically gunzipped.
*/
public final static int DONT_GUNZIP = 4;
/** Do break lines when encoding. Value is 8. */
public final static int DO_BREAK_LINES = 8;
/* ******** P R I V A T E F I E L D S ******** */
/**
* Encode using Base64-like encoding that is URL- and Filename-safe as
* described in Section 4 of RFC3548: <a
* href="http://www.faqs.org/rfcs/rfc3548.html"
* >http://www.faqs.org/rfcs/rfc3548.html</a>. It is important to note that
* data encoded this way is <em>not</em> officially valid Base64, or at the
* very least should not be called Base64 without also specifying that is
* was encoded using the URL- and Filename-safe dialect.
*/
public final static int URL_SAFE = 16;
/**
* Encode using the special "ordered" dialect of Base64 described here: <a
* href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-
* 1940.html</a>.
*/
public final static int ORDERED = 32;
/** Maximum line length (76) of Base64 output. */
private final static int MAX_LINE_LENGTH = 76;
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte) '=';
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte) '\n';
/** Preferred encoding. */
private final static String PREFERRED_ENCODING = "US-ASCII";
/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in
// encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in
// encoding
/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
/** The 64 valid Base64 values. */
/*
* Host platform me be something funny like EBCDIC, so we hardcode these
* values.
*/
private final static byte[] _STANDARD_ALPHABET = { (byte) 'A', (byte) 'B',
(byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',
(byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L',
(byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q',
(byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V',
(byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a',
(byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f',
(byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k',
(byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p',
(byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',
(byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z',
(byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',
(byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9',
(byte) '+', (byte) '/' };
/**
* Translates a Base64 value to either its 6-bit reconstruction value or a
* negative number indicating some other meaning.
**/
private final static byte[] _STANDARD_DECODABET = { -9, -9, -9, -9, -9, -9,
-9, -9, -9, // Decimal 0 - 8
-5, -5, // Whitespace: Tab and Linefeed
-9, -9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 -
// 26
-9, -9, -9, -9, -9, // Decimal 27 - 31
-5, // Whitespace: Space
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9, -9, -9, // Decimal 44 - 46
63, // Slash at decimal 47
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
-9, -9, -9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9, -9, -9, // Decimal 62 - 64
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through
// 'N'
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O'
// through 'Z'
-9, -9, -9, -9, -9, -9, // Decimal 91 - 96
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a'
// through 'm'
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n'
// through 'z'
-9, -9, -9, -9, -9 // Decimal 123 - 127
, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 -
// 139
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 -
// 152
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 -
// 165
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 -
// 178
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 -
// 191
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 -
// 204
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 -
// 217
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 -
// 230
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 -
// 243
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255
};
/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
/**
* Used in the URL- and Filename-safe dialect described in Section 4 of
* RFC3548: <a
* href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org
* /rfcs/rfc3548.html</a>. Notice that the last two bytes become "hyphen"
* and "underscore" instead of "plus" and "slash."
*/
private final static byte[] _URL_SAFE_ALPHABET = { (byte) 'A', (byte) 'B',
(byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',
(byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L',
(byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q',
(byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V',
(byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a',
(byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f',
(byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k',
(byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p',
(byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',
(byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z',
(byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',
(byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9',
(byte) '-', (byte) '_' };
/**
* Used in decoding URL- and Filename-safe dialects of Base64.
*/
private final static byte[] _URL_SAFE_DECODABET = { -9, -9, -9, -9, -9, -9,
-9, -9, -9, // Decimal 0 - 8
-5, -5, // Whitespace: Tab and Linefeed
-9, -9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 -
// 26
-9, -9, -9, -9, -9, // Decimal 27 - 31
-5, // Whitespace: Space
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
62, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
-9, -9, -9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9, -9, -9, // Decimal 62 - 64
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through
// 'N'
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O'
// through 'Z'
-9, -9, -9, -9, // Decimal 91 - 94
63, // Underscore at decimal 95
-9, // Decimal 96
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a'
// through 'm'
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n'
// through 'z'
-9, -9, -9, -9, -9 // Decimal 123 - 127
, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 -
// 139
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 -
// 152
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 -
// 165
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 -
// 178
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 -
// 191
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 -
// 204
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 -
// 217
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 -
// 230
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 -
// 243
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255
};
/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */
/**
* I don't get the point of this technique, but someone requested it, and it
* is described here: <a
* href="http://www.faqs.org/qa/rfcc-1940.html">http://
* www.faqs.org/qa/rfcc-1940.html</a>.
*/
private final static byte[] _ORDERED_ALPHABET = { (byte) '-', (byte) '0',
(byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5',
(byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'A',
(byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F',
(byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K',
(byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P',
(byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
(byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
(byte) '_', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd',
(byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i',
(byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',
(byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's',
(byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x',
(byte) 'y', (byte) 'z' };
/**
* Used in decoding the "ordered" dialect of Base64.
*/
private final static byte[] _ORDERED_DECODABET = { -9, -9, -9, -9, -9, -9,
-9, -9, -9, // Decimal 0 - 8
-5, -5, // Whitespace: Tab and Linefeed
-9, -9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 -
// 26
-9, -9, -9, -9, -9, // Decimal 27 - 31
-5, // Whitespace: Space
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
0, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine
-9, -9, -9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9, -9, -9, // Decimal 62 - 64
11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters 'A'
// through 'M'
24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters 'N'
// through 'Z'
-9, -9, -9, -9, // Decimal 91 - 94
37, // Underscore at decimal 95
-9, // Decimal 96
38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters 'a'
// through 'm'
51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters 'n'
// through 'z'
-9, -9, -9, -9, -9 // Decimal 123 - 127
, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128
// - 139
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 -
// 152
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 -
// 165
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 -
// 178
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 -
// 191
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 -
// 204
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 -
// 217
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 -
// 230
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 -
// 243
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255
};
/**
* Low-level access to decoding ASCII characters in the form of a byte
* array. <strong>Ignores GUNZIP option, if it's set.</strong> This is not
* generally a recommended method, although it is used internally as part of
* the decoding process. Special case: if len = 0, an empty array is
* returned. Still, if you need more speed and reduced memory footprint (and
* aren't gzipping), consider this method.
*
* @param source
* The Base64 encoded data
* @return decoded data
* @since 2.3.1
*/
public static byte[] decode(byte[] source) throws java.io.IOException {
byte[] decoded = null;
// try {
decoded = decode(source, 0, source.length, Base64.NO_OPTIONS);
// } catch( java.io.IOException ex ) {
// assert false :
// "IOExceptions only come from GZipping, which is turned off: " +
// ex.getMessage();
// }
return decoded;
}
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* Low-level access to decoding ASCII characters in the form of a byte
* array. <strong>Ignores GUNZIP option, if it's set.</strong> This is not
* generally a recommended method, although it is used internally as part of
* the decoding process. Special case: if len = 0, an empty array is
* returned. Still, if you need more speed and reduced memory footprint (and
* aren't gzipping), consider this method.
*
* @param source
* The Base64 encoded data
* @param off
* The offset of where to begin decoding
* @param len
* The length of characters to decode
* @param options
* Can specify options such as alphabet type to use
* @return decoded data
* @throws java.io.IOException
* If bogus characters exist in source data
* @since 1.3
*/
public static byte[] decode(byte[] source, int off, int len, int options)
throws java.io.IOException {
// Lots of error checking and exception throwing
if (source == null) {
throw new NullPointerException("Cannot decode null source array.");
} // end if
if (off < 0 || off + len > source.length) {
throw new IllegalArgumentException(
String.format(
"Source array with length %d cannot have offset of %d and process %d bytes.",
source.length, off, len));
} // end if
if (len == 0) {
return new byte[0];
} else if (len < 4) {
throw new IllegalArgumentException(
"Base64-encoded string must have at least four characters, but length specified was "
+ len);
} // end if
byte[] DECODABET = getDecodabet(options);
int len34 = len * 3 / 4; // Estimate on array size
byte[] outBuff = new byte[len34]; // Upper limit on size of output
int outBuffPosn = 0; // Keep track of where we're writing
byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating
// white space
int b4Posn = 0; // Keep track of four byte input buffer
int i = 0; // Source array counter
byte sbiDecode = 0; // Special value from DECODABET
for (i = off; i < off + len; i++) { // Loop through source
sbiDecode = DECODABET[source[i] & 0xFF];
// White space, Equals sign, or legit Base64 character
// Note the values such as -5 and -9 in the
// DECODABETs at the top of the file.
if (sbiDecode >= WHITE_SPACE_ENC) {
if (sbiDecode >= EQUALS_SIGN_ENC) {
b4[b4Posn++] = source[i]; // Save non-whitespace
if (b4Posn > 3) { // Time to decode?
outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn,
options);
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if (source[i] == EQUALS_SIGN) {
break;
} // end if: equals sign
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else {
// There's a bad input character in the Base64 stream.
throw new java.io.IOException(
String.format(
"Bad Base64 input character decimal %d in array position %d",
source[i] & 0xFF, i));
} // end else:
} // each input character
byte[] out = new byte[outBuffPosn];
System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
return out;
} // end decode
/**
* Decodes data from Base64 notation, automatically detecting
* gzip-compressed data and decompressing it.
*
* @param s
* the string to decode
* @return the decoded data
* @throws java.io.IOException
* If there is a problem
* @since 1.4
*/
public static byte[] decode(String s) throws java.io.IOException {
return decode(s, NO_OPTIONS);
}
/**
* Decodes data from Base64 notation, automatically detecting
* gzip-compressed data and decompressing it.
*
* @param s
* the string to decode
* @param options
* encode options such as URL_SAFE
* @return the decoded data
* @throws java.io.IOException
* if there is an error
* @throws NullPointerException
* if <tt>s</tt> is null
* @since 1.4
*/
public static byte[] decode(String s, int options)
throws java.io.IOException {
if (s == null) {
throw new NullPointerException("Input string was null.");
} // end if
byte[] bytes;
try {
bytes = s.getBytes(PREFERRED_ENCODING);
} // end try
catch (java.io.UnsupportedEncodingException uee) {
bytes = s.getBytes();
} // end catch
// </change>
// Decode
bytes = decode(bytes, 0, bytes.length, options);
// Check to see if it's gzip-compressed
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
boolean dontGunzip = (options & DONT_GUNZIP) != 0;
if ((bytes != null) && (bytes.length >= 4) && (!dontGunzip)) {
int head = (bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) {
java.io.ByteArrayInputStream bais = null;
java.util.zip.GZIPInputStream gzis = null;
java.io.ByteArrayOutputStream baos = null;
byte[] buffer = new byte[2048];
int length = 0;
try {
baos = new java.io.ByteArrayOutputStream();
bais = new java.io.ByteArrayInputStream(bytes);
gzis = new java.util.zip.GZIPInputStream(bais);
while ((length = gzis.read(buffer)) >= 0) {
baos.write(buffer, 0, length);
} // end while: reading input
// No error? Get new bytes.
bytes = baos.toByteArray();
} // end try
catch (java.io.IOException e) {
e.printStackTrace();
// Just return originally-decoded bytes
} // end catch
finally {
try {
baos.close();
} catch (Exception e) {
}
try {
gzis.close();
} catch (Exception e) {
}
try {
bais.close();
} catch (Exception e) {
}
} // end finally
} // end if: gzipped
} // end if: bytes.length >= 2
return bytes;
} // end decode
/**
* Decodes four bytes from array <var>source</var> and writes the resulting
* bytes (up to three of them) to <var>destination</var>. The source and
* destination arrays can be manipulated anywhere along their length by
* specifying <var>srcOffset</var> and <var>destOffset</var>. This method
* does not check to make sure your arrays are large enough to accomodate
* <var>srcOffset</var> + 4 for the <var>source</var> array or
* <var>destOffset</var> + 3 for the <var>destination</var> array. This
* method returns the actual number of bytes that were converted from the
* Base64 encoding.
* <p>
* This is the lowest level of the decoding methods with all possible
* parameters.
* </p>
*
*
* @param source
* the array to convert
* @param srcOffset
* the index where conversion begins
* @param destination
* the array to hold the conversion
* @param destOffset
* the index where output will be put
* @param options
* alphabet type is pulled from this (standard, url-safe,
* ordered)
* @return the number of decoded bytes converted
* @throws NullPointerException
* if source or destination arrays are null
* @throws IllegalArgumentException
* if srcOffset or destOffset are invalid or there is not enough
* room in the array.
* @since 1.3
*/
private static int decode4to3(byte[] source, int srcOffset,
byte[] destination, int destOffset, int options) {
// Lots of error checking and exception throwing
if (source == null) {
throw new NullPointerException("Source array was null.");
} // end if
if (destination == null) {
throw new NullPointerException("Destination array was null.");
} // end if
if (srcOffset < 0 || srcOffset + 3 >= source.length) {
throw new IllegalArgumentException(
String.format(
"Source array with length %d cannot have offset of %d and still process four bytes.",
source.length, srcOffset));
} // end if
if (destOffset < 0 || destOffset + 2 >= destination.length) {
throw new IllegalArgumentException(
String.format(
"Destination array with length %d cannot have offset of %d and still store three bytes.",
destination.length, destOffset));
} // end if
byte[] DECODABET = getDecodabet(options);
// Example: Dk==
if (source[srcOffset + 2] == EQUALS_SIGN) {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6
// )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
| ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12);
destination[destOffset] = (byte) (outBuff >>> 16);
return 1;
}
// Example: DkL=
else if (source[srcOffset + 3] == EQUALS_SIGN) {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6
// )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
| ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
| ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6);
destination[destOffset] = (byte) (outBuff >>> 16);
destination[destOffset + 1] = (byte) (outBuff >>> 8);
return 2;
}
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
// int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6
// )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)
| ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)
| ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6)
| ((DECODABET[source[srcOffset + 3]] & 0xFF));
destination[destOffset] = (byte) (outBuff >> 16);
destination[destOffset + 1] = (byte) (outBuff >> 8);
destination[destOffset + 2] = (byte) (outBuff);
return 3;
}
} // end decodeToBytes
/**
* Reads <tt>infile</tt> and decodes it to <tt>outfile</tt>.
*
* @param infile
* Input file
* @param outfile
* Output file
* @throws java.io.IOException
* if there is an error
* @since 2.2
*/
public static void decodeFileToFile(String infile, String outfile)
throws java.io.IOException {
byte[] decoded = Base64.decodeFromFile(infile);
java.io.OutputStream out = null;
try {
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream(outfile));
out.write(decoded);
} // end try
catch (java.io.IOException e) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try {
out.close();
} catch (Exception ex) {
}
} // end finally
} // end decodeFileToFile
/**
* Convenience method for reading a base64-encoded file and decoding it.
*
* <p>
* As of v 2.3, if there is a error, the method will throw an
* java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it
* just returned false, but in retrospect that's a pretty poor way to handle
* it.
* </p>
*
* @param filename
* Filename for reading encoded data
* @return decoded byte array
* @throws java.io.IOException
* if there is an error
* @since 2.1
*/
public static byte[] decodeFromFile(String filename)
throws java.io.IOException {
byte[] decodedData = null;
Base64.InputStream bis = null;
try {
// Set up some useful variables
java.io.File file = new java.io.File(filename);
byte[] buffer = null;
int length = 0;
int numBytes = 0;
// Check for size of file
if (file.length() > Integer.MAX_VALUE) {
throw new java.io.IOException(
"File is too big for this convenience method ("
+ file.length() + " bytes).");
} // end if: file too big for int index
buffer = new byte[(int) file.length()];
// Open a stream
bis = new Base64.InputStream(new java.io.BufferedInputStream(
new java.io.FileInputStream(file)), Base64.DECODE);
// Read until done
while ((numBytes = bis.read(buffer, length, 4096)) >= 0) {
length += numBytes;
} // end while
// Save in a variable to return
decodedData = new byte[length];
System.arraycopy(buffer, 0, decodedData, 0, length);
} // end try
catch (java.io.IOException e) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try {
bis.close();
} catch (Exception e) {
}
} // end finally
return decodedData;
} // end decodeFromFile
/**
* Convenience method for decoding data to a file.
*
* <p>
* As of v 2.3, if there is a error, the method will throw an
* java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it
* just returned false, but in retrospect that's a pretty poor way to handle
* it.
* </p>
*
* @param dataToDecode
* Base64-encoded data as a string
* @param filename
* Filename for saving decoded data
* @throws java.io.IOException
* if there is an error
* @since 2.1
*/
public static void decodeToFile(String dataToDecode, String filename)
throws java.io.IOException {
Base64.OutputStream bos = null;
try {
bos = new Base64.OutputStream(
new java.io.FileOutputStream(filename), Base64.DECODE);
bos.write(dataToDecode.getBytes(PREFERRED_ENCODING));
} // end try
catch (java.io.IOException e) {
throw e; // Catch and throw to execute finally{} block
} // end catch: java.io.IOException
finally {
try {
bos.close();
} catch (Exception e) {
}
} // end finally
} // end decodeToFile
/**
* Attempts to decode Base64 data and deserialize a Java Object within.
* Returns <tt>null</tt> if there was an error.
*
* @param encodedObject
* The Base64 data to decode
* @return The decoded and deserialized object
* @throws NullPointerException
* if encodedObject is null
* @throws java.io.IOException
* if there is a general error
* @throws ClassNotFoundException
* if the decoded object is of a class that cannot be found by
* the JVM
* @since 1.5
*/
public static Object decodeToObject(String encodedObject)
throws java.io.IOException, java.lang.ClassNotFoundException {
return decodeToObject(encodedObject, NO_OPTIONS, null);
}
/**
* Attempts to decode Base64 data and deserialize a Java Object within.
* Returns <tt>null</tt> if there was an error. If <tt>loader</tt> is not
* null, it will be the class loader used when deserializing.
*
* @param encodedObject
* The Base64 data to decode
* @param options
* Various parameters related to decoding
* @param loader
* Optional class loader to use in deserializing classes.
* @return The decoded and deserialized object
* @throws NullPointerException
* if encodedObject is null
* @throws java.io.IOException
* if there is a general error
* @throws ClassNotFoundException
* if the decoded object is of a class that cannot be found by
* the JVM
* @since 2.3.4
*/
public static Object decodeToObject(String encodedObject, int options,
final ClassLoader loader) throws java.io.IOException,
java.lang.ClassNotFoundException {
// Decode and gunzip if necessary
byte[] objBytes = decode(encodedObject, options);
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try {
bais = new java.io.ByteArrayInputStream(objBytes);
// If no custom class loader is provided, use Java's builtin OIS.
if (loader == null) {
ois = new java.io.ObjectInputStream(bais);
} // end if: no loader provided
// Else make a customized object input stream that uses
// the provided class loader.
else {
ois = new java.io.ObjectInputStream(bais) {
@Override
public Class<?> resolveClass(
java.io.ObjectStreamClass streamClass)
throws java.io.IOException, ClassNotFoundException {
Class c = Class.forName(streamClass.getName(), false,
loader);
if (c == null) {
return super.resolveClass(streamClass);
} else {
return c; // Class loader knows of this class.
} // end else: not null
} // end resolveClass
}; // end ois
} // end else: no custom class loader
obj = ois.readObject();
} // end try
catch (java.io.IOException e) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
catch (java.lang.ClassNotFoundException e) {
throw e; // Catch and throw in order to execute finally{}
} // end catch
finally {
try {
bais.close();
} catch (Exception e) {
}
try {
ois.close();
} catch (Exception e) {
}
} // end finally
return obj;
} // end decodeObject
/**
* Performs Base64 encoding on the <code>raw</code> ByteBuffer, writing it
* to the <code>encoded</code> ByteBuffer. This is an experimental feature.
* Currently it does not pass along any options (such as
* {@link #DO_BREAK_LINES} or {@link #GZIP}.
*
* @param raw
* input buffer
* @param encoded
* output buffer
* @since 2.3
*/
public static void encode(java.nio.ByteBuffer raw,
java.nio.ByteBuffer encoded) {
byte[] raw3 = new byte[3];
byte[] enc4 = new byte[4];
while (raw.hasRemaining()) {
int rem = Math.min(3, raw.remaining());
raw.get(raw3, 0, rem);
Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS);
encoded.put(enc4);
} // end input remaining
}
/**
* Performs Base64 encoding on the <code>raw</code> ByteBuffer, writing it
* to the <code>encoded</code> CharBuffer. This is an experimental feature.
* Currently it does not pass along any options (such as
* {@link #DO_BREAK_LINES} or {@link #GZIP}.
*
* @param raw
* input buffer
* @param encoded
* output buffer
* @since 2.3
*/
public static void encode(java.nio.ByteBuffer raw,
java.nio.CharBuffer encoded) {
byte[] raw3 = new byte[3];
byte[] enc4 = new byte[4];
while (raw.hasRemaining()) {
int rem = Math.min(3, raw.remaining());
raw.get(raw3, 0, rem);
Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS);
for (int i = 0; i < 4; i++) {
encoded.put((char) (enc4[i] & 0xFF));
}
} // end input remaining
}
/**
* Encodes up to the first three bytes of array <var>threeBytes</var> and
* returns a four-byte array in Base64 notation. The actual number of
* significant bytes in your array is given by <var>numSigBytes</var>. The
* array <var>threeBytes</var> needs only be as big as
* <var>numSigBytes</var>. Code can reuse a byte array by passing a
* four-byte array as <var>b4</var>.
*
* @param b4
* A reusable byte array to reduce array instantiation
* @param threeBytes
* the array to convert
* @param numSigBytes
* the number of significant bytes in your array
* @return four byte array in Base64 notation.
* @since 1.5.1
*/
private static byte[] encode3to4(byte[] b4, byte[] threeBytes,
int numSigBytes, int options) {
encode3to4(threeBytes, 0, numSigBytes, b4, 0, options);
return b4;
} // end encode3to4
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* <p>
* Encodes up to three bytes of the array <var>source</var> and writes the
* resulting four Base64 bytes to <var>destination</var>. The source and
* destination arrays can be manipulated anywhere along their length by
* specifying <var>srcOffset</var> and <var>destOffset</var>. This method
* does not check to make sure your arrays are large enough to accomodate
* <var>srcOffset</var> + 3 for the <var>source</var> array or
* <var>destOffset</var> + 4 for the <var>destination</var> array. The
* actual number of significant bytes in your array is given by
* <var>numSigBytes</var>.
* </p>
* <p>
* This is the lowest level of the encoding methods with all possible
* parameters.
* </p>
*
* @param source
* the array to convert
* @param srcOffset
* the index where conversion begins
* @param numSigBytes
* the number of significant bytes in your array
* @param destination
* the array to hold the conversion
* @param destOffset
* the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(byte[] source, int srcOffset,
int numSigBytes, byte[] destination, int destOffset, int options) {
byte[] ALPHABET = getAlphabet(options);
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an
// int.
int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)
| (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
| (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
switch (numSigBytes) {
case 3:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f];
return destination;
case 2:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
case 1:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = EQUALS_SIGN;
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4
/**
* Encodes a byte array into Base64 notation. Does not GZip-compress data.
*
* @param source
* The data to convert
* @return The data in Base64-encoded form
* @throws NullPointerException
* if source array is null
* @since 1.4
*/
public static String encodeBytes(byte[] source) {
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
String encoded = null;
try {
encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
} // end catch
assert encoded != null;
return encoded;
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:
*
* <pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example:
* <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
*
* <p>
* As of v 2.3, if there is an error with the GZIP stream, the method will
* throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier
* versions, it just returned a null value, but in retrospect that's a
* pretty poor way to handle it.
* </p>
*
*
* @param source
* The data to convert
* @param options
* Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException
* if there is an error
* @throws NullPointerException
* if source array is null
* @since 2.0
*/
public static String encodeBytes(byte[] source, int options)
throws java.io.IOException {
return encodeBytes(source, 0, source.length, options);
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation. Does not GZip-compress data.
*
* <p>
* As of v 2.3, if there is an error, the method will throw an
* java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it
* just returned a null value, but in retrospect that's a pretty poor way to
* handle it.
* </p>
*
*
* @param source
* The data to convert
* @param off
* Offset in array where conversion should begin
* @param len
* Length of data to convert
* @return The Base64-encoded data as a String
* @throws NullPointerException
* if source array is null
* @throws IllegalArgumentException
* if source array, offset, or length are invalid
* @since 1.4
*/
public static String encodeBytes(byte[] source, int off, int len) {
// Since we're not going to have the GZIP encoding turned on,
// we're not going to have an java.io.IOException thrown, so
// we should not force the user to have to catch it.
String encoded = null;
try {
encoded = encodeBytes(source, off, len, NO_OPTIONS);
} catch (java.io.IOException ex) {
assert false : ex.getMessage();
} // end catch
assert encoded != null;
return encoded;
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Example options:
*
* <pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example:
* <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
*
* <p>
* As of v 2.3, if there is an error with the GZIP stream, the method will
* throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier
* versions, it just returned a null value, but in retrospect that's a
* pretty poor way to handle it.
* </p>
*
*
* @param source
* The data to convert
* @param off
* Offset in array where conversion should begin
* @param len
* Length of data to convert
* @param options
* Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException
* if there is an error
* @throws NullPointerException
* if source array is null
* @throws IllegalArgumentException
* if source array, offset, or length are invalid
* @since 2.0
*/
public static String encodeBytes(byte[] source, int off, int len,
int options) throws java.io.IOException {
byte[] encoded = encodeBytesToBytes(source, off, len, options);
// Return value according to relevant encoding.
try {
return new String(encoded, PREFERRED_ENCODING);
} // end try
catch (java.io.UnsupportedEncodingException uue) {
return new String(encoded);
} // end catch
} // end encodeBytes
/**
* Similar to {@link #encodeBytes(byte[])} but returns a byte array instead
* of instantiating a String. This is more efficient if you're working with
* I/O streams and have large data sets to encode.
*
*
* @param source
* The data to convert
* @return The Base64-encoded data as a byte[] (of ASCII characters)
* @throws NullPointerException
* if source array is null
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes(byte[] source) {
byte[] encoded = null;
try {
encoded = encodeBytesToBytes(source, 0, source.length,
Base64.NO_OPTIONS);
} catch (java.io.IOException ex) {
assert false : "IOExceptions only come from GZipping, which is turned off: "
+ ex.getMessage();
}
return encoded;
}
/**
* Similar to {@link #encodeBytes(byte[], int, int, int)} but returns a byte
* array instead of instantiating a String. This is more efficient if you're
* working with I/O streams and have large data sets to encode.
*
*
* @param source
* The data to convert
* @param off
* Offset in array where conversion should begin
* @param len
* Length of data to convert
* @param options
* Specified options
* @return The Base64-encoded data as a String
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException
* if there is an error
* @throws NullPointerException
* if source array is null
* @throws IllegalArgumentException
* if source array, offset, or length are invalid
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes(byte[] source, int off, int len,
int options) throws java.io.IOException {
if (source == null) {
throw new NullPointerException("Cannot serialize a null array.");
} // end if: null
if (off < 0) {
throw new IllegalArgumentException("Cannot have negative offset: "
+ off);
} // end if: off < 0
if (len < 0) {
throw new IllegalArgumentException("Cannot have length offset: "
+ len);
} // end if: len < 0
if (off + len > source.length) {
throw new IllegalArgumentException(
String.format(
"Cannot have offset of %d and length of %d with array of length %d",
off, len, source.length));
} // end if: off < 0
// Compress?
if ((options & GZIP) != 0) {
java.io.ByteArrayOutputStream baos = null;
java.util.zip.GZIPOutputStream gzos = null;
Base64.OutputStream b64os = null;
try {
// GZip -> Base64 -> ByteArray
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream(baos, ENCODE | options);
gzos = new java.util.zip.GZIPOutputStream(b64os);
gzos.write(source, off, len);
gzos.close();
} // end try
catch (java.io.IOException e) {
// Catch it and then throw it immediately so that
// the finally{} block is called for cleanup.
throw e;
} // end catch
finally {
try {
gzos.close();
} catch (Exception e) {
}
try {
b64os.close();
} catch (Exception e) {
}
try {
baos.close();
} catch (Exception e) {
}
} // end finally
return baos.toByteArray();
} // end if: compress
// Else, don't compress. Better not to use streams at all then.
else {
boolean breakLines = (options & DO_BREAK_LINES) != 0;
// int len43 = len * 4 / 3;
// byte[] outBuff = new byte[ ( len43 ) // Main 4:3
// + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
// + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
// Try to determine more precisely how big the array needs to be.
// If we get it right, we don't have to do an array copy, and
// we save a bunch of memory.
int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); // Bytes needed
// for actual
// encoding
if (breakLines) {
encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline
// characters
}
byte[] outBuff = new byte[encLen];
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for (; d < len2; d += 3, e += 4) {
encode3to4(source, d + off, 3, outBuff, e, options);
lineLength += 4;
if (breakLines && lineLength >= MAX_LINE_LENGTH) {
outBuff[e + 4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if (d < len) {
encode3to4(source, d + off, len - d, outBuff, e, options);
e += 4;
} // end if: some padding needed
// Only resize array if we didn't guess it right.
if (e <= outBuff.length - 1) {
// If breaking lines and the last byte falls right at
// the line length (76 bytes per line), there will be
// one extra byte, and the array will need to be resized.
// Not too bad of an estimate on array size, I'd say.
byte[] finalOut = new byte[e];
System.arraycopy(outBuff, 0, finalOut, 0, e);
// System.err.println("Having to resize array from " +
// outBuff.length + " to " + e );
return finalOut;
} else {
// System.err.println("No need to resize array.");
return outBuff;
}
} // end else: don't compress
} // end encodeBytesToBytes
/**
* Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>.
*
* @param infile
* Input file
* @param outfile
* Output file
* @throws java.io.IOException
* if there is an error
* @since 2.2
*/
public static void encodeFileToFile(String infile, String outfile)
throws java.io.IOException {
String encoded = Base64.encodeFromFile(infile);
java.io.OutputStream out = null;
try {
out = new java.io.BufferedOutputStream(
new java.io.FileOutputStream(outfile));
out.write(encoded.getBytes("US-ASCII")); // Strict, 7-bit output.
} // end try
catch (java.io.IOException e) {
throw e; // Catch and release to execute finally{}
} // end catch
finally {
try {
out.close();
} catch (Exception ex) {
}
} // end finally
} // end encodeFileToFile
/**
* Convenience method for reading a binary file and base64-encoding it.
*
* <p>
* As of v 2.3, if there is a error, the method will throw an
* java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it
* just returned false, but in retrospect that's a pretty poor way to handle
* it.
* </p>
*
* @param filename
* Filename for reading binary data
* @return base64-encoded string
* @throws java.io.IOException
* if there is an error
* @since 2.1
*/
public static String encodeFromFile(String filename)
throws java.io.IOException {
String encodedData = null;
Base64.InputStream bis = null;
try {
// Set up some useful variables
java.io.File file = new java.io.File(filename);
byte[] buffer = new byte[Math.max((int) (file.length() * 1.4 + 1),
40)]; // Need max() for math on small files (v2.2.1); Need
// +1 for a few corner cases (v2.3.5)
int length = 0;
int numBytes = 0;
// Open a stream
bis = new Base64.InputStream(new java.io.BufferedInputStream(
new java.io.FileInputStream(file)), Base64.ENCODE);
// Read until done
while ((numBytes = bis.read(buffer, length, 4096)) >= 0) {
length += numBytes;
} // end while
// Save in a variable to return
encodedData = new String(buffer, 0, length,
Base64.PREFERRED_ENCODING);
} // end try
catch (java.io.IOException e) {
throw e; // Catch and release to execute finally{}
} // end catch: java.io.IOException
finally {
try {
bis.close();
} catch (Exception e) {
}
} // end finally
return encodedData;
} // end encodeFromFile
/**
* Serializes an object and returns the Base64-encoded version of that
* serialized object.
*
* <p>
* As of v 2.3, if the object cannot be serialized or there is another
* error, the method will throw an java.io.IOException. <b>This is new to
* v2.3!</b> In earlier versions, it just returned a null value, but in
* retrospect that's a pretty poor way to handle it.
* </p>
*
* The object is not GZip-compressed before being encoded.
*
* @param serializableObject
* The object to encode
* @return The Base64-encoded object
* @throws java.io.IOException
* if there is an error
* @throws NullPointerException
* if serializedObject is null
* @since 1.4
*/
public static String encodeObject(java.io.Serializable serializableObject)
throws java.io.IOException {
return encodeObject(serializableObject, NO_OPTIONS);
} // end encodeObject
/**
* Serializes an object and returns the Base64-encoded version of that
* serialized object.
*
* <p>
* As of v 2.3, if the object cannot be serialized or there is another
* error, the method will throw an java.io.IOException. <b>This is new to
* v2.3!</b> In earlier versions, it just returned a null value, but in
* retrospect that's a pretty poor way to handle it.
* </p>
*
* The object is not GZip-compressed before being encoded.
* <p>
* Example options:
*
* <pre>
* GZIP: gzip-compresses object before encoding it.
* DO_BREAK_LINES: break lines at 76 characters
* </pre>
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
* <p>
* Example:
* <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>
*
* @param serializableObject
* The object to encode
* @param options
* Specified options
* @return The Base64-encoded object
* @see Base64#GZIP
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException
* if there is an error
* @since 2.0
*/
public static String encodeObject(java.io.Serializable serializableObject,
int options) throws java.io.IOException {
if (serializableObject == null) {
throw new NullPointerException("Cannot serialize a null object.");
} // end if: null
// Streams
java.io.ByteArrayOutputStream baos = null;
java.io.OutputStream b64os = null;
java.util.zip.GZIPOutputStream gzos = null;
java.io.ObjectOutputStream oos = null;
try {
// ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream(baos, ENCODE | options);
if ((options & GZIP) != 0) {
// Gzip
gzos = new java.util.zip.GZIPOutputStream(b64os);
oos = new java.io.ObjectOutputStream(gzos);
} else {
// Not gzipped
oos = new java.io.ObjectOutputStream(b64os);
}
oos.writeObject(serializableObject);
} // end try
catch (java.io.IOException e) {
// Catch it and then throw it immediately so that
// the finally{} block is called for cleanup.
throw e;
} // end catch
finally {
try {
oos.close();
} catch (Exception e) {
}
try {
gzos.close();
} catch (Exception e) {
}
try {
b64os.close();
} catch (Exception e) {
}
try {
baos.close();
} catch (Exception e) {
}
} // end finally
// Return value according to relevant encoding.
try {
return new String(baos.toByteArray(), PREFERRED_ENCODING);
} // end try
catch (java.io.UnsupportedEncodingException uue) {
// Fall back to some Java default
return new String(baos.toByteArray());
} // end catch
} // end encode
/**
* Convenience method for encoding data to a file.
*
* <p>
* As of v 2.3, if there is a error, the method will throw an
* java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it
* just returned false, but in retrospect that's a pretty poor way to handle
* it.
* </p>
*
* @param dataToEncode
* byte array of data to encode in base64 form
* @param filename
* Filename for saving encoded data
* @throws java.io.IOException
* if there is an error
* @throws NullPointerException
* if dataToEncode is null
* @since 2.1
*/
public static void encodeToFile(byte[] dataToEncode, String filename)
throws java.io.IOException {
if (dataToEncode == null) {
throw new NullPointerException("Data to encode was null.");
} // end iff
Base64.OutputStream bos = null;
try {
bos = new Base64.OutputStream(
new java.io.FileOutputStream(filename), Base64.ENCODE);
bos.write(dataToEncode);
} // end try
catch (java.io.IOException e) {
throw e; // Catch and throw to execute finally{} block
} // end catch: java.io.IOException
finally {
try {
bos.close();
} catch (Exception e) {
}
} // end finally
} // end encodeToFile
/**
* Returns one of the _SOMETHING_ALPHABET byte arrays depending on the
* options specified. It's possible, though silly, to specify ORDERED
* <b>and</b> URLSAFE in which case one of them will be picked, though there
* is no guarantee as to which one will be picked.
*/
private final static byte[] getAlphabet(int options) {
if ((options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_ALPHABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_ALPHABET;
} else {
return _STANDARD_ALPHABET;
}
} // end getAlphabet
/* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
/**
* Returns one of the _SOMETHING_DECODABET byte arrays depending on the
* options specified. It's possible, though silly, to specify ORDERED and
* URL_SAFE in which case one of them will be picked, though there is no
* guarantee as to which one will be picked.
*/
private final static byte[] getDecodabet(int options) {
if ((options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_DECODABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_DECODABET;
} else {
return _STANDARD_DECODABET;
}
} // end getAlphabet
/* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
/** Defeats instantiation. */
private Base64() {
}
} // end class Base64
| zyh3290-proxy | src/org/gaeproxy/Base64.java | Java | gpl3 | 75,120 |
package org.gaeproxy;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;
import org.gaeproxy.db.DNSResponse;
import org.gaeproxy.db.DatabaseHelper;
import android.content.Context;
import android.util.Log;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
/**
* 此类实现了DNS代理
*
* @author biaji
*
*/
public class DNSServer implements Runnable {
public static byte[] int2byte(int res) {
byte[] targets = new byte[4];
targets[0] = (byte) (res & 0xff);// 最低位
targets[1] = (byte) ((res >> 8) & 0xff);// 次低位
targets[2] = (byte) ((res >> 16) & 0xff);// 次高位
targets[3] = (byte) (res >>> 24);// 最高位,无符号右移。
return targets;
}
private final String TAG = "GAEDNSProxy";
private DatagramSocket srvSocket;
public HashSet<String> domains;
private int srvPort = 8153;
final protected int DNS_PKG_HEADER_LEN = 12;
final private int[] DNS_HEADERS = { 0, 0, 0x81, 0x80, 0, 0, 0, 0, 0, 0, 0, 0 };
final private int[] DNS_PAYLOAD = { 0xc0, 0x0c, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3c,
0x00, 0x04 };
final private int IP_SECTION_LEN = 4;
private boolean inService = false;
/**
* 内建自定义缓存
*
*/
private Hashtable<String, String> orgCache = new Hashtable<String, String>();
private String appHost = "203.208.46.1";
private static final String CANT_RESOLVE = "Error";
private DatabaseHelper helper;
private final static AsyncHttpClient client = new AsyncHttpClient();
public DNSServer(Context ctx, String appHost) {
this.appHost = appHost;
client.setTimeout(6 * 1000);
domains = new HashSet<String>();
initOrgCache();
OpenHelperManager.setOpenHelperClass(DatabaseHelper.class);
if (helper == null) {
helper = OpenHelperManager.getHelper(ctx, DatabaseHelper.class);
}
try {
srvSocket = new DatagramSocket(0, InetAddress.getByName("127.0.0.1"));
srvPort = srvSocket.getLocalPort();
Log.d(TAG, "start at port " + srvPort);
inService = true;
} catch (SocketException e) {
Log.e(TAG, "error to initilized at port " + srvPort, e);
} catch (UnknownHostException e) {
Log.e(TAG, "error to initilized at port " + srvPort, e);
}
}
/**
* 在缓存中添加一个域名解析
*
* @param questDomainName
* 域名
* @param answer
* 解析结果
*/
private synchronized void addToCache(String questDomainName, byte[] answer) {
DNSResponse response = new DNSResponse(questDomainName);
response.setAddress(DNSResponse.getIPString(answer));
try {
Dao<DNSResponse, String> dnsCacheDao = helper.getDNSCacheDao();
dnsCacheDao.createOrUpdate(response);
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO", e);
}
}
public void close() throws IOException {
inService = false;
srvSocket.close();
if (helper != null) {
OpenHelperManager.releaseHelper();
helper = null;
}
Log.i(TAG, "DNS Proxy closed");
}
/*
* Create a DNS response packet, which will send back to application.
*
* @author yanghong
*
* Reference to:
*
* Mini Fake DNS server (Python)
* http://code.activestate.com/recipes/491264-mini-fake-dns-server/
*
* DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION
* http://www.ietf.org/rfc/rfc1035.txt
*/
protected byte[] createDNSResponse(byte[] quest, byte[] ips) {
byte[] response = null;
int start = 0;
response = new byte[128];
for (int val : DNS_HEADERS) {
response[start] = (byte) val;
start++;
}
System.arraycopy(quest, 0, response, 0, 2); /* 0:2 | NAME */
System.arraycopy(quest, 4, response, 4, 2); /* 4:6 -> 4:6 | TYPE */
System.arraycopy(quest, 4, response, 6, 2); /* 4:6 -> 7:9 | CLASS */
/* 10:14 | TTL */
System.arraycopy(quest, DNS_PKG_HEADER_LEN, response, start, quest.length
- DNS_PKG_HEADER_LEN); /* 12:~ -> 15:~ */
start += quest.length - DNS_PKG_HEADER_LEN;
for (int val : DNS_PAYLOAD) {
response[start] = (byte) val;
start++;
}
/* IP address in response */
for (byte ip : ips) {
response[start] = ip;
start++;
}
byte[] result = new byte[start];
System.arraycopy(response, 0, result, 0, start);
return result;
}
public void fetchAnswerHTTP(final DatagramPacket dnsq, final byte[] quest) {
final String domain = getRequestDomain(quest);
DomainValidator dv = DomainValidator.getInstance();
/* Not support reverse domain name query */
if (domain.endsWith("ip6.arpa") || domain.endsWith("in-addr.arpa") || !dv.isValid(domain)) {
final byte[] answer = createDNSResponse(quest, parseIPString("127.0.0.1"));
addToCache(domain, answer);
sendDns(answer, dnsq, srvSocket);
synchronized (domains) {
domains.remove(domain);
}
return;
}
final long startTime = System.currentTimeMillis();
AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
@Override
public void onFinish() {
synchronized (domains) {
domains.remove(domain);
}
}
@Override
public void onSuccess(String response) {
try {
byte[] answer = null;
if (response == null) {
Log.e(TAG, "Failed to resolve domain name: " + domain);
return;
}
response = response.trim();
if (response.equals(CANT_RESOLVE)) {
Log.e(TAG, "Cannot resolve domain name: " + domain);
return;
}
byte[] ips = parseIPString(response);
if (ips != null) {
answer = createDNSResponse(quest, ips);
}
if (answer != null && answer.length != 0) {
addToCache(domain, answer);
sendDns(answer, dnsq, srvSocket);
Log.d(TAG, "Success to resolve: " + domain + " length: " + answer.length
+ " cost: " + (System.currentTimeMillis() - startTime) / 1000 + "s");
} else {
Log.e(TAG, "The size of DNS packet returned is 0");
}
} catch (Exception e) {
// Nothing
}
}
};
resolveDomainName(domain, handler);
}
/**
* 获取UDP DNS请求的域名
*
* @param request
* dns udp包
* @return 请求的域名
*/
protected String getRequestDomain(byte[] request) {
String requestDomain = "";
int reqLength = request.length;
if (reqLength > 13) { // 包含包体
byte[] question = new byte[reqLength - 12];
System.arraycopy(request, 12, question, 0, reqLength - 12);
requestDomain = parseDomain(question);
if (requestDomain.length() > 1)
requestDomain = requestDomain.substring(0, requestDomain.length() - 1);
}
return requestDomain;
}
public int getServPort() {
return this.srvPort;
}
private void initOrgCache() {
InputStream is = null;
try {
File f = new File("/data/data/org.gaeproxy/hosts");
if (!f.exists()) {
URL aURL = new URL("http://myhosts.sinaapp.com/hosts");
HttpURLConnection conn = (HttpURLConnection) aURL.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(10000);
conn.connect();
is = conn.getInputStream();
} else {
is = new FileInputStream(f);
}
loadOrgCache(is);
is.close();
} catch (Exception e) {
Log.e(TAG, "cannot get remote host files", e);
}
}
public boolean isClosed() {
return srvSocket.isClosed();
}
public boolean isInService() {
return inService;
}
/**
* 由缓存载入域名解析缓存
*/
private void loadCache() {
try {
Dao<DNSResponse, String> dnsCacheDao = helper.getDNSCacheDao();
List<DNSResponse> list = dnsCacheDao.queryForAll();
for (DNSResponse resp : list) {
// expire after 10 days
if ((System.currentTimeMillis() - resp.getTimestamp()) > 864000000L) {
Log.d(TAG, "deleted: " + resp.getRequest());
dnsCacheDao.delete(resp);
}
}
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO", e);
}
}
private void loadOrgCache(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
if (line == null)
return;
if (!line.startsWith("#SSHTunnel"))
return;
while (true) {
line = reader.readLine();
if (line == null)
break;
if (line.startsWith("#"))
continue;
line = line.trim().toLowerCase();
if (line.equals(""))
continue;
String[] hosts = line.split(" ");
if (hosts.length == 2) {
orgCache.put(hosts[1], hosts[0]);
}
}
Log.d(TAG, "Load hosts: " + orgCache.size());
}
/**
* 解析域名
*
* @param request
* @return
*/
private String parseDomain(byte[] request) {
String result = "";
int length = request.length;
int partLength = request[0];
if (partLength == 0)
return result;
try {
byte[] left = new byte[length - partLength - 1];
System.arraycopy(request, partLength + 1, left, 0, length - partLength - 1);
result = new String(request, 1, partLength) + ".";
result += parseDomain(left);
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage());
}
return result;
}
/*
* Parse IP string into byte, do validation.
*
* @param ip IP string
*
* @return IP in byte array
*/
protected byte[] parseIPString(String ip) {
byte[] result = null;
int value;
int i = 0;
String[] ips = null;
ips = ip.split("\\.");
// Log.d(TAG, "Start parse ip string: " + ip + ", Sectons: " +
// ips.length);
if (ips.length != IP_SECTION_LEN) {
Log.e(TAG, "Malformed IP string : " + ip);
return null;
}
result = new byte[IP_SECTION_LEN];
for (String section : ips) {
try {
value = Integer.parseInt(section);
/* 0.*.*.* and *.*.*.0 is invalid */
if ((i == 0 || i == 3) && value == 0) {
return null;
}
result[i] = (byte) value;
i++;
} catch (NumberFormatException e) {
Log.e(TAG, "Malformed IP string: " + ip);
return null;
}
}
return result;
}
private synchronized DNSResponse queryFromCache(String questDomainName) {
try {
Dao<DNSResponse, String> dnsCacheDao = helper.getDNSCacheDao();
return dnsCacheDao.queryForId(questDomainName);
} catch (Exception e) {
Log.e(TAG, "Cannot open DAO", e);
}
return null;
}
/*
* Resolve host name by access a DNSRelay running on GAE:
*
* Example:
*
* http://www.hosts.dotcloud.com/lookup.php?(domain name encoded)
* http://gaednsproxy.appspot.com/?d=(domain name encoded)
*/
private void resolveDomainName(String domain, AsyncHttpResponseHandler handler) {
String ip = null;
InputStream is;
String encode_host = URLEncoder.encode(Base64.encodeBytes(Base64.encodeBytesToBytes(domain
.getBytes())));
String url = "http://gaednsproxy1.appspot.com/?d=" + encode_host;
String host = "gaednsproxy1.appspot.com";
url = url.replace(host, appHost);
Random random = new Random(System.currentTimeMillis());
int n = random.nextInt(2);
if (n == 0) {
url = "http://gaednsproxy2.appspot.com/?d=" + encode_host;
host = "gaednsproxy2.appspot.com";
url = url.replace(host, appHost);
} else if (n == 1) {
url = "http://gaednsproxy3.appspot.com/?d=" + encode_host;
host = "gaednsproxy3.appspot.com";
url = url.replace(host, appHost);
}
// Log.d(TAG, "DNS Relay URL: " + url);
// RFC 2616: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
client.get(url, host, handler);
}
@Override
public void run() {
loadCache();
byte[] qbuffer = new byte[576];
while (true) {
try {
final DatagramPacket dnsq = new DatagramPacket(qbuffer, qbuffer.length);
srvSocket.receive(dnsq);
// try to build dnsreq here
byte[] data = dnsq.getData();
int dnsqLength = dnsq.getLength();
final byte[] udpreq = new byte[dnsqLength];
System.arraycopy(data, 0, udpreq, 0, dnsqLength);
// begin to query from dns cache
final String questDomain = getRequestDomain(udpreq);
DNSResponse resp = queryFromCache(questDomain);
if (resp != null) {
sendDns(createDNSResponse(udpreq, parseIPString(resp.getAddress())), dnsq,
srvSocket);
Log.d(TAG, "DNS cache hit: " + questDomain);
} else if (orgCache.containsKey(questDomain)) { // 如果为自定义域名解析
byte[] ips = parseIPString(orgCache.get(questDomain));
byte[] answer = createDNSResponse(udpreq, ips);
addToCache(questDomain, answer);
sendDns(answer, dnsq, srvSocket);
Log.d(TAG, "Custom DNS resolver: " + questDomain);
} else if (questDomain.toLowerCase().contains("appspot.com")) { // 如果为apphost域名解析
byte[] ips = parseIPString(appHost);
byte[] answer = createDNSResponse(udpreq, ips);
addToCache(questDomain, answer);
sendDns(answer, dnsq, srvSocket);
Log.d(TAG, "Custom DNS resolver: " + questDomain);
} else {
synchronized (domains) {
if (domains.contains(questDomain))
continue;
else
domains.add(questDomain);
}
fetchAnswerHTTP(dnsq, udpreq);
}
} catch (SocketException e) {
Log.e(TAG, e.getLocalizedMessage());
break;
} catch (NullPointerException e) {
Log.e(TAG, "Srvsocket wrong", e);
break;
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage());
}
}
}
/**
* send response to the source
*
* @param response
* response
* @param dnsq
* request
* @param srvSocket
* local socket
*/
private void sendDns(byte[] response, DatagramPacket dnsq, DatagramSocket srvSocket) {
// 同步identifier
System.arraycopy(dnsq.getData(), 0, response, 0, 2);
DatagramPacket resp = new DatagramPacket(response, 0, response.length);
resp.setPort(dnsq.getPort());
resp.setAddress(dnsq.getAddress());
try {
srvSocket.send(resp);
} catch (IOException e) {
Log.e(TAG, "", e);
}
}
}
| zyh3290-proxy | src/org/gaeproxy/DNSServer.java | Java | gpl3 | 14,390 |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gaeproxy;
import java.io.FileDescriptor;
/**
* Utility methods for creating and managing a subprocess.
* <p>
* Note: The native methods access a package-private java.io.FileDescriptor
* field to get and set the raw Linux file descriptor. This might break if the
* implementation of java.io.FileDescriptor is changed.
*/
public class Exec {
static {
System.loadLibrary("exec");
}
/**
* Close a given file descriptor.
*/
public static native void close(FileDescriptor fd);
/**
* Create a subprocess. Differs from java.lang.ProcessBuilder in that a pty
* is used to communicate with the subprocess.
* <p>
* Callers are responsible for calling Exec.close() on the returned file
* descriptor.
*
* @param cmd
* The command to execute
* @param args
* An array of arguments to the command
* @param envVars
* An array of strings of the form "VAR=value" to be added to the
* environment of the process
* @param processId
* A one-element array to which the process ID of the started
* process will be written.
* @return the file descriptor of the started process.
*
*/
public static native FileDescriptor createSubprocess(String cmd,
String[] args, String[] envVars, int[] processId);
/**
* Send SIGHUP to a process group.
*/
public static native void hangupProcessGroup(int processId);
/**
* Causes the calling thread to wait for the process associated with the
* receiver to finish executing.
*
* @return The exit value of the Process being waited on
*
*/
public static native int waitFor(int processId);
}
| zyh3290-proxy | src/org/gaeproxy/Exec.java | Java | gpl3 | 2,287 |
/* gaeproxy - GAppProxy / WallProxy client App for Android
* Copyright (C) 2011 <max.c.lv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ___====-_ _-====___
* _--^^^#####// \\#####^^^--_
* _-^##########// ( ) \\##########^-_
* -############// |\^^/| \\############-
* _/############// (@::@) \\############\_
* /#############(( \\// ))#############\
* -###############\\ (oo) //###############-
* -#################\\ / VV \ //#################-
* -###################\\/ \//###################-
* _#/|##########/\######( /\ )######/\##########|\#_
* |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
* ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
* ` ` ` ` / | | | | \ ' ' ' '
* ( | | | | )
* __\ | | | | /__
* (vvv(VVV)(VVV)vvv)
*
* HERE BE DRAGONS
*
*/
package org.gaeproxy;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import org.gaeproxy.db.DNSResponse;
import org.gaeproxy.db.DatabaseHelper;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;
import com.google.analytics.tracking.android.EasyTracker;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
public class GAEProxyService extends Service {
private Notification notification;
private NotificationManager notificationManager;
private Intent intent;
private PendingIntent pendIntent;
private PowerManager.WakeLock mWakeLock;
public static final String BASE = "/data/data/org.gaeproxy/";
private static final int MSG_CONNECT_START = 0;
private static final int MSG_CONNECT_FINISH = 1;
private static final int MSG_CONNECT_SUCCESS = 2;
private static final int MSG_CONNECT_FAIL = 3;
private static final int MSG_HOST_CHANGE = 4;
private static final int MSG_STOP_SELF = 5;
final static String CMD_IPTABLES_RETURN = " -t nat -A OUTPUT -p tcp -d 0.0.0.0 -j RETURN\n";
final static String CMD_IPTABLES_REDIRECT_ADD_HTTP = " -t nat -A OUTPUT -p tcp "
+ "--dport 80 -j REDIRECT --to 8123\n";
final static String CMD_IPTABLES_REDIRECT_ADD_HTTPS = " -t nat -A OUTPUT -p tcp "
+ "--dport 443 -j REDIRECT --to 8124\n";
final static String CMD_IPTABLES_DNAT_ADD_HTTP = " -t nat -A OUTPUT -p tcp "
+ "--dport 80 -j DNAT --to-destination 127.0.0.1:8123\n";
final static String CMD_IPTABLES_DNAT_ADD_HTTPS = " -t nat -A OUTPUT -p tcp "
+ "--dport 443 -j DNAT --to-destination 127.0.0.1:8124\n";
private static final String TAG = "GAEProxyService";
public static volatile boolean statusLock = false;
private Process httpProcess = null;
private DataOutputStream httpOS = null;
private String proxy;
private String appHost = "203.208.46.1";
private String appMask = "203.208.0.0";
private int port;
private String sitekey;
private String proxyType = "GoAgent";
private DNSServer dnsServer = null;
private int dnsPort = 8153;
private SharedPreferences settings = null;
private boolean hasRedirectSupport = true;
private boolean isGlobalProxy = false;
private boolean isHTTPSProxy = false;
private boolean isDNSBlocked = true;
private boolean isGFWList = false;
private ProxyedApp apps[];
private static final Class<?>[] mStartForegroundSignature = new Class[] { int.class,
Notification.class };
private static final Class<?>[] mStopForegroundSignature = new Class[] { boolean.class };
private static final Class<?>[] mSetForegroundSignature = new Class[] { boolean.class };
private Method mSetForeground;
private Method mStartForeground;
private Method mStopForeground;
private Object[] mSetForegroundArgs = new Object[1];
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];
/*
* This is a hack see
* http://www.mail-archive.com/android-developers@googlegroups
* .com/msg18298.html we are not really able to decide if the service was
* started. So we remember a week reference to it. We set it if we are
* running and clear it if we are stopped. If anything goes wrong, the
* reference will hopefully vanish
*/
private static WeakReference<GAEProxyService> sRunningInstance = null;
public final static boolean isServiceStarted() {
final boolean isServiceStarted;
if (sRunningInstance == null) {
isServiceStarted = false;
} else if (sRunningInstance.get() == null) {
isServiceStarted = false;
sRunningInstance = null;
} else {
isServiceStarted = true;
}
return isServiceStarted;
}
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Editor ed = settings.edit();
switch (msg.what) {
case MSG_CONNECT_START:
ed.putBoolean("isConnecting", true);
statusLock = true;
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
| PowerManager.ON_AFTER_RELEASE, "GAEProxy");
mWakeLock.acquire();
break;
case MSG_CONNECT_FINISH:
ed.putBoolean("isConnecting", false);
statusLock = false;
if (mWakeLock != null && mWakeLock.isHeld())
mWakeLock.release();
break;
case MSG_CONNECT_SUCCESS:
ed.putBoolean("isRunning", true);
break;
case MSG_CONNECT_FAIL:
ed.putBoolean("isRunning", false);
break;
case MSG_HOST_CHANGE:
ed.putString("appHost", appHost);
break;
case MSG_STOP_SELF:
stopSelf();
break;
}
ed.commit();
super.handleMessage(msg);
}
};
public boolean connect() {
try {
StringBuffer sb = new StringBuffer();
if (isDNSBlocked)
sb.append(BASE + "localproxy.sh \"" + Utils.getDataPath(this) + "\"");
else
sb.append(BASE + "localproxy_en.sh \"" + Utils.getDataPath(this) + "\"");
if (proxyType.equals("GAppProxy")) {
File conf = new File(BASE + "proxy.conf");
if (!conf.exists())
conf.createNewFile();
FileOutputStream is = new FileOutputStream(conf);
byte[] buffer = ("listen_port = " + port + "\n" + "fetch_server = " + proxy + "\n")
.getBytes();
is.write(buffer);
is.flush();
is.close();
sb.append(" gappproxy");
} else if (proxyType.equals("WallProxy")) {
sb.append(" wallproxy " + proxy + " " + port + " " + appHost + " " + sitekey);
} else if (proxyType.equals("GoAgent")) {
String[] proxyString = proxy.split("\\/");
if (proxyString.length < 4)
return false;
String[] appid = proxyString[2].split("\\.");
if (appid.length < 3)
return false;
sb.append(" goagent " + appid[0] + " " + port + " " + appHost + " "
+ proxyString[3] + " " + sitekey);
}
final String cmd = sb.toString();
Log.e(TAG, cmd);
if (Utils.isRoot()) {
Utils.runRootCommand(cmd);
} else {
Utils.runCommand(cmd);
}
} catch (Exception e) {
Log.e(TAG, "Cannot connect");
return false;
}
return true;
}
private String getVersionName() {
String version;
try {
PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
version = pi.versionName;
} catch (PackageManager.NameNotFoundException e) {
version = "Package name not found";
}
return version;
}
public void handleCommand(Intent intent) {
Log.d(TAG, "Service Start");
if (intent == null) {
stopSelf();
return;
}
Bundle bundle = intent.getExtras();
if (bundle == null) {
stopSelf();
return;
}
proxy = bundle.getString("proxy");
proxyType = bundle.getString("proxyType");
port = bundle.getInt("port");
sitekey = bundle.getString("sitekey");
isGlobalProxy = bundle.getBoolean("isGlobalProxy");
isHTTPSProxy = bundle.getBoolean("isHTTPSProxy");
isGFWList = bundle.getBoolean("isGFWList");
Log.e(TAG, "GAE Proxy: " + proxy);
Log.e(TAG, "Local Port: " + port);
// APNManager.setAPNProxy("127.0.0.1", Integer.toString(port), this);
new Thread(new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(MSG_CONNECT_START);
try {
URL url = new URL("http://gae-ip-country.appspot.com/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(8000);
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader input = new BufferedReader(new InputStreamReader(is));
String code = input.readLine();
if (code != null && code.length() > 0 && code.length() < 5) {
Log.d(TAG, "Location: " + code);
if (!code.contains("CN") && !code.contains("ZZ"))
isDNSBlocked = false;
}
} catch (Exception e) {
isDNSBlocked = true;
Log.d(TAG, "Cannot get country info", e);
// Nothing
}
Log.d(TAG, "IPTABLES: " + Utils.getIptables());
// Test for Redirect Support
hasRedirectSupport = Utils.getHasRedirectSupport();
if (handleConnection()) {
// Connection and forward successful
notifyAlert(getString(R.string.forward_success),
getString(R.string.service_running));
handler.sendEmptyMessageDelayed(MSG_CONNECT_SUCCESS, 500);
// for widget, maybe exception here
try {
RemoteViews views = new RemoteViews(getPackageName(),
R.layout.gaeproxy_appwidget);
views.setImageViewResource(R.id.serviceToggle, R.drawable.on);
AppWidgetManager awm = AppWidgetManager.getInstance(GAEProxyService.this);
awm.updateAppWidget(awm.getAppWidgetIds(new ComponentName(
GAEProxyService.this, GAEProxyWidgetProvider.class)), views);
} catch (Exception ignore) {
// Nothing
}
} else {
// Connection or forward unsuccessful
notifyAlert(getString(R.string.forward_fail),
getString(R.string.service_failed));
stopSelf();
handler.sendEmptyMessageDelayed(MSG_CONNECT_FAIL, 500);
}
handler.sendEmptyMessageDelayed(MSG_CONNECT_FINISH, 500);
}
}).start();
markServiceStarted();
}
/** Called when the activity is first created. */
public boolean handleConnection() {
if (isDNSBlocked) {
try {
InetAddress addr = InetAddress.getByName("www.google.cn");
appHost = addr.getHostAddress();
} catch (Exception ignore) {
// Nothing
}
if (appHost == null || !appHost.startsWith("203.208")) {
appHost = settings.getString("appHost", "203.208.46.1");
try {
URL aURL = new URL("http://myhosts.sinaapp.com/apphost");
HttpURLConnection conn = (HttpURLConnection) aURL.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setReadTimeout(10 * 1000);
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
if (line == null)
return false;
if (!line.startsWith("#GAEPROXY"))
return false;
while (true) {
line = reader.readLine();
if (line == null)
break;
if (line.startsWith("#"))
continue;
line = line.trim().toLowerCase();
if (line.equals(""))
continue;
if (!line.equals(appHost)) {
try {
DatabaseHelper helper = OpenHelperManager.getHelper(this,
DatabaseHelper.class);
Dao<DNSResponse, String> dnsCacheDao = helper.getDNSCacheDao();
List<DNSResponse> list = dnsCacheDao.queryForAll();
for (DNSResponse resp : list) {
dnsCacheDao.delete(resp);
}
} catch (Exception ignore) {
// Nothing
}
appHost = line;
handler.sendEmptyMessage(MSG_HOST_CHANGE);
}
break;
}
} catch (Exception e) {
Log.e(TAG, "cannot get remote host files", e);
}
}
} else {
try {
InetAddress addr = InetAddress.getByName("www.google.com");
appHost = addr.getHostAddress();
} catch (Exception ignore) {
return false;
}
}
try {
if (appHost.length() > 8) {
String[] ips = appHost.split("\\.");
if (ips.length == 4)
appMask = ips[0] + "." + ips[1] + ".0.0";
Log.d(TAG, appMask);
}
} catch (Exception ignore) {
return false;
}
// DNS Proxy Setup
// with AsyncHttpClient
dnsServer = new DNSServer(this, appHost);
dnsPort = dnsServer.getServPort();
// Random mirror for load balance
// only affect when appid equals proxyofmax
if (proxy.equals("https://proxyofmax.appspot.com/fetch.py")) {
proxyType = "GoAgent";
String[] mirror_list = null;
int mirror_num = 0;
try {
String mirror_string = new String(Base64.decode(getString(R.string.mirror_list)));
mirror_list = mirror_string.split("\\|");
} catch (IOException e) {
}
if (mirror_list != null) {
mirror_num = mirror_list.length;
Random random = new Random(System.currentTimeMillis());
int n = random.nextInt(mirror_num);
proxy = "https://" + mirror_list[n] + ".appspot.com/fetch.py";
Log.d(TAG, "Balance Proxy: " + proxy);
}
}
if (!preConnection())
return false;
Thread dnsThread = new Thread(dnsServer);
dnsThread.setDaemon(true);
dnsThread.start();
connect();
return true;
}
private void initSoundVibrateLights(Notification notification) {
final String ringtone = settings.getString("settings_key_notif_ringtone", null);
AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_RING) == 0) {
notification.sound = null;
} else if (ringtone != null)
notification.sound = Uri.parse(ringtone);
else
notification.defaults |= Notification.DEFAULT_SOUND;
if (settings.getBoolean("settings_key_notif_vibrate", false)) {
long[] vibrate = { 0, 500 };
notification.vibrate = vibrate;
}
notification.defaults |= Notification.DEFAULT_LIGHTS;
}
void invokeMethod(Method method, Object[] args) {
try {
method.invoke(this, mStartForegroundArgs);
} catch (InvocationTargetException e) {
// Should not happen.
Log.w(TAG, "Unable to invoke method", e);
} catch (IllegalAccessException e) {
// Should not happen.
Log.w(TAG, "Unable to invoke method", e);
}
}
private void markServiceStarted() {
sRunningInstance = new WeakReference<GAEProxyService>(this);
}
private void markServiceStopped() {
sRunningInstance = null;
}
private void notifyAlert(String title, String info) {
notification.icon = R.drawable.ic_stat_gaeproxy;
notification.tickerText = title;
notification.flags = Notification.FLAG_ONGOING_EVENT;
initSoundVibrateLights(notification);
// notification.defaults = Notification.DEFAULT_SOUND;
notification.setLatestEventInfo(this, getString(R.string.app_name), info, pendIntent);
startForegroundCompat(1, notification);
}
private void notifyAlert(String title, String info, int flags) {
notification.icon = R.drawable.ic_stat_gaeproxy;
notification.tickerText = title;
notification.flags = flags;
initSoundVibrateLights(notification);
notification.setLatestEventInfo(this, getString(R.string.app_name), info, pendIntent);
notificationManager.notify(0, notification);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
EasyTracker.getTracker().trackEvent("service", "start", getVersionName(), 0L);
settings = PreferenceManager.getDefaultSharedPreferences(this);
notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
intent = new Intent(this, GAEProxy.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification = new Notification();
try {
mStartForeground = getClass().getMethod("startForeground", mStartForegroundSignature);
mStopForeground = getClass().getMethod("stopForeground", mStopForegroundSignature);
} catch (NoSuchMethodException e) {
// Running on an older platform.
mStartForeground = mStopForeground = null;
}
try {
mSetForeground = getClass().getMethod("setForeground", mSetForegroundSignature);
} catch (NoSuchMethodException e) {
throw new IllegalStateException(
"OS doesn't have Service.startForeground OR Service.setForeground!");
}
}
/** Called when the activity is closed. */
@Override
public void onDestroy() {
EasyTracker.getTracker().trackEvent("service", "stop", getVersionName(), 0L);
statusLock = true;
stopForegroundCompat(1);
notifyAlert(getString(R.string.forward_stop), getString(R.string.service_stopped),
Notification.FLAG_AUTO_CANCEL);
try {
if (httpOS != null) {
httpOS.close();
httpOS = null;
}
if (httpProcess != null) {
httpProcess.destroy();
httpProcess = null;
}
} catch (Exception e) {
Log.e(TAG, "HTTP Server close unexpected");
}
try {
if (dnsServer != null)
dnsServer.close();
} catch (Exception e) {
Log.e(TAG, "DNS Server close unexpected");
}
new Thread() {
@Override
public void run() {
// Make sure the connection is closed, important here
onDisconnect();
}
}.start();
// for widget, maybe exception here
try {
RemoteViews views = new RemoteViews(getPackageName(), R.layout.gaeproxy_appwidget);
views.setImageViewResource(R.id.serviceToggle, R.drawable.off);
AppWidgetManager awm = AppWidgetManager.getInstance(this);
awm.updateAppWidget(
awm.getAppWidgetIds(new ComponentName(this, GAEProxyWidgetProvider.class)),
views);
} catch (Exception ignore) {
// Nothing
}
Editor ed = settings.edit();
ed.putBoolean("isRunning", false);
ed.putBoolean("isConnecting", false);
ed.commit();
try {
notificationManager.cancel(0);
} catch (Exception ignore) {
// Nothing
}
try {
ProxySettings.resetProxy(this);
} catch (Exception ignore) {
// Nothing
}
// APNManager.clearAPNProxy("127.0.0.1", Integer.toString(port), this);
super.onDestroy();
statusLock = false;
markServiceStopped();
}
private void onDisconnect() {
Utils.runRootCommand(Utils.getIptables() + " -t nat -F OUTPUT");
if (Utils.isRoot())
Utils.runRootCommand(BASE + "proxy.sh stop");
else
Utils.runCommand(BASE + "proxy.sh stop");
}
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
handleCommand(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
/**
* Internal method to request actual PTY terminal once we've finished
* authentication. If called before authenticated, it will just fail.
*/
private boolean preConnection() {
if (isHTTPSProxy) {
InputStream is = null;
String socksIp = settings.getString("socksIp", null);
String socksPort = settings.getString("socksPort", null);
String sig = Utils.getSignature(this);
if (sig == null)
return false;
for (int tries = 0; tries < 2; tries++) {
try {
URL aURL = new URL("http://myhosts.sinaapp.com/port3.php?sig=" + sig);
HttpURLConnection conn = (HttpURLConnection) aURL.openConnection();
conn.setConnectTimeout(4000);
conn.setReadTimeout(8000);
conn.connect();
is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
if (line.startsWith("ERROR"))
return false;
if (!line.startsWith("#ip"))
throw new Exception("Format error");
line = reader.readLine();
socksIp = line.trim().toLowerCase();
line = reader.readLine();
if (!line.startsWith("#port"))
throw new Exception("Format error");
line = reader.readLine();
socksPort = line.trim().toLowerCase();
Editor ed = settings.edit();
ed.putString("socksIp", socksIp);
ed.putString("socksPort", socksPort);
ed.commit();
} catch (Exception e) {
Log.e(TAG, "cannot get remote port info", e);
continue;
}
break;
}
if (socksIp == null || socksPort == null)
return false;
Log.d(TAG, "Forward Successful");
if (Utils.isRoot())
Utils.runRootCommand(BASE + "proxy.sh start " + port + " " + socksIp + " "
+ socksPort);
else
Utils.runCommand(BASE + "proxy.sh start " + port + " " + socksIp + " " + socksPort);
} else {
Log.d(TAG, "Forward Successful");
if (Utils.isRoot())
Utils.runRootCommand(BASE + "proxy.sh start " + port + " " + "127.0.0.1" + " "
+ port);
else
Utils.runCommand(BASE + "proxy.sh start " + port + " " + "127.0.0.1" + " " + port);
}
StringBuffer init_sb = new StringBuffer();
StringBuffer http_sb = new StringBuffer();
StringBuffer https_sb = new StringBuffer();
init_sb.append(Utils.getIptables() + " -t nat -F OUTPUT\n");
if (hasRedirectSupport) {
init_sb.append(Utils.getIptables()
+ " -t nat -A OUTPUT -p udp --dport 53 -j REDIRECT --to " + dnsPort + "\n");
} else {
init_sb.append(Utils.getIptables()
+ " -t nat -A OUTPUT -p udp --dport 53 -j DNAT --to-destination 127.0.0.1:"
+ dnsPort + "\n");
}
String cmd_bypass = Utils.getIptables() + CMD_IPTABLES_RETURN;
init_sb.append(cmd_bypass.replace("0.0.0.0", appMask + "/16"));
init_sb.append(cmd_bypass.replace("-d 0.0.0.0", "-m owner --uid-owner "
+ getApplicationInfo().uid));
if (isGFWList) {
String[] chn_list = getResources().getStringArray(R.array.chn_list);
for (String item : chn_list) {
init_sb.append(cmd_bypass.replace("0.0.0.0", item));
}
}
if (isGlobalProxy) {
http_sb.append(hasRedirectSupport ? Utils.getIptables()
+ CMD_IPTABLES_REDIRECT_ADD_HTTP : Utils.getIptables()
+ CMD_IPTABLES_DNAT_ADD_HTTP);
https_sb.append(hasRedirectSupport ? Utils.getIptables()
+ CMD_IPTABLES_REDIRECT_ADD_HTTPS : Utils.getIptables()
+ CMD_IPTABLES_DNAT_ADD_HTTPS);
} else {
// for proxy specified apps
if (apps == null || apps.length <= 0)
apps = AppManager.getProxyedApps(this);
HashSet<Integer> uidSet = new HashSet<Integer>();
for (int i = 0; i < apps.length; i++) {
if (apps[i].isProxyed()) {
uidSet.add(apps[i].getUid());
}
}
for (int uid : uidSet) {
http_sb.append((hasRedirectSupport ? Utils.getIptables()
+ CMD_IPTABLES_REDIRECT_ADD_HTTP : Utils.getIptables()
+ CMD_IPTABLES_DNAT_ADD_HTTP).replace("-t nat",
"-t nat -m owner --uid-owner " + uid));
https_sb.append((hasRedirectSupport ? Utils.getIptables()
+ CMD_IPTABLES_REDIRECT_ADD_HTTPS : Utils.getIptables()
+ CMD_IPTABLES_DNAT_ADD_HTTPS).replace("-t nat",
"-t nat -m owner --uid-owner " + uid));
}
}
String init_rules = init_sb.toString();
Utils.runRootCommand(init_rules, 30 * 1000);
String redt_rules = http_sb.toString();
redt_rules += https_sb.toString();
Utils.runRootCommand(redt_rules);
return true;
}
/**
* This is a wrapper around the new startForeground method, using the older
* APIs if it is not available.
*/
void startForegroundCompat(int id, Notification notification) {
// If we have the new startForeground API, then use it.
if (mStartForeground != null) {
mStartForegroundArgs[0] = Integer.valueOf(id);
mStartForegroundArgs[1] = notification;
invokeMethod(mStartForeground, mStartForegroundArgs);
return;
}
// Fall back on the old API.
mSetForegroundArgs[0] = Boolean.TRUE;
invokeMethod(mSetForeground, mSetForegroundArgs);
notificationManager.notify(id, notification);
}
/**
* This is a wrapper around the new stopForeground method, using the older
* APIs if it is not available.
*/
void stopForegroundCompat(int id) {
// If we have the new stopForeground API, then use it.
if (mStopForeground != null) {
mStopForegroundArgs[0] = Boolean.TRUE;
try {
mStopForeground.invoke(this, mStopForegroundArgs);
} catch (InvocationTargetException e) {
// Should not happen.
Log.w(TAG, "Unable to invoke stopForeground", e);
} catch (IllegalAccessException e) {
// Should not happen.
Log.w(TAG, "Unable to invoke stopForeground", e);
}
return;
}
// Fall back on the old API. Note to cancel BEFORE changing the
// foreground state, since we could be killed at that point.
notificationManager.cancel(id);
mSetForegroundArgs[0] = Boolean.FALSE;
invokeMethod(mSetForeground, mSetForegroundArgs);
}
}
| zyh3290-proxy | src/org/gaeproxy/GAEProxyService.java | Java | gpl3 | 26,577 |
package org.gaeproxy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Stack;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.widget.ImageView;
public class ImageLoader {
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
ImageView imageView;
public BitmapDisplayer(Bitmap b, ImageView i) {
bitmap = b;
imageView = i;
}
@Override
public void run() {
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else
imageView.setImageResource(stub_id);
}
}
class PhotosLoader extends Thread {
@Override
public void run() {
try {
while (true) {
// thread waits until there are any images to load in the
// queue
if (photosQueue.photosToLoad.size() == 0)
synchronized (photosQueue.photosToLoad) {
photosQueue.photosToLoad.wait();
}
if (photosQueue.photosToLoad.size() != 0) {
PhotoToLoad photoToLoad;
synchronized (photosQueue.photosToLoad) {
photoToLoad = photosQueue.photosToLoad.pop();
}
Bitmap bmp = getBitmap(photoToLoad.uid);
cache.put(photoToLoad.uid, bmp);
Object tag = photoToLoad.imageView.getTag();
if (tag != null && ((Integer) tag) == photoToLoad.uid) {
BitmapDisplayer bd = new BitmapDisplayer(bmp,
photoToLoad.imageView);
Activity a = (Activity) photoToLoad.imageView
.getContext();
a.runOnUiThread(bd);
}
}
if (Thread.interrupted())
break;
}
} catch (InterruptedException e) {
// allow thread to exit
}
}
}
// stores list of photos to download
class PhotosQueue {
private Stack<PhotoToLoad> photosToLoad = new Stack<PhotoToLoad>();
// removes all instances of this ImageView
public void Clean(ImageView image) {
for (int j = 0; j < photosToLoad.size();) {
if (photosToLoad.get(j).imageView == image)
photosToLoad.remove(j);
else
++j;
}
}
}
// Task for the queue
private class PhotoToLoad {
public int uid;
public ImageView imageView;
public PhotoToLoad(int u, ImageView i) {
uid = u;
imageView = i;
}
}
// the simplest in-memory cache implementation. This should be replaced with
// something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
private HashMap<Integer, Bitmap> cache = new HashMap<Integer, Bitmap>();
private File cacheDir;
private Context context;
final int stub_id = R.drawable.sym_def_app_icon;
PhotosQueue photosQueue = new PhotosQueue();
PhotosLoader photoLoaderThread = new PhotosLoader();
public ImageLoader(Context c) {
// Make the background thead low priority. This way it will not affect
// the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);
context = c;
// Find the dir to save cached images
cacheDir = context.getCacheDir();
}
public void clearCache() {
// clear memory cache
cache.clear();
// clear SD cache
File[] files = cacheDir.listFiles();
for (File f : files)
f.delete();
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
public void DisplayImage(int uid, Activity activity, ImageView imageView) {
if (cache.containsKey(uid))
imageView.setImageBitmap(cache.get(uid));
else {
queuePhoto(uid, activity, imageView);
imageView.setImageResource(stub_id);
}
}
private Bitmap getBitmap(int uid) {
// I identify images by hashcode. Not a perfect solution, good for the
// demo.
String filename = String.valueOf(uid);
File f = new File(cacheDir, filename);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
BitmapDrawable icon = (BitmapDrawable) Utils.getAppIcon(context,
uid);
return icon.getBitmap();
} catch (Exception ex) {
return null;
}
}
private void queuePhoto(int uid, Activity activity, ImageView imageView) {
// This ImageView may be used for other images before. So there may be
// some old tasks in the queue. We need to discard them.
photosQueue.Clean(imageView);
PhotoToLoad p = new PhotoToLoad(uid, imageView);
synchronized (photosQueue.photosToLoad) {
photosQueue.photosToLoad.push(p);
photosQueue.photosToLoad.notifyAll();
}
// start thread if it's not started yet
if (photoLoaderThread.getState() == Thread.State.NEW)
photoLoaderThread.start();
}
public void stopThread() {
photoLoaderThread.interrupt();
}
}
| zyh3290-proxy | src/org/gaeproxy/ImageLoader.java | Java | gpl3 | 5,686 |
/* gaeproxy - GAppProxy / WallProxy client App for Android
* Copyright (C) 2011 <max.c.lv@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* ___====-_ _-====___
* _--^^^#####// \\#####^^^--_
* _-^##########// ( ) \\##########^-_
* -############// |\^^/| \\############-
* _/############// (@::@) \\############\_
* /#############(( \\// ))#############\
* -###############\\ (oo) //###############-
* -#################\\ / VV \ //#################-
* -###################\\/ \//###################-
* _#/|##########/\######( /\ )######/\##########|\#_
* |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \|
* ` |/ V V ` V \#\| | | |/#/ V ' V V \| '
* ` ` ` ` / | | | | \ ' ' ' '
* ( | | | | )
* __\ | | | | /__
* (vvv(VVV)(VVV)vvv)
*
* HERE BE DRAGONS
*
*/
package org.gaeproxy;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
public class GAEProxyWidgetProvider extends AppWidgetProvider {
public static final String PROXY_SWITCH_ACTION = "org.gaeproxy.GAEProxyWidgetProvider.PROXY_SWITCH_ACTION";
public static final String SERVICE_NAME = "org.gaeproxy.GAEProxyService";
public static final String TAG = "GAEProxyWidgetProvider";
private String proxy;
private String proxyType;
private int port;
private String sitekey;
private boolean isGlobalProxy;
private boolean isHTTPSProxy;
private boolean isGFWList;
@Override
public synchronized void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(PROXY_SWITCH_ACTION)) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
if (GAEProxyService.statusLock) {
// only one request a time
return;
}
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 10 milliseconds
v.vibrate(10);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.gaeproxy_appwidget);
try {
views.setImageViewResource(R.id.serviceToggle, R.drawable.ing);
AppWidgetManager awm = AppWidgetManager.getInstance(context);
awm.updateAppWidget(awm.getAppWidgetIds(new ComponentName(context,
GAEProxyWidgetProvider.class)), views);
} catch (Exception ignore) {
// Nothing
}
Log.d(TAG, "Proxy switch action");
// do some really cool stuff here
if (GAEProxyService.isServiceStarted()) {
// Service is working, so stop it
try {
context.stopService(new Intent(context, GAEProxyService.class));
} catch (Exception e) {
// Nothing
}
} else {
// Service is not working, then start it
String versionName;
try {
versionName = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
versionName = "NONE";
}
boolean isInstalled = settings.getBoolean(versionName, false);
if (isInstalled) {
Toast.makeText(context, context.getString(R.string.toast_start),
Toast.LENGTH_LONG).show();
proxy = settings.getString("proxy", "");
proxyType = settings.getString("proxyType", "GoAgent");
String portText = settings.getString("port", "");
if (portText != null && portText.length() > 0) {
port = Integer.valueOf(portText);
if (port <= 1024)
port = 1984;
} else {
port = 1984;
}
sitekey = settings.getString("sitekey", "");
isGlobalProxy = settings.getBoolean("isGlobalProxy", false);
isHTTPSProxy = settings.getBoolean("isHTTPSProxy", false);
isGFWList = settings.getBoolean("isGFWList", false);
Intent it = new Intent(context, GAEProxyService.class);
Bundle bundle = new Bundle();
bundle.putString("proxy", proxy);
bundle.putInt("port", port);
bundle.putString("proxyType", proxyType);
bundle.putString("sitekey", sitekey);
bundle.putBoolean("isGlobalProxy", isGlobalProxy);
bundle.putBoolean("isHTTPSProxy", isHTTPSProxy);
bundle.putBoolean("isGFWList", isGFWList);
it.putExtras(bundle);
context.startService(it);
} else {
try {
Thread.sleep(500);
} catch (InterruptedException ignore) {
// Nothing
}
try {
views.setImageViewResource(R.id.serviceToggle, R.drawable.off);
AppWidgetManager awm = AppWidgetManager.getInstance(context);
awm.updateAppWidget(awm.getAppWidgetIds(new ComponentName(context,
GAEProxyWidgetProvider.class)), views);
} catch (Exception ignore) {
// Nothing
}
}
}
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final int N = appWidgetIds.length;
// Perform this loop procedure for each App Widget that belongs to this
// provider
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
// Create an Intent to launch ExampleActivity
Intent intent = new Intent(context, GAEProxyWidgetProvider.class);
intent.setAction(PROXY_SWITCH_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// Get the layout for the App Widget and attach an on-click listener
// to the button
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.gaeproxy_appwidget);
views.setOnClickPendingIntent(R.id.serviceToggle, pendingIntent);
if (GAEProxyService.isServiceStarted()) {
views.setImageViewResource(R.id.serviceToggle, R.drawable.on);
Log.d(TAG, "Service running");
} else {
views.setImageViewResource(R.id.serviceToggle, R.drawable.off);
Log.d(TAG, "Service stopped");
}
// Tell the AppWidgetManager to perform an update on the current App
// Widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
| zyh3290-proxy | src/org/gaeproxy/GAEProxyWidgetProvider.java | Java | gpl3 | 7,500 |
package org.gaeproxy;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;
public class Utils {
/**
* Internal thread used to execute scripts (as root or not).
*/
private static final class ScriptRunner extends Thread {
private final File file;
private final String script;
private final StringBuilder res;
private final boolean asroot;
public int exitcode = -1;
// private Process exec;
private int mProcId;
private FileDescriptor mTermFd;
/**
* Creates a new script runner.
*
* @param file
* temporary script file
* @param script
* script to run
* @param res
* response output
* @param asroot
* if true, executes the script as root
*/
public ScriptRunner(File file, String script, StringBuilder res,
boolean asroot) {
this.file = file;
this.script = script;
this.res = res;
this.asroot = asroot;
}
private int createSubprocess(int[] processId, String cmd) {
ArrayList<String> argList = parse(cmd);
String arg0 = argList.get(0);
String[] args = argList.toArray(new String[1]);
mTermFd = Exec.createSubprocess(arg0, args, null, processId);
return processId[0];
}
/**
* Destroy this script runner
*/
@Override
public synchronized void destroy() {
try {
Exec.hangupProcessGroup(mProcId);
Exec.close(mTermFd);
} catch (NoClassDefFoundError ignore) {
// Nothing
}
}
private ArrayList<String> parse(String cmd) {
final int PLAIN = 0;
final int WHITESPACE = 1;
final int INQUOTE = 2;
int state = WHITESPACE;
ArrayList<String> result = new ArrayList<String>();
int cmdLen = cmd.length();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < cmdLen; i++) {
char c = cmd.charAt(i);
if (state == PLAIN) {
if (Character.isWhitespace(c)) {
result.add(builder.toString());
builder.delete(0, builder.length());
state = WHITESPACE;
} else if (c == '"') {
state = INQUOTE;
} else {
builder.append(c);
}
} else if (state == WHITESPACE) {
if (Character.isWhitespace(c)) {
// do nothing
} else if (c == '"') {
state = INQUOTE;
} else {
state = PLAIN;
builder.append(c);
}
} else if (state == INQUOTE) {
if (c == '\\') {
if (i + 1 < cmdLen) {
i += 1;
builder.append(cmd.charAt(i));
}
} else if (c == '"') {
state = PLAIN;
} else {
builder.append(c);
}
}
}
if (builder.length() > 0) {
result.add(builder.toString());
}
return result;
}
@Override
public void run() {
try {
new File(DEFOUT_FILE).createNewFile();
file.createNewFile();
final String abspath = file.getAbsolutePath();
// TODO: Rewrite this line
// make sure we have execution permission on the script file
// Runtime.getRuntime().exec("chmod 755 " + abspath).waitFor();
// Write the script to be executed
final OutputStreamWriter out = new OutputStreamWriter(
new FileOutputStream(file));
out.write("#!/system/bin/sh\n");
out.write(script);
if (!script.endsWith("\n"))
out.write("\n");
out.write("exit\n");
out.flush();
out.close();
if (this.asroot) {
// Create the "su" request to run the script
// exec = Runtime.getRuntime().exec(
// root_shell + " -c " + abspath);
int pid[] = new int[1];
mProcId = createSubprocess(pid, root_shell + " -c "
+ abspath);
} else {
// Create the "sh" request to run the script
// exec = Runtime.getRuntime().exec(getShell() + " " +
// abspath);
int pid[] = new int[1];
mProcId = createSubprocess(pid, getShell() + " " + abspath);
}
final InputStream stdout = new FileInputStream(DEFOUT_FILE);
final byte buf[] = new byte[8192];
int read = 0;
exitcode = Exec.waitFor(mProcId);
// Read stdout
while (stdout.available() > 0) {
read = stdout.read(buf);
if (res != null)
res.append(new String(buf, 0, read));
}
} catch (Exception ex) {
if (res != null)
res.append("\n" + ex);
} finally {
destroy();
}
}
}
public final static String TAG = "GAEProxy";
public final static String DEFAULT_SHELL = "/system/bin/sh";
public final static String DEFAULT_ROOT = "/system/bin/su";
public final static String ALTERNATIVE_ROOT = "/system/xbin/su";
public final static String DEFAULT_IPTABLES = "/data/data/org.gaeproxy/iptables";
public final static String ALTERNATIVE_IPTABLES = "/system/bin/iptables";
public final static String SCRIPT_FILE = "/data/data/org.gaeproxy/script";
public final static String DEFOUT_FILE = "/data/data/org.gaeproxy/defout";
public final static int TIME_OUT = -99;
private static boolean initialized = false;
private static int hasRedirectSupport = -1;
private static int isRoot = -1;
private static String shell = null;
private static String root_shell = null;
private static String iptables = null;
private static String data_path = null;
private static void checkIptables() {
if (!isRoot()) {
iptables = DEFAULT_IPTABLES;
return;
}
// Check iptables binary
iptables = DEFAULT_IPTABLES;
String lines = null;
boolean compatible = false;
boolean version = false;
StringBuilder sb = new StringBuilder();
String command = iptables + " --version\n" + iptables
+ " -L -t nat -n\n" + "exit\n";
int exitcode = runScript(command, sb, 10 * 1000, true);
if (exitcode == TIME_OUT)
return;
lines = sb.toString();
if (lines.contains("OUTPUT")) {
compatible = true;
}
if (lines.contains("v1.4.")) {
version = true;
}
if (!compatible || !version) {
iptables = ALTERNATIVE_IPTABLES;
if (!new File(iptables).exists())
iptables = "iptables";
}
}
public static Drawable getAppIcon(Context c, int uid) {
PackageManager pm = c.getPackageManager();
Drawable appIcon = c.getResources().getDrawable(
R.drawable.sym_def_app_icon);
String[] packages = pm.getPackagesForUid(uid);
if (packages != null) {
if (packages.length == 1) {
try {
ApplicationInfo appInfo = pm.getApplicationInfo(
packages[0], 0);
appIcon = pm.getApplicationIcon(appInfo);
} catch (NameNotFoundException e) {
Log.e(c.getPackageName(),
"No package found matching with the uid " + uid);
}
}
} else {
Log.e(c.getPackageName(), "Package not found for uid " + uid);
}
return appIcon;
}
public static String getDataPath(Context ctx) {
if (data_path == null) {
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
data_path = Environment.getExternalStorageDirectory()
.getAbsolutePath();
} else {
data_path = ctx.getFilesDir().getAbsolutePath();
}
Log.d(TAG, "Python Data Path: " + data_path);
}
return data_path;
}
public static boolean getHasRedirectSupport() {
if (hasRedirectSupport == -1)
initHasRedirectSupported();
return hasRedirectSupport == 1 ? true : false;
}
public static String getIptables() {
if (iptables == null)
checkIptables();
return iptables;
}
private static String getShell() {
if (shell == null) {
shell = DEFAULT_SHELL;
if (!new File(shell).exists())
shell = "sh";
}
return shell;
}
public static String getSignature(Context ctx) {
Signature sig = null;
try {
Signature[] sigs;
sigs = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(),
PackageManager.GET_SIGNATURES).signatures;
if (sigs != null && sigs.length > 0)
sig = sigs[0];
} catch (Exception ignore) {
// Nothing
}
if (sig == null)
return null;
return sig.toCharsString().substring(11, 256);
}
public static void initHasRedirectSupported() {
if (!Utils.isRoot())
return;
StringBuilder sb = new StringBuilder();
String command = Utils.getIptables()
+ " -t nat -A OUTPUT -p udp --dport 54 -j REDIRECT --to 8154";
int exitcode = runScript(command, sb, 10 * 1000, true);
String lines = sb.toString();
hasRedirectSupport = 1;
// flush the check command
Utils.runRootCommand(command.replace("-A", "-D"));
if (exitcode == TIME_OUT)
return;
if (lines.contains("No chain/target/match")) {
hasRedirectSupport = 0;
}
}
public static boolean isInitialized() {
if (initialized)
return true;
else {
initialized = true;
return false;
}
}
public static boolean isRoot() {
if (isRoot != -1)
return isRoot == 1 ? true : false;
// switch between binaries
if (new File(DEFAULT_ROOT).exists()) {
root_shell = DEFAULT_ROOT;
} else if (new File(ALTERNATIVE_ROOT).exists()) {
root_shell = ALTERNATIVE_ROOT;
} else {
root_shell = "su";
}
String lines = null;
StringBuilder sb = new StringBuilder();
String command = "ls /\n" + "exit\n";
int exitcode = runScript(command, sb, 10 * 1000, true);
if (exitcode == TIME_OUT) {
return false;
}
lines = sb.toString();
if (lines.contains("system")) {
isRoot = 1;
}
return isRoot == 1 ? true : false;
}
public static boolean runCommand(String command) {
return runCommand(command, 10 * 1000);
}
public static boolean runCommand(String command, int timeout) {
Log.d(TAG, command);
runScript(command, null, timeout, false);
return true;
}
public static boolean runRootCommand(String command) {
return runRootCommand(command, 10 * 1000);
}
public static boolean runRootCommand(String command, int timeout) {
if (!isRoot())
return false;
Log.d(TAG, command);
runScript(command, null, timeout, true);
return true;
}
private synchronized static int runScript(String script, StringBuilder res,
long timeout, boolean asroot) {
final File file = new File(SCRIPT_FILE);
final ScriptRunner runner = new ScriptRunner(file, script, res, asroot);
runner.start();
try {
if (timeout > 0) {
runner.join(timeout);
} else {
runner.join();
}
if (runner.isAlive()) {
// Timed-out
runner.destroy();
runner.join(1000);
return TIME_OUT;
}
} catch (InterruptedException ex) {
return TIME_OUT;
}
return runner.exitcode;
}
}
| zyh3290-proxy | src/org/gaeproxy/Utils.java | Java | gpl3 | 11,149 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gaeproxy;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <b>Regular Expression</b> validation (using JDK 1.4+ regex support).
* <p>
* Construct the validator either for a single regular expression or a set
* (array) of regular expressions. By default validation is <i>case
* sensitive</i> but constructors are provided to allow <i>case in-sensitive</i>
* validation. For example to create a validator which does <i>case
* in-sensitive</i> validation for a set of regular expressions:
*
* <pre>
* String[] regexs = new String[] {...};
* RegexValidator validator = new RegexValidator(regexs, false);
* </pre>
* <p>
* <ul>
* <li>Validate <code>true</code> or <code>false</code>:</li>
* <ul>
* <li><code>boolean valid = validator.isValid(value);</code></li>
* </ul>
* <li>Validate returning an aggregated String of the matched groups:</li>
* <ul>
* <li><code>String result = validator.validate(value);</code></li>
* </ul>
* <li>Validate returning the matched groups:</li>
* <ul>
* <li><code>String[] result = validator.match(value);</code></li>
* </ul>
* </ul>
* <p>
* Cached instances pre-compile and re-use {@link Pattern}(s) - which according
* to the {@link Pattern} API are safe to use in a multi-threaded environment.
*
* @version $Revision$ $Date$
* @since Validator 1.4
*/
public class RegexValidator implements Serializable {
private final Pattern[] patterns;
/**
* Construct a <i>case sensitive</i> validator for a single regular
* expression.
*
* @param regex
* The regular expression this validator will validate against
*/
public RegexValidator(String regex) {
this(regex, true);
}
/**
* Construct a validator for a single regular expression with the specified
* case sensitivity.
*
* @param regex
* The regular expression this validator will validate against
* @param caseSensitive
* when <code>true</code> matching is <i>case sensitive</i>,
* otherwise matching is <i>case in-sensitive</i>
*/
public RegexValidator(String regex, boolean caseSensitive) {
this(new String[] { regex }, caseSensitive);
}
/**
* Construct a <i>case sensitive</i> validator that matches any one of the
* set of regular expressions.
*
* @param regexs
* The set of regular expressions this validator will validate
* against
*/
public RegexValidator(String[] regexs) {
this(regexs, true);
}
/**
* Construct a validator that matches any one of the set of regular
* expressions with the specified case sensitivity.
*
* @param regexs
* The set of regular expressions this validator will validate
* against
* @param caseSensitive
* when <code>true</code> matching is <i>case sensitive</i>,
* otherwise matching is <i>case in-sensitive</i>
*/
public RegexValidator(String[] regexs, boolean caseSensitive) {
if (regexs == null || regexs.length == 0) {
throw new IllegalArgumentException(
"Regular expressions are missing");
}
patterns = new Pattern[regexs.length];
int flags = (caseSensitive ? 0 : Pattern.CASE_INSENSITIVE);
for (int i = 0; i < regexs.length; i++) {
if (regexs[i] == null || regexs[i].length() == 0) {
throw new IllegalArgumentException("Regular expression[" + i
+ "] is missing");
}
patterns[i] = Pattern.compile(regexs[i], flags);
}
}
/**
* Validate a value against the set of regular expressions.
*
* @param value
* The value to validate.
* @return <code>true</code> if the value is valid otherwise
* <code>false</code>.
*/
public boolean isValid(String value) {
if (value == null) {
return false;
}
for (int i = 0; i < patterns.length; i++) {
if (patterns[i].matcher(value).matches()) {
return true;
}
}
return false;
}
/**
* Validate a value against the set of regular expressions returning the
* array of matched groups.
*
* @param value
* The value to validate.
* @return String array of the <i>groups</i> matched if valid or
* <code>null</code> if invalid
*/
public String[] match(String value) {
if (value == null) {
return null;
}
for (int i = 0; i < patterns.length; i++) {
Matcher matcher = patterns[i].matcher(value);
if (matcher.matches()) {
int count = matcher.groupCount();
String[] groups = new String[count];
for (int j = 0; j < count; j++) {
groups[j] = matcher.group(j + 1);
}
return groups;
}
}
return null;
}
/**
* Provide a String representation of this validator.
*
* @return A String representation of this validator
*/
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("RegexValidator{");
for (int i = 0; i < patterns.length; i++) {
if (i > 0) {
buffer.append(",");
}
buffer.append(patterns[i].pattern());
}
buffer.append("}");
return buffer.toString();
}
/**
* Validate a value against the set of regular expressions returning a
* String value of the aggregated groups.
*
* @param value
* The value to validate.
* @return Aggregated String value comprised of the <i>groups</i> matched if
* valid or <code>null</code> if invalid
*/
public String validate(String value) {
if (value == null) {
return null;
}
for (int i = 0; i < patterns.length; i++) {
Matcher matcher = patterns[i].matcher(value);
if (matcher.matches()) {
int count = matcher.groupCount();
if (count == 1) {
return matcher.group(1);
}
StringBuffer buffer = new StringBuffer();
for (int j = 0; j < count; j++) {
String component = matcher.group(j + 1);
if (component != null) {
buffer.append(component);
}
}
return buffer.toString();
}
}
return null;
}
} | zyh3290-proxy | src/org/gaeproxy/RegexValidator.java | Java | gpl3 | 6,974 |
/*
Android Asynchronous Http Client
Copyright (c) 2011 James Smith <james@loopj.com>
http://loopj.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
This code is taken from Rafael Sanches' blog.
http://blog.rafaelsanches.com/2011/01/29/upload-using-multipart-post-using-httpclient-in-android/
*/
package com.loopj.android.http;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;
class SimpleMultipartEntity implements HttpEntity {
private final static char[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public SimpleMultipartEntity() {
final StringBuffer buf = new StringBuffer();
final Random rand = new Random();
for (int i = 0; i < 30; i++) {
buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
}
this.boundary = buf.toString();
}
public void writeFirstBoundaryIfNeeds(){
if(!isSetFirst){
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
e.printStackTrace();
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if(isSetLast){
return;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
e.printStackTrace();
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n\r\n").getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
e.printStackTrace();
}
}
public void addPart(final String key, final String fileName, final InputStream fin, final boolean isLast){
addPart(key, fileName, fin, "application/octet-stream", isLast);
}
public void addPart(final String key, final String fileName, final InputStream fin, String type, final boolean isLast){
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: "+type+"\r\n";
out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
if(!isLast)
out.write(("\r\n--" + boundary + "\r\n").getBytes());
out.flush();
} catch (final IOException e) {
e.printStackTrace();
} finally {
try {
fin.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
public void addPart(final String key, final File value, final boolean isLast) {
try {
addPart(key, value.getName(), new FileInputStream(value), isLast);
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
}
@Override
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}
@Override
public boolean isChunked() {
return false;
}
@Override
public boolean isRepeatable() {
return false;
}
@Override
public boolean isStreaming() {
return false;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
@Override
public Header getContentEncoding() {
return null;
}
@Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
@Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
} | zyh3290-proxy | src/com/loopj/android/http/SimpleMultipartEntity.java | Java | gpl3 | 5,576 |
/*
Android Asynchronous Http Client
Copyright (c) 2011 James Smith <james@loopj.com>
http://loopj.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.loopj.android.http;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
/**
* A persistent cookie store which implements the Apache HttpClient
* {@link CookieStore} interface. Cookies are stored and will persist on the
* user's device between application sessions since they are serialized and
* stored in {@link SharedPreferences}.
* <p>
* Instances of this class are designed to be used with
* {@link AsyncHttpClient#setCookieStore}, but can also be used with a
* regular old apache HttpClient/HttpContext if you prefer.
*/
public class PersistentCookieStore implements CookieStore {
private static final String COOKIE_PREFS = "CookiePrefsFile";
private static final String COOKIE_NAME_STORE = "names";
private static final String COOKIE_NAME_PREFIX = "cookie_";
private final ConcurrentHashMap<String, Cookie> cookies;
private final SharedPreferences cookiePrefs;
/**
* Construct a persistent cookie store.
*/
public PersistentCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new ConcurrentHashMap<String, Cookie>();
// Load any previously stored cookies into the store
String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null);
if(storedCookieNames != null) {
String[] cookieNames = TextUtils.split(storedCookieNames, ",");
for(String name : cookieNames) {
String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
if(encodedCookie != null) {
Cookie decodedCookie = decodeCookie(encodedCookie);
if(decodedCookie != null) {
cookies.put(name, decodedCookie);
}
}
}
// Clear out expired cookies
clearExpired(new Date());
}
}
@Override
public void addCookie(Cookie cookie) {
String name = cookie.getName();
// Save cookie into local store, or remove if expired
if(!cookie.isExpired(new Date())) {
cookies.put(name, cookie);
} else {
cookies.remove(name);
}
// Save cookie into persistent store
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));
prefsWriter.commit();
}
@Override
public void clear() {
// Clear cookies from local store
cookies.clear();
// Clear cookies from persistent store
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
for(String name : cookies.keySet()) {
prefsWriter.remove(COOKIE_NAME_PREFIX + name);
}
prefsWriter.remove(COOKIE_NAME_STORE);
prefsWriter.commit();
}
@Override
public boolean clearExpired(Date date) {
boolean clearedAny = false;
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
for(ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) {
String name = entry.getKey();
Cookie cookie = entry.getValue();
if(cookie.isExpired(date)) {
// Clear cookies from local store
cookies.remove(name);
// Clear cookies from persistent store
prefsWriter.remove(COOKIE_NAME_PREFIX + name);
// We've cleared at least one
clearedAny = true;
}
}
// Update names in persistent store
if(clearedAny) {
prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
}
prefsWriter.commit();
return clearedAny;
}
@Override
public List<Cookie> getCookies() {
return new ArrayList<Cookie>(cookies.values());
}
//
// Cookie serialization/deserialization
//
protected String encodeCookie(SerializableCookie cookie) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ObjectOutputStream outputStream = new ObjectOutputStream(os);
outputStream.writeObject(cookie);
} catch (Exception e) {
return null;
}
return byteArrayToHexString(os.toByteArray());
}
protected Cookie decodeCookie(String cookieStr) {
byte[] bytes = hexStringToByteArray(cookieStr);
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
Cookie cookie = null;
try {
ObjectInputStream ois = new ObjectInputStream(is);
cookie = ((SerializableCookie)ois.readObject()).getCookie();
} catch (Exception e) {
e.printStackTrace();
}
return cookie;
}
// Using some super basic byte array <-> hex conversions so we don't have
// to rely on any large Base64 libraries. Can be overridden if you like!
protected String byteArrayToHexString(byte[] b) {
StringBuffer sb = new StringBuffer(b.length * 2);
for (byte element : b) {
int v = element & 0xff;
if(v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString().toUpperCase();
}
protected byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for(int i=0; i<len; i+=2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
}
return data;
}
} | zyh3290-proxy | src/com/loopj/android/http/PersistentCookieStore.java | Java | gpl3 | 6,854 |
/*
Android Asynchronous Http Client
Copyright (c) 2011 James Smith <james@loopj.com>
http://loopj.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.loopj.android.http;
import java.io.Serializable;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.Date;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;
/**
* A wrapper class around {@link Cookie} and/or {@link BasicClientCookie}
* designed for use in {@link PersistentCookieStore}.
*/
public class SerializableCookie implements Serializable {
private static final long serialVersionUID = 6374381828722046732L;
private transient final Cookie cookie;
private transient BasicClientCookie clientCookie;
public SerializableCookie(Cookie cookie) {
this.cookie = cookie;
}
public Cookie getCookie() {
Cookie bestCookie = cookie;
if(clientCookie != null) {
bestCookie = clientCookie;
}
return bestCookie;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(cookie.getName());
out.writeObject(cookie.getValue());
out.writeObject(cookie.getComment());
out.writeObject(cookie.getDomain());
out.writeObject(cookie.getExpiryDate());
out.writeObject(cookie.getPath());
out.writeInt(cookie.getVersion());
out.writeBoolean(cookie.isSecure());
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
String name = (String)in.readObject();
String value = (String)in.readObject();
clientCookie = new BasicClientCookie(name, value);
clientCookie.setComment((String)in.readObject());
clientCookie.setDomain((String)in.readObject());
clientCookie.setExpiryDate((Date)in.readObject());
clientCookie.setPath((String)in.readObject());
clientCookie.setVersion(in.readInt());
clientCookie.setSecure(in.readBoolean());
}
} | zyh3290-proxy | src/com/loopj/android/http/SerializableCookie.java | Java | gpl3 | 2,610 |
/*
Android Asynchronous Http Client
Copyright (c) 2011 James Smith <james@loopj.com>
http://loopj.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.loopj.android.http;
import java.io.IOException;
import java.net.ConnectException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.protocol.HttpContext;
class AsyncHttpRequest implements Runnable {
private final AbstractHttpClient client;
private final HttpContext context;
private final HttpUriRequest request;
private final AsyncHttpResponseHandler responseHandler;
private int executionCount;
public AsyncHttpRequest(AbstractHttpClient client, HttpContext context, HttpUriRequest request, AsyncHttpResponseHandler responseHandler) {
this.client = client;
this.context = context;
this.request = request;
this.responseHandler = responseHandler;
}
public void run() {
try {
if(responseHandler != null){
responseHandler.sendStartMessage();
}
makeRequestWithRetries();
if(responseHandler != null) {
responseHandler.sendFinishMessage();
}
} catch (IOException e) {
if(responseHandler != null) {
responseHandler.sendFinishMessage();
responseHandler.sendFailureMessage(e, null);
}
}
}
private void makeRequest() throws IOException {
if(!Thread.currentThread().isInterrupted()) {
HttpResponse response = client.execute(request, context);
if(!Thread.currentThread().isInterrupted()) {
if(responseHandler != null) {
responseHandler.sendResponseMessage(response);
}
} else{
//TODO: should raise InterruptedException? this block is reached whenever the request is cancelled before its response is received
}
}
}
private void makeRequestWithRetries() throws ConnectException {
// This is an additional layer of retry logic lifted from droid-fu
// See: https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/http/BetterHttpRequestBase.java
boolean retry = true;
IOException cause = null;
HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
while (retry) {
try {
makeRequest();
return;
} catch (IOException e) {
cause = e;
retry = retryHandler.retryRequest(cause, ++executionCount, context);
} catch (NullPointerException e) {
// there's a bug in HttpClient 4.0.x that on some occasions causes
// DefaultRequestExecutor to throw an NPE, see
// http://code.google.com/p/android/issues/detail?id=5255
cause = new IOException("NPE in HttpClient" + e.getMessage());
retry = retryHandler.retryRequest(cause, ++executionCount, context);
}
}
// no retries left, crap out with exception
ConnectException ex = new ConnectException();
ex.initCause(cause);
throw ex;
}
} | zyh3290-proxy | src/com/loopj/android/http/AsyncHttpRequest.java | Java | gpl3 | 3,877 |
/*
Android Asynchronous Http Client
Copyright (c) 2011 James Smith <james@loopj.com>
http://loopj.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.loopj.android.http;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpResponseException;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.util.EntityUtils;
import android.os.Handler;
import android.os.Message;
import android.os.Looper;
/**
* Used to intercept and handle the responses from requests made using
* {@link AsyncHttpClient}. The {@link #onSuccess(String)} method is
* designed to be anonymously overridden with your own response handling code.
* <p>
* Additionally, you can override the {@link #onFailure(Throwable, String)},
* {@link #onStart()}, and {@link #onFinish()} methods as required.
* <p>
* For example:
* <p>
* <pre>
* AsyncHttpClient client = new AsyncHttpClient();
* client.get("http://www.google.com", new AsyncHttpResponseHandler() {
* @Override
* public void onStart() {
* // Initiated the request
* }
*
* @Override
* public void onSuccess(String response) {
* // Successfully got a response
* }
*
* @Override
* public void onFailure(Throwable e, String response) {
* // Response failed :(
* }
*
* @Override
* public void onFinish() {
* // Completed the request (either success or failure)
* }
* });
* </pre>
*/
public class AsyncHttpResponseHandler {
private static final int SUCCESS_MESSAGE = 0;
private static final int FAILURE_MESSAGE = 1;
private static final int START_MESSAGE = 2;
private static final int FINISH_MESSAGE = 3;
private Handler handler;
/**
* Creates a new AsyncHttpResponseHandler
*/
public AsyncHttpResponseHandler() {
// Set up a handler to post events back to the correct thread if possible
if(Looper.myLooper() != null) {
handler = new Handler(){
public void handleMessage(Message msg){
AsyncHttpResponseHandler.this.handleMessage(msg);
}
};
}
}
//
// Callbacks to be overridden, typically anonymously
//
/**
* Fired when the request is started, override to handle in your own code
*/
public void onStart() {}
/**
* Fired in all cases when the request is finished, after both success and failure, override to handle in your own code
*/
public void onFinish() {}
/**
* Fired when a request returns successfully, override to handle in your own code
* @param content the body of the HTTP response from the server
*/
public void onSuccess(String content) {}
/**
* Fired when a request fails to complete, override to handle in your own code
* @param error the underlying cause of the failure
* @deprecated use {@link #onFailure(Throwable, String)}
*/
public void onFailure(Throwable error) {}
/**
* Fired when a request fails to complete, override to handle in your own code
* @param error the underlying cause of the failure
* @param content the response body, if any
*/
public void onFailure(Throwable error, String content) {
// By default, call the deprecated onFailure(Throwable) for compatibility
onFailure(error);
}
//
// Pre-processing of messages (executes in background threadpool thread)
//
protected void sendSuccessMessage(String responseBody) {
sendMessage(obtainMessage(SUCCESS_MESSAGE, responseBody));
}
protected void sendFailureMessage(Throwable e, String responseBody) {
sendMessage(obtainMessage(FAILURE_MESSAGE, new Object[]{e, responseBody}));
}
protected void sendStartMessage() {
sendMessage(obtainMessage(START_MESSAGE, null));
}
protected void sendFinishMessage() {
sendMessage(obtainMessage(FINISH_MESSAGE, null));
}
//
// Pre-processing of messages (in original calling thread, typically the UI thread)
//
protected void handleSuccessMessage(String responseBody) {
onSuccess(responseBody);
}
protected void handleFailureMessage(Throwable e, String responseBody) {
onFailure(e, responseBody);
}
// Methods which emulate android's Handler and Message methods
protected void handleMessage(Message msg) {
switch(msg.what) {
case SUCCESS_MESSAGE:
handleSuccessMessage((String)msg.obj);
break;
case FAILURE_MESSAGE:
Object[] repsonse = (Object[])msg.obj;
handleFailureMessage((Throwable)repsonse[0], (String)repsonse[1]);
break;
case START_MESSAGE:
onStart();
break;
case FINISH_MESSAGE:
onFinish();
break;
}
}
protected void sendMessage(Message msg) {
if(handler != null){
handler.sendMessage(msg);
} else {
handleMessage(msg);
}
}
protected Message obtainMessage(int responseMessage, Object response) {
Message msg = null;
if(handler != null){
msg = this.handler.obtainMessage(responseMessage, response);
}else{
msg = new Message();
msg.what = responseMessage;
msg.obj = response;
}
return msg;
}
// Interface to AsyncHttpRequest
void sendResponseMessage(HttpResponse response) {
StatusLine status = response.getStatusLine();
String responseBody = null;
try {
HttpEntity entity = null;
HttpEntity temp = response.getEntity();
if(temp != null) {
entity = new BufferedHttpEntity(temp);
}
responseBody = EntityUtils.toString(entity);
} catch(IOException e) {
sendFailureMessage(e, null);
}
if(status.getStatusCode() >= 300) {
sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody);
} else {
sendSuccessMessage(responseBody);
}
}
} | zyh3290-proxy | src/com/loopj/android/http/AsyncHttpResponseHandler.java | Java | gpl3 | 6,926 |
/*
Android Asynchronous Http Client
Copyright (c) 2011 James Smith <james@loopj.com>
http://loopj.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.loopj.android.http;
import java.io.InputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
/**
* A collection of string request parameters or files to send along with
* requests made from an {@link AsyncHttpClient} instance.
* <p>
* For example:
* <p>
* <pre>
* RequestParams params = new RequestParams();
* params.put("username", "james");
* params.put("password", "123456");
* params.put("email", "my@email.com");
* params.put("profile_picture", new File("pic.jpg")); // Upload a File
* params.put("profile_picture2", someInputStream); // Upload an InputStream
* params.put("profile_picture3", new ByteArrayInputStream(someBytes)); // Upload some bytes
*
* AsyncHttpClient client = new AsyncHttpClient();
* client.post("http://myendpoint.com", params, responseHandler);
* </pre>
*/
public class RequestParams {
private static String ENCODING = "UTF-8";
protected ConcurrentHashMap<String, String> urlParams;
protected ConcurrentHashMap<String, FileWrapper> fileParams;
/**
* Constructs a new empty <code>RequestParams</code> instance.
*/
public RequestParams() {
init();
}
/**
* Constructs a new RequestParams instance containing the key/value
* string params from the specified map.
* @param source the source key/value string map to add.
*/
public RequestParams(Map<String, String> source) {
init();
for(Map.Entry<String, String> entry : source.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
/**
* Constructs a new RequestParams instance and populate it with a single
* initial key/value string param.
* @param key the key name for the intial param.
* @param value the value string for the initial param.
*/
public RequestParams(String key, String value) {
init();
put(key, value);
}
/**
* Adds a key/value string pair to the request.
* @param key the key name for the new param.
* @param value the value string for the new param.
*/
public void put(String key, String value){
if(key != null && value != null) {
urlParams.put(key, value);
}
}
/**
* Adds a file to the request.
* @param key the key name for the new param.
* @param file the file to add.
*/
public void put(String key, File file) throws FileNotFoundException {
put(key, new FileInputStream(file), file.getName());
}
/**
* Adds an input stream to the request.
* @param key the key name for the new param.
* @param stream the input stream to add.
*/
public void put(String key, InputStream stream) {
put(key, stream, null);
}
/**
* Adds an input stream to the request.
* @param key the key name for the new param.
* @param stream the input stream to add.
* @param fileName the name of the file.
*/
public void put(String key, InputStream stream, String fileName) {
put(key, stream, fileName, null);
}
/**
* Adds an input stream to the request.
* @param key the key name for the new param.
* @param stream the input stream to add.
* @param fileName the name of the file.
* @param contentType the content type of the file, eg. application/json
*/
public void put(String key, InputStream stream, String fileName, String contentType) {
if(key != null && stream != null) {
fileParams.put(key, new FileWrapper(stream, fileName, contentType));
}
}
/**
* Removes a parameter from the request.
* @param key the key name for the parameter to remove.
*/
public void remove(String key){
urlParams.remove(key);
fileParams.remove(key);
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
for(ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
if(result.length() > 0)
result.append("&");
result.append(entry.getKey());
result.append("=");
result.append(entry.getValue());
}
for(ConcurrentHashMap.Entry<String, FileWrapper> entry : fileParams.entrySet()) {
if(result.length() > 0)
result.append("&");
result.append(entry.getKey());
result.append("=");
result.append("FILE");
}
return result.toString();
}
/**
* Returns an HttpEntity containing all request parameters
*/
public HttpEntity getEntity() {
HttpEntity entity = null;
if(!fileParams.isEmpty()) {
SimpleMultipartEntity multipartEntity = new SimpleMultipartEntity();
// Add string params
for(ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
multipartEntity.addPart(entry.getKey(), entry.getValue());
}
// Add file params
int currentIndex = 0;
int lastIndex = fileParams.entrySet().size() - 1;
for(ConcurrentHashMap.Entry<String, FileWrapper> entry : fileParams.entrySet()) {
FileWrapper file = entry.getValue();
if(file.inputStream != null) {
boolean isLast = currentIndex == lastIndex;
if(file.contentType != null) {
multipartEntity.addPart(entry.getKey(), file.getFileName(), file.inputStream, file.contentType, isLast);
} else {
multipartEntity.addPart(entry.getKey(), file.getFileName(), file.inputStream, isLast);
}
}
currentIndex++;
}
entity = multipartEntity;
} else {
try {
entity = new UrlEncodedFormEntity(getParamsList(), ENCODING);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return entity;
}
private void init(){
urlParams = new ConcurrentHashMap<String, String>();
fileParams = new ConcurrentHashMap<String, FileWrapper>();
}
protected List<BasicNameValuePair> getParamsList() {
List<BasicNameValuePair> lparams = new LinkedList<BasicNameValuePair>();
for(ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
lparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
return lparams;
}
protected String getParamString() {
return URLEncodedUtils.format(getParamsList(), ENCODING);
}
private static class FileWrapper {
public InputStream inputStream;
public String fileName;
public String contentType;
public FileWrapper(InputStream inputStream, String fileName, String contentType) {
this.inputStream = inputStream;
this.fileName = fileName;
this.contentType = contentType;
}
public String getFileName() {
if(fileName != null) {
return fileName;
} else {
return "nofilename";
}
}
}
} | zyh3290-proxy | src/com/loopj/android/http/RequestParams.java | Java | gpl3 | 8,371 |
/*
Android Asynchronous Http Client
Copyright (c) 2011 James Smith <james@loopj.com>
http://loopj.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.loopj.android.http;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
/**
* Used to intercept and handle the responses from requests made using
* {@link AsyncHttpClient}, with automatic parsing into a {@link JSONObject}
* or {@link JSONArray}.
* <p>
* This class is designed to be passed to get, post, put and delete requests
* with the {@link #onSuccess(JSONObject)} or {@link #onSuccess(JSONArray)}
* methods anonymously overridden.
* <p>
* Additionally, you can override the other event methods from the
* parent class.
*/
public class JsonHttpResponseHandler extends AsyncHttpResponseHandler {
//
// Callbacks to be overridden, typically anonymously
//
/**
* Fired when a request returns successfully and contains a json object
* at the base of the response string. Override to handle in your
* own code.
* @param response the parsed json object found in the server response (if any)
*/
public void onSuccess(JSONObject response) {}
/**
* Fired when a request returns successfully and contains a json array
* at the base of the response string. Override to handle in your
* own code.
* @param response the parsed json array found in the server response (if any)
*/
public void onSuccess(JSONArray response) {}
// Utility methods
@Override
protected void handleSuccessMessage(String responseBody) {
super.handleSuccessMessage(responseBody);
try {
Object jsonResponse = parseResponse(responseBody);
if(jsonResponse instanceof JSONObject) {
onSuccess((JSONObject)jsonResponse);
} else if(jsonResponse instanceof JSONArray) {
onSuccess((JSONArray)jsonResponse);
} else {
throw new JSONException("Unexpected type " + jsonResponse.getClass().getName());
}
} catch(JSONException e) {
onFailure(e, responseBody);
}
}
protected Object parseResponse(String responseBody) throws JSONException {
return new JSONTokener(responseBody).nextValue();
}
/**
* Handle cases where a failure is returned as JSON
*/
public void onFailure(Throwable e, JSONObject errorResponse) {}
public void onFailure(Throwable e, JSONArray errorResponse) {}
@Override
protected void handleFailureMessage(Throwable e, String responseBody) {
super.handleFailureMessage(e, responseBody);
if (responseBody != null) try {
Object jsonResponse = parseResponse(responseBody);
if(jsonResponse instanceof JSONObject) {
onFailure(e, (JSONObject)jsonResponse);
} else if(jsonResponse instanceof JSONArray) {
onFailure(e, (JSONArray)jsonResponse);
}
}
catch(JSONException ex) {
onFailure(e, responseBody);
}
else {
onFailure(e, "");
}
}
} | zyh3290-proxy | src/com/loopj/android/http/JsonHttpResponseHandler.java | Java | gpl3 | 3,731 |
/*
Android Asynchronous Http Client
Copyright (c) 2011 James Smith <james@loopj.com>
http://loopj.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.loopj.android.http;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpVersion;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.SyncBasicHttpContext;
import android.content.Context;
/**
* The AsyncHttpClient can be used to make asynchronous GET, POST, PUT and
* DELETE HTTP requests in your Android applications. Requests can be made with
* additional parameters by passing a {@link RequestParams} instance, and
* responses can be handled by passing an anonymously overridden
* {@link AsyncHttpResponseHandler} instance.
* <p>
* For example:
* <p>
*
* <pre>
* AsyncHttpClient client = new AsyncHttpClient();
* client.get("http://www.google.com", new AsyncHttpResponseHandler() {
* @Override
* public void onSuccess(String response) {
* System.out.println(response);
* }
* });
* </pre>
*/
public class AsyncHttpClient {
private static final String VERSION = "1.3.2";
private static final int DEFAULT_MAX_CONNECTIONS = 10;
private static final int DEFAULT_SOCKET_TIMEOUT = 10 * 1000;
private static final int DEFAULT_MAX_RETRIES = 5;
private static final int DEFAULT_SOCKET_BUFFER_SIZE = 8192;
private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
private static final String ENCODING_GZIP = "gzip";
private static int maxConnections = DEFAULT_MAX_CONNECTIONS;
private static int socketTimeout = DEFAULT_SOCKET_TIMEOUT;
private final DefaultHttpClient httpClient;
private final HttpContext httpContext;
private ThreadPoolExecutor threadPool;
private final Map<Context, List<WeakReference<Future<?>>>> requestMap;
private final Map<String, String> clientHeaderMap;
/**
* Creates a new AsyncHttpClient.
*/
public AsyncHttpClient() {
BasicHttpParams httpParams = new BasicHttpParams();
ConnManagerParams.setTimeout(httpParams, socketTimeout);
ConnManagerParams.setMaxConnectionsPerRoute(httpParams,
new ConnPerRouteBean(maxConnections));
ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
HttpConnectionParams.setTcpNoDelay(httpParams, true);
HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setUserAgent(httpParams, String.format(
"android-async-http/%s (http://loopj.com/android-async-http)", VERSION));
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
httpContext = new SyncBasicHttpContext(new BasicHttpContext());
httpClient = new DefaultHttpClient(cm, httpParams);
httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(HttpRequest request, HttpContext context) {
if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
}
for (String header : clientHeaderMap.keySet()) {
request.addHeader(header, clientHeaderMap.get(header));
}
}
});
httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
public void process(HttpResponse response, HttpContext context) {
final HttpEntity entity = response.getEntity();
final Header encoding = entity.getContentEncoding();
if (encoding != null) {
for (HeaderElement element : encoding.getElements()) {
if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
response.setEntity(new InflatingEntity(response.getEntity()));
break;
}
}
}
}
});
httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));
threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
clientHeaderMap = new HashMap<String, String>();
}
/**
* Get the underlying HttpClient instance. This is useful for setting
* additional fine-grained settings for requests by accessing the client's
* ConnectionManager, HttpParams and SchemeRegistry.
*/
public HttpClient getHttpClient() {
return this.httpClient;
}
/**
* Sets an optional CookieStore to use when making requests
*
* @param cookieStore
* The CookieStore implementation to use, usually an instance of
* {@link PersistentCookieStore}
*/
public void setCookieStore(CookieStore cookieStore) {
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}
/**
* Overrides the threadpool implementation used when queuing/pooling
* requests. By default, Executors.newCachedThreadPool() is used.
*
* @param threadPool
* an instance of {@link ThreadPoolExecutor} to use for
* queuing/pooling requests.
*/
public void setThreadPool(ThreadPoolExecutor threadPool) {
this.threadPool = threadPool;
}
/**
* Sets the User-Agent header to be sent with each request. By default,
* "Android Asynchronous Http Client/VERSION (http://loopj.com/android-async-http/)"
* is used.
*
* @param userAgent
* the string to use in the User-Agent header.
*/
public void setUserAgent(String userAgent) {
HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent);
}
/**
* Sets the connection time oout. By default, 10 seconds
*
* @param timeout
* the connect/socket timeout in milliseconds
*/
public void setTimeout(int timeout) {
final HttpParams httpParams = this.httpClient.getParams();
ConnManagerParams.setTimeout(httpParams, timeout);
HttpConnectionParams.setSoTimeout(httpParams, timeout);
HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
}
/**
* Sets the SSLSocketFactory to user when making requests. By default, a
* new, default SSLSocketFactory is used.
*
* @param sslSocketFactory
* the socket factory to use for https requests.
*/
public void setSSLSocketFactory(SSLSocketFactory sslSocketFactory) {
this.httpClient.getConnectionManager().getSchemeRegistry()
.register(new Scheme("https", sslSocketFactory, 443));
}
/**
* Sets headers that will be added to all requests this client makes (before
* sending).
*
* @param header
* the name of the header
* @param value
* the contents of the header
*/
public void addHeader(String header, String value) {
clientHeaderMap.put(header, value);
}
/**
* Cancels any pending (or potentially active) requests associated with the
* passed Context.
* <p>
* <b>Note:</b> This will only affect requests which were created with a
* non-null android Context. This method is intended to be used in the
* onDestroy method of your android activities to destroy all requests which
* are no longer required.
*
* @param context
* the android Context instance associated to the request.
* @param mayInterruptIfRunning
* specifies if active requests should be cancelled along with
* pending requests.
*/
public void cancelRequests(Context context, boolean mayInterruptIfRunning) {
List<WeakReference<Future<?>>> requestList = requestMap.get(context);
if (requestList != null) {
for (WeakReference<Future<?>> requestRef : requestList) {
Future<?> request = requestRef.get();
if (request != null) {
request.cancel(mayInterruptIfRunning);
}
}
}
requestMap.remove(context);
}
//
// HTTP GET Requests
//
/**
* Perform a HTTP GET request, without any parameters.
*
* @param url
* the URL to send the request to.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void get(String url, AsyncHttpResponseHandler responseHandler) {
get(null, url, null, responseHandler);
}
/**
* Perform a HTTP GET request with parameters.
*
* @param url
* the URL to send the request to.
* @param params
* additional GET parameters to send with the request.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
get(null, url, params, responseHandler);
}
/**
* Perform a HTTP GET request without any parameters and track the Android
* Context which initiated the request.
*
* @param context
* the Android Context which initiated the request.
* @param url
* the URL to send the request to.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void get(Context context, String url, AsyncHttpResponseHandler responseHandler) {
get(context, url, null, responseHandler);
}
/**
* Perform a HTTP GET request and track the Android Context which initiated
* the request.
*
* @param context
* the Android Context which initiated the request.
* @param url
* the URL to send the request to.
* @param params
* additional GET parameters to send with the request.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void get(Context context, String url, RequestParams params,
AsyncHttpResponseHandler responseHandler) {
sendRequest(httpClient, httpContext, new HttpGet(getUrlWithQueryString(url, params)), null,
responseHandler, context);
}
/**
* Perform a HTTP GET request and track the Android Context which initiated
* the request with customized headers
*
* @param url
* the URL to send the request to.
* @param headers
* set headers only for this request
* @param params
* additional GET parameters to send with the request.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void get(Context context, String url, Header[] headers, RequestParams params,
AsyncHttpResponseHandler responseHandler) {
HttpUriRequest request = new HttpGet(getUrlWithQueryString(url, params));
if (headers != null)
request.setHeaders(headers);
sendRequest(httpClient, httpContext, request, null, responseHandler, context);
}
public void get(String url, String host, AsyncHttpResponseHandler responseHandler) {
HttpUriRequest request = new HttpGet(url);
request.setHeader("Host", host);
sendRequest(httpClient, httpContext, request, null, responseHandler, null);
}
//
// HTTP POST Requests
//
/**
* Perform a HTTP POST request, without any parameters.
*
* @param url
* the URL to send the request to.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void post(String url, AsyncHttpResponseHandler responseHandler) {
post(null, url, null, responseHandler);
}
/**
* Perform a HTTP POST request with parameters.
*
* @param url
* the URL to send the request to.
* @param params
* additional POST parameters or files to send with the request.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
post(null, url, params, responseHandler);
}
/**
* Perform a HTTP POST request and track the Android Context which initiated
* the request.
*
* @param context
* the Android Context which initiated the request.
* @param url
* the URL to send the request to.
* @param params
* additional POST parameters or files to send with the request.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void post(Context context, String url, RequestParams params,
AsyncHttpResponseHandler responseHandler) {
post(context, url, paramsToEntity(params), null, responseHandler);
}
/**
* Perform a HTTP POST request and track the Android Context which initiated
* the request.
*
* @param context
* the Android Context which initiated the request.
* @param url
* the URL to send the request to.
* @param entity
* a raw {@link HttpEntity} to send with the request, for
* example, use this to send string/json/xml payloads to a server
* by passing a {@link org.apache.http.entity.StringEntity}.
* @param contentType
* the content type of the payload you are sending, for example
* application/json if sending a json payload.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void post(Context context, String url, HttpEntity entity, String contentType,
AsyncHttpResponseHandler responseHandler) {
sendRequest(httpClient, httpContext, addEntityToRequestBase(new HttpPost(url), entity),
contentType, responseHandler, context);
}
/**
* Perform a HTTP POST request and track the Android Context which initiated
* the request. Set headers only for this request
*
* @param context
* the Android Context which initiated the request.
* @param url
* the URL to send the request to.
* @param headers
* set headers only for this request
* @param entity
* a raw {@link HttpEntity} to send with the request, for
* example, use this to send string/json/xml payloads to a server
* by passing a {@link org.apache.http.entity.StringEntity}.
* @param contentType
* the content type of the payload you are sending, for example
* application/json if sending a json payload.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void post(Context context, String url, Header[] headers, RequestParams params,
String contentType, AsyncHttpResponseHandler responseHandler) {
HttpEntityEnclosingRequestBase request = new HttpPost(url);
if (params != null)
request.setEntity(paramsToEntity(params));
if (headers != null)
request.setHeaders(headers);
sendRequest(httpClient, httpContext, request, contentType, responseHandler, context);
}
//
// HTTP PUT Requests
//
/**
* Perform a HTTP PUT request, without any parameters.
*
* @param url
* the URL to send the request to.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void put(String url, AsyncHttpResponseHandler responseHandler) {
put(null, url, null, responseHandler);
}
/**
* Perform a HTTP PUT request with parameters.
*
* @param url
* the URL to send the request to.
* @param params
* additional PUT parameters or files to send with the request.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void put(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
put(null, url, params, responseHandler);
}
/**
* Perform a HTTP PUT request and track the Android Context which initiated
* the request.
*
* @param context
* the Android Context which initiated the request.
* @param url
* the URL to send the request to.
* @param params
* additional PUT parameters or files to send with the request.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void put(Context context, String url, RequestParams params,
AsyncHttpResponseHandler responseHandler) {
put(context, url, paramsToEntity(params), null, responseHandler);
}
/**
* Perform a HTTP PUT request and track the Android Context which initiated
* the request. And set one-time headers for the request
*
* @param context
* the Android Context which initiated the request.
* @param url
* the URL to send the request to.
* @param entity
* a raw {@link HttpEntity} to send with the request, for
* example, use this to send string/json/xml payloads to a server
* by passing a {@link org.apache.http.entity.StringEntity}.
* @param contentType
* the content type of the payload you are sending, for example
* application/json if sending a json payload.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void put(Context context, String url, HttpEntity entity, String contentType,
AsyncHttpResponseHandler responseHandler) {
sendRequest(httpClient, httpContext, addEntityToRequestBase(new HttpPut(url), entity),
contentType, responseHandler, context);
}
/**
* Perform a HTTP PUT request and track the Android Context which initiated
* the request. And set one-time headers for the request
*
* @param context
* the Android Context which initiated the request.
* @param url
* the URL to send the request to.
* @param headers
* set one-time headers for this request
* @param entity
* a raw {@link HttpEntity} to send with the request, for
* example, use this to send string/json/xml payloads to a server
* by passing a {@link org.apache.http.entity.StringEntity}.
* @param contentType
* the content type of the payload you are sending, for example
* application/json if sending a json payload.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void put(Context context, String url, Header[] headers, HttpEntity entity,
String contentType, AsyncHttpResponseHandler responseHandler) {
HttpEntityEnclosingRequestBase request = addEntityToRequestBase(new HttpPut(url), entity);
if (headers != null)
request.setHeaders(headers);
sendRequest(httpClient, httpContext, request, contentType, responseHandler, context);
}
//
// HTTP DELETE Requests
//
/**
* Perform a HTTP DELETE request.
*
* @param url
* the URL to send the request to.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void delete(String url, AsyncHttpResponseHandler responseHandler) {
delete(null, url, responseHandler);
}
/**
* Perform a HTTP DELETE request.
*
* @param context
* the Android Context which initiated the request.
* @param url
* the URL to send the request to.
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void delete(Context context, String url, AsyncHttpResponseHandler responseHandler) {
final HttpDelete delete = new HttpDelete(url);
sendRequest(httpClient, httpContext, delete, null, responseHandler, context);
}
/**
* Perform a HTTP DELETE request.
*
* @param context
* the Android Context which initiated the request.
* @param url
* the URL to send the request to.
* @param headers
* set one-time headers for this request
* @param responseHandler
* the response handler instance that should handle the response.
*/
public void delete(Context context, String url, Header[] headers,
AsyncHttpResponseHandler responseHandler) {
final HttpDelete delete = new HttpDelete(url);
if (headers != null)
delete.setHeaders(headers);
sendRequest(httpClient, httpContext, delete, null, responseHandler, context);
}
// Private stuff
private void sendRequest(DefaultHttpClient client, HttpContext httpContext,
HttpUriRequest uriRequest, String contentType,
AsyncHttpResponseHandler responseHandler, Context context) {
if (contentType != null) {
uriRequest.addHeader("Content-Type", contentType);
}
Future<?> request = threadPool.submit(new AsyncHttpRequest(client, httpContext, uriRequest,
responseHandler));
if (context != null) {
// Add request to request map
List<WeakReference<Future<?>>> requestList = requestMap.get(context);
if (requestList == null) {
requestList = new LinkedList<WeakReference<Future<?>>>();
requestMap.put(context, requestList);
}
requestList.add(new WeakReference<Future<?>>(request));
// TODO: Remove dead weakrefs from requestLists?
}
}
private String getUrlWithQueryString(String url, RequestParams params) {
if (params != null) {
String paramString = params.getParamString();
url += "?" + paramString;
}
return url;
}
private HttpEntity paramsToEntity(RequestParams params) {
HttpEntity entity = null;
if (params != null) {
entity = params.getEntity();
}
return entity;
}
private HttpEntityEnclosingRequestBase addEntityToRequestBase(
HttpEntityEnclosingRequestBase requestBase, HttpEntity entity) {
if (entity != null) {
requestBase.setEntity(entity);
}
return requestBase;
}
private static class InflatingEntity extends HttpEntityWrapper {
public InflatingEntity(HttpEntity wrapped) {
super(wrapped);
}
@Override
public InputStream getContent() throws IOException {
return new GZIPInputStream(wrappedEntity.getContent());
}
@Override
public long getContentLength() {
return -1;
}
}
}
| zyh3290-proxy | src/com/loopj/android/http/AsyncHttpClient.java | Java | gpl3 | 24,273 |
/*
Android Asynchronous Http Client
Copyright (c) 2011 James Smith <james@loopj.com>
http://loopj.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
Some of the retry logic in this class is heavily borrowed from the
fantastic droid-fu project: https://github.com/donnfelker/droid-fu
*/
package com.loopj.android.http;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashSet;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import android.os.SystemClock;
class RetryHandler implements HttpRequestRetryHandler {
private static final int RETRY_SLEEP_TIME_MILLIS = 1500;
private static HashSet<Class<?>> exceptionWhitelist = new HashSet<Class<?>>();
private static HashSet<Class<?>> exceptionBlacklist = new HashSet<Class<?>>();
static {
// Retry if the server dropped connection on us
exceptionWhitelist.add(NoHttpResponseException.class);
// retry-this, since it may happens as part of a Wi-Fi to 3G failover
exceptionWhitelist.add(UnknownHostException.class);
// retry-this, since it may happens as part of a Wi-Fi to 3G failover
exceptionWhitelist.add(SocketException.class);
// never retry timeouts
exceptionBlacklist.add(InterruptedIOException.class);
// never retry SSL handshake failures
exceptionBlacklist.add(SSLHandshakeException.class);
}
private final int maxRetries;
public RetryHandler(int maxRetries) {
this.maxRetries = maxRetries;
}
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
boolean retry;
Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
boolean sent = (b != null && b.booleanValue());
if(executionCount > maxRetries) {
// Do not retry if over max retry count
retry = false;
} else if (exceptionBlacklist.contains(exception.getClass())) {
// immediately cancel retry if the error is blacklisted
retry = false;
} else if (exceptionWhitelist.contains(exception.getClass())) {
// immediately retry if error is whitelisted
retry = true;
} else if (!sent) {
// for most other errors, retry only if request hasn't been fully sent yet
retry = true;
} else {
// resend all idempotent requests
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
String requestType = currentReq.getMethod();
if(!requestType.equals("POST")) {
retry = true;
} else {
// otherwise do not retry
retry = false;
}
}
if(retry) {
SystemClock.sleep(RETRY_SLEEP_TIME_MILLIS);
} else {
exception.printStackTrace();
}
return retry;
}
} | zyh3290-proxy | src/com/loopj/android/http/RetryHandler.java | Java | gpl3 | 3,820 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "Exec"
#include "jni.h"
#include <android/log.h>
#define LOGI(...) do { __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__); } while(0)
#define LOGW(...) do { __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__); } while(0)
#define LOGE(...) do { __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__); } while(0)
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <termios.h>
#include <signal.h>
static jclass class_fileDescriptor;
static jfieldID field_fileDescriptor_descriptor;
static jmethodID method_fileDescriptor_init;
typedef unsigned short char16_t;
class String8 {
public:
String8() {
mString = 0;
}
~String8() {
if (mString) {
free(mString);
}
}
void set(const char16_t* o, size_t numChars) {
if (mString) {
free(mString);
}
mString = (char*) malloc(numChars + 1);
if (!mString) {
return;
}
for (size_t i = 0; i < numChars; i++) {
mString[i] = (char) o[i];
}
mString[numChars] = '\0';
}
const char* string() {
return mString;
}
private:
char* mString;
};
static int throwOutOfMemoryError(JNIEnv *env, const char *message)
{
jclass exClass;
const char *className = "java/lang/OutOfMemoryError";
exClass = env->FindClass(className);
return env->ThrowNew(exClass, message);
}
static int create_subprocess(const char *cmd,
char *const argv[], char *const envp[], int* pProcessId)
{
char filename[] = "/data/data/org.gaeproxy/defout";
char script[] = "/data/data/org.gaeproxy/script";
pid_t pid;
if (chmod(script, 0755) < 0) {
LOGE("error to chmod\n");
exit(-1);
}
int defout = open(filename, O_RDWR | O_CREAT | O_TRUNC, 0600);
if(defout < 0) {
LOGE("open file error\n");
exit(-1);
}
pid = fork();
if(pid < 0) {
LOGE("- fork failed: %s -\n", strerror(errno));
return -1;
}
if(pid == 0){
//setsid();
dup2(defout, 1);
dup2(defout, 2);
if (envp) {
for (; *envp; ++envp) {
putenv(*envp);
}
}
execv(cmd, argv);
exit(-1);
} else {
*pProcessId = (int) pid;
return defout;
}
}
static jobject android_os_Exec_createSubProcess(JNIEnv *env, jobject clazz,
jstring cmd, jobjectArray args, jobjectArray envVars,
jintArray processIdArray)
{
const jchar* str = cmd ? env->GetStringCritical(cmd, 0) : 0;
String8 cmd_8;
if (str) {
cmd_8.set(str, env->GetStringLength(cmd));
env->ReleaseStringCritical(cmd, str);
}
jsize size = args ? env->GetArrayLength(args) : 0;
char **argv = NULL;
String8 tmp_8;
if (size > 0) {
argv = (char **)malloc((size+1)*sizeof(char *));
if (!argv) {
throwOutOfMemoryError(env, "Couldn't allocate argv array");
return NULL;
}
for (int i = 0; i < size; ++i) {
jstring arg = reinterpret_cast<jstring>(env->GetObjectArrayElement(args, i));
str = env->GetStringCritical(arg, 0);
if (!str) {
throwOutOfMemoryError(env, "Couldn't get argument from array");
return NULL;
}
tmp_8.set(str, env->GetStringLength(arg));
env->ReleaseStringCritical(arg, str);
argv[i] = strdup(tmp_8.string());
}
argv[size] = NULL;
}
size = envVars ? env->GetArrayLength(envVars) : 0;
char **envp = NULL;
if (size > 0) {
envp = (char **)malloc((size+1)*sizeof(char *));
if (!envp) {
throwOutOfMemoryError(env, "Couldn't allocate envp array");
return NULL;
}
for (int i = 0; i < size; ++i) {
jstring var = reinterpret_cast<jstring>(env->GetObjectArrayElement(envVars, i));
str = env->GetStringCritical(var, 0);
if (!str) {
throwOutOfMemoryError(env, "Couldn't get env var from array");
return NULL;
}
tmp_8.set(str, env->GetStringLength(var));
env->ReleaseStringCritical(var, str);
envp[i] = strdup(tmp_8.string());
}
envp[size] = NULL;
}
int procId;
int ptm = create_subprocess(cmd_8.string(), argv, envp, &procId);
if (argv) {
for (char **tmp = argv; *tmp; ++tmp) {
free(*tmp);
}
free(argv);
}
if (envp) {
for (char **tmp = envp; *tmp; ++tmp) {
free(*tmp);
}
free(envp);
}
if (processIdArray) {
int procIdLen = env->GetArrayLength(processIdArray);
if (procIdLen > 0) {
jboolean isCopy;
int* pProcId = (int*) env->GetPrimitiveArrayCritical(processIdArray, &isCopy);
if (pProcId) {
*pProcId = procId;
env->ReleasePrimitiveArrayCritical(processIdArray, pProcId, 0);
}
}
}
jobject result = env->NewObject(class_fileDescriptor, method_fileDescriptor_init);
if (!result) {
LOGE("Couldn't create a FileDescriptor.");
}
else {
env->SetIntField(result, field_fileDescriptor_descriptor, ptm);
}
return result;
}
static int android_os_Exec_waitFor(JNIEnv *env, jobject clazz,
jint procId) {
int status;
waitpid(procId, &status, 0);
int result = 0;
if (WIFEXITED(status)) {
result = WEXITSTATUS(status);
}
return result;
}
static void android_os_Exec_close(JNIEnv *env, jobject clazz, jobject fileDescriptor)
{
int fd;
fd = env->GetIntField(fileDescriptor, field_fileDescriptor_descriptor);
if (env->ExceptionOccurred() != NULL) {
return;
}
close(fd);
}
static void android_os_Exec_hangupProcessGroup(JNIEnv *env, jobject clazz,
jint procId) {
kill(-procId, SIGHUP);
}
static int register_FileDescriptor(JNIEnv *env)
{
jclass localRef_class_fileDescriptor = env->FindClass("java/io/FileDescriptor");
if (localRef_class_fileDescriptor == NULL) {
LOGE("Can't find class java/io/FileDescriptor");
return -1;
}
class_fileDescriptor = (jclass) env->NewGlobalRef(localRef_class_fileDescriptor);
env->DeleteLocalRef(localRef_class_fileDescriptor);
if (class_fileDescriptor == NULL) {
LOGE("Can't get global ref to class java/io/FileDescriptor");
return -1;
}
field_fileDescriptor_descriptor = env->GetFieldID(class_fileDescriptor, "descriptor", "I");
if (field_fileDescriptor_descriptor == NULL) {
LOGE("Can't find FileDescriptor.descriptor");
return -1;
}
method_fileDescriptor_init = env->GetMethodID(class_fileDescriptor, "<init>", "()V");
if (method_fileDescriptor_init == NULL) {
LOGE("Can't find FileDescriptor.init");
return -1;
}
return 0;
}
static const char *classPathName = "org/gaeproxy/Exec";
static JNINativeMethod method_table[] = {
{ "createSubprocess", "(Ljava/lang/String;[Ljava/lang/String;[Ljava/lang/String;[I)Ljava/io/FileDescriptor;",
(void*) android_os_Exec_createSubProcess },
{ "waitFor", "(I)I",
(void*) android_os_Exec_waitFor},
{ "close", "(Ljava/io/FileDescriptor;)V",
(void*) android_os_Exec_close},
{ "hangupProcessGroup", "(I)V",
(void*) android_os_Exec_hangupProcessGroup}
};
/*
* Register several native methods for one class.
*/
static int registerNativeMethods(JNIEnv* env, const char* className,
JNINativeMethod* gMethods, int numMethods)
{
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
LOGE("Native registration unable to find class '%s'", className);
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {
LOGE("RegisterNatives failed for '%s'", className);
return JNI_FALSE;
}
return JNI_TRUE;
}
/*
* Register native methods for all classes we know about.
*
* returns JNI_TRUE on success.
*/
static int registerNatives(JNIEnv* env)
{
if (!registerNativeMethods(env, classPathName, method_table,
sizeof(method_table) / sizeof(method_table[0]))) {
return JNI_FALSE;
}
return JNI_TRUE;
}
// ----------------------------------------------------------------------------
/*
* This is called by the VM when the shared library is first loaded.
*/
typedef union {
JNIEnv* env;
void* venv;
} UnionJNIEnvToVoid;
jint JNI_OnLoad(JavaVM* vm, void* reserved) {
UnionJNIEnvToVoid uenv;
uenv.venv = NULL;
jint result = -1;
JNIEnv* env = NULL;
LOGI("JNI_OnLoad");
if (vm->GetEnv(&uenv.venv, JNI_VERSION_1_4) != JNI_OK) {
LOGE("ERROR: GetEnv failed");
goto bail;
}
env = uenv.env;
if ((result = register_FileDescriptor(env)) < 0) {
LOGE("ERROR: registerFileDescriptor failed");
goto bail;
}
if (registerNatives(env) != JNI_TRUE) {
LOGE("ERROR: registerNatives failed");
goto bail;
}
result = JNI_VERSION_1_4;
bail:
return result;
}
| zyh3290-proxy | jni/termExec.cpp | C++ | gpl3 | 10,617 |
# Build both ARMv5TE and x86 machine code.
APP_ABI := armeabi
| zyh3290-proxy | jni/Application.mk | Makefile | gpl3 | 62 |
#
# Copyright (C) 2008 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This makefile supplies the rules for building a library of JNI code for
# use by our example of how to bundle a shared library with an APK.
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
# This is the target being built.
LOCAL_MODULE:= libexec
# All of the source files that we will compile.
LOCAL_SRC_FILES:= \
termExec.cpp
LOCAL_LDLIBS := -ldl -llog
include $(BUILD_SHARED_LIBRARY)
| zyh3290-proxy | jni/Android.mk | Makefile | gpl3 | 1,001 |
APP_ABI := armeabi
| zyh3290-proxy | external_python_cl/jni/Application.mk | Makefile | gpl3 | 19 |
/* Minimal main program -- everything is loaded from the library */
#include <dlfcn.h>
typedef int (*main_t)(int, char **);
#define PYTHONPATH "/sdcard/python-extras:/mnt/sdcard/python-extras:/data/data/org.gaeproxy/files/python-extras:/data/data/org.gaeproxy/python/lib/python2.6/lib-dynload"
#define PYTHONHOME "/data/data/org.gaeproxy/python"
#define LD_LIBRARY_PATH "/data/data/org.gaeproxy/python/lib"
int
main(int argc, char **argv)
{
setenv("PYTHONPATH", PYTHONPATH, 0);
setenv("PYTHONHOME", PYTHONHOME, 0);
setenv("LD_LIBRARY_PATH", LD_LIBRARY_PATH, 1);
void *fd = dlopen("/data/data/org.gaeproxy/python/lib/libpython2.6.so", RTLD_LAZY);
main_t Py_Main = (main_t) dlsym (fd, "Py_Main");
int exitcode = Py_Main(argc, argv);
dlclose(fd);
return exitcode;
}
| zyh3290-proxy | external_python_cl/jni/python.c | C | gpl3 | 796 |
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
# This is the target being built.
LOCAL_MODULE := python
# All of the source files that we will compile.
LOCAL_SRC_FILES := python.c
LOCAL_SHARED_LIBRARIES := libdl
include $(BUILD_EXECUTABLE)
| zyh3290-proxy | external_python_cl/jni/Android.mk | Makefile | gpl3 | 248 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is RSJ Software GmbH code.
*
* The Initial Developer of the Original Code is
* RSJ Software GmbH.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributors:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <stdio.h>
#include <windows.h>
#include <winbase.h>
// ----------------------------------------------------------------------------
int main (int ArgC,
char *ArgV[])
{
const char *sourceName;
const char *targetName;
HANDLE targetHandle;
void *versionPtr;
DWORD versionLen;
int lastError;
int ret = 0;
if (ArgC < 3) {
fprintf(stderr,
"Usage: %s <source> <target>\n",
ArgV[0]);
exit (1);
}
sourceName = ArgV[1];
targetName = ArgV[2];
if ((versionLen = GetFileVersionInfoSize(sourceName,
NULL)) == 0) {
fprintf(stderr,
"Could not retrieve version len from %s\n",
sourceName);
exit (2);
}
if ((versionPtr = calloc(1,
versionLen)) == NULL) {
fprintf(stderr,
"Error allocating temp memory\n");
exit (3);
}
if (!GetFileVersionInfo(sourceName,
NULL,
versionLen,
versionPtr)) {
fprintf(stderr,
"Could not retrieve version info from %s\n",
sourceName);
exit (4);
}
if ((targetHandle = BeginUpdateResource(targetName,
FALSE)) == INVALID_HANDLE_VALUE) {
fprintf(stderr,
"Could not begin update of %s\n",
targetName);
free(versionPtr);
exit (5);
}
if (!UpdateResource(targetHandle,
RT_VERSION,
MAKEINTRESOURCE(VS_VERSION_INFO),
MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL),
versionPtr,
versionLen)) {
lastError = GetLastError();
fprintf(stderr,
"Error %d updating resource\n",
lastError);
ret = 6;
}
if (!EndUpdateResource(targetHandle,
FALSE)) {
fprintf(stderr,
"Error finishing update\n");
ret = 7;
}
free(versionPtr);
return (ret);
}
| zzhongster-wxtlactivex | transver/transver.cpp | C++ | mpl11 | 3,963 |
# Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
# Use of this source code is governed by a Mozilla-1.1 license that can be
# found in the LICENSE file.
import googlecode_upload
import tempfile
import urllib2
import optparse
import os
extensionid = 'lgllffgicojgllpmdbemgglaponefajn'
def download():
url = ("https://clients2.google.com/service/update2/crx?"
"response=redirect&x=id%3D" + extensionid + "%26uc")
response = urllib2.urlopen(url)
filename = response.geturl().split('/')[-1]
version = '.'.join(filename.replace('_', '.').split('.')[1:-1])
name = os.path.join(tempfile.gettempdir(), filename)
f = open(name, 'wb')
data = response.read()
f.write(data)
f.close()
return name, version
def upload(path, version, user, password):
summary = 'Extension version ' + version + ' download'
labels = ['Type-Executable']
print googlecode_upload.upload(
path, 'np-activex', user, password, summary, labels)
def main():
parser = optparse.OptionParser()
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
options, args = parser.parse_args()
name, version = download()
print 'File downloaded ', name, version
upload(name, version, options.user, options.password)
os.remove(name)
if __name__ == '__main__':
main()
| zzhongster-wxtlactivex | Tools/upload.py | Python | mpl11 | 1,501 |
import subprocess
import tempfile
import shutil
import os
import codecs
import json
import zipfile
class Packer:
def __init__(self, input_path, outputfile):
self.input_path = os.path.abspath(input_path)
self.outputfile = os.path.abspath(outputfile)
self.tmppath = None
def pack(self):
if self.tmppath == None:
self.tmppath = tempfile.mkdtemp()
else:
self.tmppath = os.path.abspath(self.tmppath)
if not os.path.isdir(self.tmppath):
os.mkdir(self.tmppath)
self.zipf = zipfile.ZipFile(self.outputfile, 'w', zipfile.ZIP_DEFLATED)
self.processdir('')
self.zipf.close()
def processdir(self, path):
dst = os.path.join(self.tmppath, path)
if not os.path.isdir(dst):
os.mkdir(dst)
for f in os.listdir(os.path.join(self.input_path, path)):
abspath = os.path.join(self.input_path, path, f)
if os.path.isdir(abspath):
self.processdir(os.path.join(path, f))
else:
self.processfile(os.path.join(path, f))
def compact_json(self, src, dst):
print 'Compacting json file ', src
with open(src) as s:
sval = s.read()
if sval[:3] == codecs.BOM_UTF8:
sval = sval[3:].decode('utf-8')
val = json.loads(sval, 'utf-8')
with open(dst, 'w') as d:
json.dump(val, d, separators=(',', ':'))
def processfile(self, path):
src = os.path.join(self.input_path, path)
dst = os.path.join(self.tmppath, path)
if not os.path.isfile(dst) or os.stat(src).st_mtime > os.stat(dst).st_mtime:
ext = os.path.splitext(path)[1].lower()
op = None
if ext == '.js':
if path.split(os.sep)[0] == 'settings':
op = self.copyfile
elif os.path.basename(path) == 'jquery.js':
op = self.copyfile
else:
op = self.compilefile
elif ext == '.json':
op = self.compact_json
elif ext in ['.swp', '.php']:
pass
else:
op = self.copyfile
if op != None:
op(src, dst)
if os.path.isfile(dst):
self.zipf.write(dst, path)
def copyfile(self, src, dst):
shutil.copyfile(src, dst)
def compilefile(self, src, dst):
args = ['java', '-jar', 'compiler.jar',\
'--js', src, '--js_output_file', dst]
args += ['--language_in', 'ECMASCRIPT5']
print 'Compiling ', src
retval = subprocess.call(args)
if retval != 0:
os.remove(dst)
print 'Failed to generate ', dst
a = Packer('..\\chrome', '..\\plugin.zip')
a.tmppath = '..\\output'
a.pack()
| zzhongster-wxtlactivex | Tools/pack.py | Python | mpl11 | 2,602 |
#!/usr/bin/env python
#
# Copyright 2006, 2007 Google Inc. All Rights Reserved.
# Author: danderson@google.com (David Anderson)
#
# Script for uploading files to a Google Code project.
#
# This is intended to be both a useful script for people who want to
# streamline project uploads and a reference implementation for
# uploading files to Google Code projects.
#
# To upload a file to Google Code, you need to provide a path to the
# file on your local machine, a small summary of what the file is, a
# project name, and a valid account that is a member or owner of that
# project. You can optionally provide a list of labels that apply to
# the file. The file will be uploaded under the same name that it has
# in your local filesystem (that is, the "basename" or last path
# component). Run the script with '--help' to get the exact syntax
# and available options.
#
# Note that the upload script requests that you enter your
# googlecode.com password. This is NOT your Gmail account password!
# This is the password you use on googlecode.com for committing to
# Subversion and uploading files. You can find your password by going
# to http://code.google.com/hosting/settings when logged in with your
# Gmail account. If you have already committed to your project's
# Subversion repository, the script will automatically retrieve your
# credentials from there (unless disabled, see the output of '--help'
# for details).
#
# If you are looking at this script as a reference for implementing
# your own Google Code file uploader, then you should take a look at
# the upload() function, which is the meat of the uploader. You
# basically need to build a multipart/form-data POST request with the
# right fields and send it to https://PROJECT.googlecode.com/files .
# Authenticate the request using HTTP Basic authentication, as is
# shown below.
#
# Licensed under the terms of the Apache Software License 2.0:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Questions, comments, feature requests and patches are most welcome.
# Please direct all of these to the Google Code users group:
# http://groups.google.com/group/google-code-hosting
"""Google Code file uploader script.
"""
__author__ = 'danderson@google.com (David Anderson)'
import httplib
import os.path
import optparse
import getpass
import base64
import sys
def upload(file, project_name, user_name, password, summary, labels=None):
"""Upload a file to a Google Code project's file server.
Args:
file: The local path to the file.
project_name: The name of your project on Google Code.
user_name: Your Google account name.
password: The googlecode.com password for your account.
Note that this is NOT your global Google Account password!
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
Returns: a tuple:
http_status: 201 if the upload succeeded, something else if an
error occured.
http_reason: The human-readable string associated with http_status
file_url: If the upload succeeded, the URL of the file on Google
Code, None otherwise.
"""
# The login is the user part of user@gmail.com. If the login provided
# is in the full user@domain form, strip it down.
if user_name.endswith('@gmail.com'):
user_name = user_name[:user_name.index('@gmail.com')]
form_fields = [('summary', summary)]
if labels is not None:
form_fields.extend([('label', l.strip()) for l in labels])
content_type, body = encode_upload_request(form_fields, file)
upload_host = '%s.googlecode.com' % project_name
upload_uri = '/files'
auth_token = base64.b64encode('%s:%s'% (user_name, password))
headers = {
'Authorization': 'Basic %s' % auth_token,
'User-Agent': 'Googlecode.com uploader v0.9.4',
'Content-Type': content_type,
}
server = httplib.HTTPSConnection(upload_host)
server.request('POST', upload_uri, body, headers)
resp = server.getresponse()
server.close()
if resp.status == 201:
location = resp.getheader('Location', None)
else:
location = None
return resp.status, resp.reason, location
def encode_upload_request(fields, file_path):
"""Encode the given fields and file into a multipart form body.
fields is a sequence of (name, value) pairs. file is the path of
the file to upload. The file will be uploaded to Google Code with
the same file name.
Returns: (content_type, body) ready for httplib.HTTP instance
"""
BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla'
CRLF = '\r\n'
body = []
# Add the metadata about the upload first
for key, value in fields:
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="%s"' % key,
'',
value,
])
# Now add the file itself
file_name = os.path.basename(file_path)
f = open(file_path, 'rb')
file_content = f.read()
f.close()
body.extend(
['--' + BOUNDARY,
'Content-Disposition: form-data; name="filename"; filename="%s"'
% file_name,
# The upload server determines the mime-type, no need to set it.
'Content-Type: application/octet-stream',
'',
file_content,
])
# Finalize the form body
body.extend(['--' + BOUNDARY + '--', ''])
return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body)
def upload_find_auth(file_path, project_name, summary, labels=None,
user_name=None, password=None, tries=3):
"""Find credentials and upload a file to a Google Code project's file server.
file_path, project_name, summary, and labels are passed as-is to upload.
Args:
file_path: The local path to the file.
project_name: The name of your project on Google Code.
summary: A small description for the file.
labels: an optional list of label strings with which to tag the file.
config_dir: Path to Subversion configuration directory, 'none', or None.
user_name: Your Google account name.
tries: How many attempts to make.
"""
if user_name is None or password is None:
from netrc import netrc
authenticators = netrc().authenticators("code.google.com")
if authenticators:
if user_name is None:
user_name = authenticators[0]
if password is None:
password = authenticators[2]
while tries > 0:
if user_name is None:
# Read username if not specified or loaded from svn config, or on
# subsequent tries.
sys.stdout.write('Please enter your googlecode.com username: ')
sys.stdout.flush()
user_name = sys.stdin.readline().rstrip()
if password is None:
# Read password if not loaded from svn config, or on subsequent tries.
print 'Please enter your googlecode.com password.'
print '** Note that this is NOT your Gmail account password! **'
print 'It is the password you use to access Subversion repositories,'
print 'and can be found here: http://code.google.com/hosting/settings'
password = getpass.getpass()
status, reason, url = upload(file_path, project_name, user_name, password,
summary, labels)
# Returns 403 Forbidden instead of 401 Unauthorized for bad
# credentials as of 2007-07-17.
if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]:
# Rest for another try.
user_name = password = None
tries = tries - 1
else:
# We're done.
break
return status, reason, url
def main():
parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY '
'-p PROJECT [options] FILE')
parser.add_option('-s', '--summary', dest='summary',
help='Short description of the file')
parser.add_option('-p', '--project', dest='project',
help='Google Code project name')
parser.add_option('-u', '--user', dest='user',
help='Your Google Code username')
parser.add_option('-w', '--password', dest='password',
help='Your Google Code password')
parser.add_option('-l', '--labels', dest='labels',
help='An optional list of comma-separated labels to attach '
'to the file')
options, args = parser.parse_args()
if not options.summary:
parser.error('File summary is missing.')
elif not options.project:
parser.error('Project name is missing.')
elif len(args) < 1:
parser.error('File to upload not provided.')
elif len(args) > 1:
parser.error('Only one file may be specified.')
file_path = args[0]
if options.labels:
labels = options.labels.split(',')
else:
labels = None
status, reason, url = upload_find_auth(file_path, options.project,
options.summary, labels,
options.user, options.password)
if url:
print 'The file was uploaded successfully.'
print 'URL: %s' % url
return 0
else:
print 'An error occurred. Your file was not uploaded.'
print 'Google Code upload server said: %s (%s)' % (reason, status)
return 1
if __name__ == '__main__':
sys.exit(main())
| zzhongster-wxtlactivex | Tools/googlecode_upload.py | Python | mpl11 | 9,200 |
import threading
import os
import csv
import argparse
from datetime import datetime
class Logger:
fields = ['name', 'mail', 'nickname', 'amount', 'actual_amount', 'unit',\
'comment', 'time', 'method', 'id']
def __init__(self, config):
logfile = config['logfile']
self.path = logfile + '.csv'
self.amount_file = logfile + '.sum'
self._file = open(self.path, 'ab', 1)
self._writer = csv.DictWriter(self._file, Logger.fields)
self._sum_lock = threading.RLock()
self.lock = threading.RLock()
try:
timestamp = os.stat(self.amount_file).st_mtime
except Exception as ex:
with open(self.amount_file, 'w') as f:
print '0\n0\n0' > f
timestamp = os.stat(self.amount_file).st_mtime
self.lastupdate = datetime.fromtimestamp(timestamp)
def log(self, item):
with self.lock:
s = dict(item)
s['time'] = s['time'].strftime('%Y/%m/%d %H:%M:%S')
for i in s:
if isinstance(s[i], unicode):
s[i] = s[i].encode('utf-8')
self._writer.writerow(s)
if item['unit'] == 'RMB':
self.add_total(0, 0, float(item['amount']))
else:
self.add_total(float(item['amount']), float(item['actual_amount']), 0)
def close(self):
self._file.close()
def read_total(self):
with self._sum_lock:
val = []
with open(self.amount_file) as amount_file:
for line in amount_file:
val.append(float(line))
return val
def read_records(self):
with self.lock:
self._file.close()
f = open(self.path, 'rb')
reader = csv.DictReader(f, Logger.fields)
# Read the header
vals = []
for item in reader:
item['time'] = datetime.strptime(item['time'], '%Y/%m/%d %H:%M:%S')
item['amount'] = float(item['amount'])
item['actual_amount'] = float(item['actual_amount'])
for field in item:
value = item[field]
if isinstance(value, str):
item[field] = value.decode('utf-8')
vals.append(item)
vals.sort(key = lambda x : x['time'])
self._file = open(self.path, 'ab', 1)
self._writer = csv.DictWriter(self._file, Logger.fields)
return vals
def add_total(self, *delta):
with self._sum_lock:
val = self.read_total()
for i in xrange(len(delta)):
val[i] += delta[i]
with open(self.amount_file, 'w') as amount_file:
for v in val:
print >> amount_file, v
def add_from_input(self):
item = {}
print '1: paypal'
print '2: taobao'
print '3: alipay'
method = int(raw_input('Select the payment method:'))
method = ['paypal', 'taobao', 'alipay'][method - 1]
item['method'] = method
if method == 'paypal':
item['unit'] = 'USD'
else:
item['unit'] = 'RMB'
for field in Logger.fields:
if field == 'actual_amount':
if method in ['taobao', 'alipay']:
item['actual_amount'] = item['amount']
else:
item['actual_amount'] = float(raw_input(field + ':'))
elif field == 'amount':
item[field] = float(raw_input(field + ':'))
elif field == 'time':
if method == 'paypal':
fmt = '%Y-%b-%d %H:%M:%S'
else:
fmt = '%Y-%m-%d %H:%M:%S'
item[field] = datetime.strptime(raw_input(field + ':'), fmt)
elif field in ['method', 'unit']:
pass
elif field == 'nickname' and method != 'taobao':
item[field] = item['name']
else:
item[field] = unicode(raw_input(field + ':'), 'gbk')
self.log(item)
print 'item added'
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--log', dest='logfile', help='Logfile',
required=True)
args = parser.parse_args()
logger = Logger(vars(args))
while True:
logger.add_from_input()
if raw_input('continue(y/N)?') != 'y':
break
logger.close()
if __name__ == '__main__':
main()
| zzhongster-wxtlactivex | Tools/donation/log.py | Python | mpl11 | 4,082 |
import urllib
import urllib2
import argparse
import sys
from log import Logger
from datetime import datetime, timedelta
def verify_order(postdata, sandbox):
data = 'cmd=_notify-validate&' + postdata
if sandbox:
scr = 'https://www.sandbox.paypal.com/cgi-bin/websc'
else:
scr = 'https://www.paypal.com/cgi-bin/websc'
res = urllib2.urlopen(scr, data).read()
if res == 'VERIFIED':
return True
return False
def convert_order(item):
value = {}
value['name'] = item['address_name']
value['mail'] = item['payer_email']
value['nickname'] = item['address_name']
gross = float(item['mc_gross'])
fee = float(item['mc_fee'])
value['amount'] = gross
value['actual_amount'] = gross - fee
value['unit'] = 'USD'
value['comment'] = ''
try:
value['time'] = datetime.strptime(
item['payment_date'], '%H:%M:%S %b %d, %Y PDT') + timedelta(hours = 15)
except:
value['time'] = datetime.strptime(
item['payment_date'], '%H:%M:%S %b %d, %Y PST') + timedelta(hours = 16)
value['method'] = 'paypal'
value['id'] = item['txn_id']
return value
def get_order(postdata):
fields = postdata.split('&')
item = {}
for field in fields:
name, value = field.split('=')
value = urllib.unquote_plus(value)
item[name] = value
for field in item:
item[field] = item[field].decode(item['charset'])
return item
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--log', dest='logfile', help='Logfile',
required=True)
parser.add_argument('-p', '--paypal', dest='paypal', help='Paypal input',
required=True)
args = parser.parse_args()
item = get_order(args.paypal)
if not verify_order(args.paypal, 'test_ipn' in item):
print 'Error in verification'
print args.paypal
sys.exit(1)
if item['payment_status'] != 'Completed':
print 'Payment from ', item['address_name'], ' not completed ', item['txn_id']
print args.paypal
sys.exit(1)
logitem = convert_order(item)
logfile = args.logfile
if 'test_ipn' in item:
logfile = 'test'
logger = Logger({'logfile': logfile})
logger.log(logitem)
logger.close()
print (u'Received payment from %s, txn_id=%s, amount=$%.2f, date=%s' % (
logitem['name'], logitem['id'], logitem['amount'], item['payment_date']
)).encode('utf-8')
if __name__ == '__main__':
main()
| zzhongster-wxtlactivex | Tools/donation/paypal.py | Python | mpl11 | 2,448 |
from hgapi import *
import shutil
import os
import threading
import optparse
import traceback
import log
from datetime import datetime, timedelta
class HGDonationLog:
def __init__(self, config, logger):
self._path = config['path']
self._repo = Repo(self._path)
self._target = config['logfile']
self._templatefile = config['template']
self._update_interval = float(config.get('update_interval', 300))
self._logger = logger
self.lastupdate = datetime.fromtimestamp(0)
def start_listener(self):
self.thread = threading.Thread(target = self.listener_thread)
self.thread.start()
def listener_thread(self):
self.update_file()
while True:
sleep(self._update_interval)
lastdataupdate = logger.lastupdate()
if lastdataupdate > self.lastupdate:
self.update_file()
def gen_file(self, path):
with open(path, 'w') as f:
with open(self._templatefile, 'r') as tempfile:
template = tempfile.read().decode('utf-8')
usd, usdnofee, cny = self._logger.read_total()
chinatime = (datetime.utcnow() + timedelta(hours = 8))
lastupdatestr = chinatime.strftime('%Y-%b-%d %X') + ' GMT+8'
s = template.format(cny = cny, usd = usd, usdnofee = usdnofee, lastupdate = lastupdatestr)
f.write(s.encode('utf-8'))
records = self._logger.read_records()
records.reverse()
for item in records:
t = item['time'].strftime('%b %d, %Y')
item['datestr'] = t
s = u'|| {nickname} || {amount:.2f} {unit} || {datestr} ||'.format(**item)
print >>f, s.encode('utf-8')
def update_file(self):
try:
self._repo.hg_command('pull')
self._repo.hg_update(self._repo.hg_heads()[0])
path = os.path.join(self._path, self._target)
print 'update donation log on wiki at ', datetime.utcnow() + timedelta(hours=8)
self.gen_file(path)
print 'File generated'
msg = 'Auto update from script'
diff = self._repo.hg_command('diff', self._target)
if diff == '':
print 'No change, skipping update donation wiki'
return
else:
print diff.encode('utf-8')
self._repo.hg_commit(msg, files = [self._target])
print 'change committed'
self._repo.hg_command('push')
print 'repo pushed to server'
self.lastupdate = datetime.utcnow() + timedelta(hours = 8)
except Exception as ex:
print 'Update wiki failed: ', str(ex).encode('utf-8')
traceback.print_exc()
def main():
parser = optparse.OptionParser()
parser.add_option('-w', '--wiki', dest='path', help='Your wiki repo')
parser.add_option('-o', '--output', dest='logfile', help='Your logging file')
parser.add_option('-t', '--template', dest='template',
help='Your template file')
parser.add_option('-l', '--logfile', dest='log', help='Log file')
options, args = parser.parse_args()
logger = log.Logger({'logfile': options.log})
print vars(options)
hgclient = HGDonationLog(vars(options), logger)
hgclient.update_file()
if __name__ == '__main__':
main()
| zzhongster-wxtlactivex | Tools/donation/hg.py | Python | mpl11 | 3,178 |
import sys
import top.api as topapi
import traceback
import log
import top
import json
import re
import webbrowser
import time
import urllib2
import cookielib
import urllib
import httplib
from ConfigParser import ConfigParser
from datetime import datetime, timedelta
class T:
def trace_exception(self, ex):
print ex
common = T()
configfile = 'config'
class TaobaoBackground:
def __init__(self, config):
self.config = config
self.onNewPaidOrder = []
self.onConfirmedOrder = []
self.retry = 1
self.stream = None
def get_permit(self):
request = self.config.create_request(topapi.IncrementCustomerPermitRequest)
request.session = self.config.session
f = request.getResponse()
print 'increment permit ', f
def start_stream(self):
site = self.config.stream_site
data = {}
data['app_key'] = self.config.appinfo.appkey
time = datetime.utcnow()
time += timedelta(hours = 8)
data['timestamp'] = time.strftime('%Y-%m-%d %H:%M:%S')
data['sign'] = top.sign(self.config.appinfo.secret, data)
url = '/stream'
self.connection = httplib.HTTPConnection(site, 80, timeout=60)
self.connection.request('POST', url, urllib.urlencode(data), self.get_request_header())
self.stream = self.connection.getresponse()
def get_request_header(self):
return {
'Content-type': 'application/x-www-form-urlencoded',
"Cache-Control": "no-cache",
"Connection": "Keep-Alive",
}
def start(self):
# get permit
self.get_permit()
self.start_stream()
def getMessage(self):
text = ''
while True:
char = self.stream.read(1)
if char == '\r':
continue
if char == '\n':
break
text += char
return json.loads(text)['packet']
def run(self):
self.start()
while True:
msg = self.getMessage()
self.processMessage(msg)
def processMessage(self, msg):
if msg['code'] == 101:
retry = 1
elif msg['code'] == 102:
retry = msg['msg']
elif msg['code'] == 103:
retry = msg['msg']
elif msg['code'] == 200:
print msg['msg']
elif msg['code'] == 203:
print 'Data lost'
self.config.pull(msg['msg']['begin'] / 1000, msg['msg']['end'] / 1000)
elif msg['code'] == 202:
# data
print msg['msg']
class TaobaoAx:
def __init__(self, configParser, logger):
self.session = None
self.sessionTs = 0
self.freq = 30
self.configParser = configParser
self._tradefields = 'buyer_nick,num_iid,status,pay_time,tid,payment,seller_rate,has_buyer_message,buyer_message,buyer_email,receiver_name'
self.logger = logger
def read_config(self):
cp = self.configParser
self.session = cp.get('taobao', 'session')
self.sessionTs = cp.getfloat('taobao', 'expire')
self.sessionTime = datetime.fromtimestamp(self.sessionTs)
appkey = cp.get('taobao', 'appkey')
secret = cp.get('taobao', 'appsecret')
self.appinfo = top.appinfo(appkey, secret)
self.site = cp.get('taobao', 'appsite')
self.authurl = cp.get('taobao', 'auth_url')
self.tokenurl = cp.get('taobao', 'token_url')
self.stream_site = cp.get('taobao', 'stream_site')
self.freq = cp.getint('taobao', 'freq');
if self.sessionTime > datetime.now():
print 'loaded session ', self.session
def write_config(self):
cp = self.configParser
cp.set('taobao', 'session', self.session)
cp.set('taobao', 'expire', self.sessionTs)
cp.set('taobao', 'freq', self.freq);
o = open(configfile, 'w')
cp.write(o)
o.close()
def get_auth_code(self):
if len(sys.argv) > 1:
return sys.argv[1];
url = self.authurl + str(self.appinfo.appkey)
webbrowser.open(url)
return raw_input("session authentication reqired:\n")
def request_session(self):
authcode = self.get_auth_code()
authurl = self.tokenurl
request = {}
request['client_id'] = self.appinfo.appkey
request['client_secret'] = self.appinfo.secret
request['grant_type'] = 'authorization_code'
request['code'] = authcode
request['redirect_uri'] = 'urn:ietf:wg:oauth:2.0:oob'
requeststr = urllib.urlencode(request)
response = urllib2.urlopen(authurl, requeststr).read()
response = json.loads(response)
print response
self.sessionTs = time.time() + response['expires_in']
self.sessionTime = datetime.fromtimestamp(self.sessionTs)
self.session = response['access_token']
#self.write_config()
nick = unicode(urllib2.unquote(str(response['taobao_user_nick'])), 'utf-8')
print 'Successfully logged in'
def init(self):
try:
pass
except:
self.session = None
self.read_config()
if self.session == None or self.sessionTime < datetime.now():
self.request_session()
def send_good(self, order):
request = self.create_request(topapi.LogisticsDummySendRequest)
request.session = self.session
request.tid = order['tid']
result = request.getResponse()
print 'send good: ', order['payment'], order['buyer_nick'].encode("GBK")
def rate_order(self, order):
request = self.create_request(topapi.TraderateAddRequest)
request.session = self.session
request.tid = order['tid']
request.role = 'seller'
request.flag = 2
request.result = 'good'
request.getResponse()
print 'rate order: ', order['payment'], order['buyer_nick'].encode("GBK")
def memo_order(self, order):
request = self.create_request(topapi.TradeMemoUpdateRequest)
request.session = self.session
request.tid = order['tid']
request.memo = 'Send by taobao.py'
request.getResponse()
def log_order(self, order):
logitem = {}
logitem['name'] = order['receiver_name']
logitem['mail'] = order['buyer_email']
logitem['nickname'] = order['buyer_nick']
logitem['amount'] = float(order['payment'])
logitem['actual_amount'] = float(order['payment'])
logitem['unit'] = 'RMB'
logitem['comment'] = order['buyer_message']
logitem['time'] = order['pay_time']
logitem['method'] = 'taobao'
logitem['id'] = order['tid']
self.logger.log(logitem)
def process_order(self, orderid):
try:
order = self.get_full_info(orderid)
if order['status'] == 'WAIT_SELLER_SEND_GOODS':
self.send_good(order)
self.memo_order(order)
self.log_order(order)
elif order['status'] == 'TRADE_FINISHED' and not order['seller_rate']:
self.rate_order(order)
except topapi.base.TopException as ex:
traceback.print_exc()
common.trace_exception(ex)
except topapi.base.RequestException as ex:
traceback.print_exc()
common.trace_exception(ex)
def get_paid_orders(self):
request = self.create_request(topapi.TradesSoldGetRequest)
request.session = self.session
request.fields = 'tid'
request.page_size = 100
request.page_no = 1
request.type = 'guarantee_trade'
return self._load_all_orders(request)
def _load_all_orders(self, request):
request.use_has_next = True
orders = []
while True:
f = request.getResponse()['trades_sold_get_response']
if 'trades' in f:
orders += f['trades']['trade']
if f['has_next']:
request.page_no += 1
else:
break
return orders
def get_wait_rate_orders(self):
request = self.create_request(topapi.TradesSoldGetRequest)
request.session = self.session
request.fields = 'tid'
request.status = 'TRADE_FINISHED'
request.rate_status = 'RATE_UNSELLER'
request.start_created = datetime.now() - timedelta(days = 21)
request.page_size = 100
request.type = 'guarantee_trade'
return self._load_all_orders(request)
def get_new_orders(self):
request = self.create_request(topapi.TradesSoldGetRequest)
request.session = self.session
request.fields = 'tid'
request.status = 'WAIT_SELLER_SEND_GOODS'
request.start_created = datetime.now() - timedelta(days = 5)
request.type = 'guarantee_trade'
request.page_size = 100
request.use_has_next = True
return self._load_all_orders(request)
def query_and_process_orders(self):
new_orders = self.get_new_orders()
unrated_orders = self.get_wait_rate_orders()
for order in new_orders + unrated_orders:
self.process_order(order['tid'])
def run(self):
while True:
try:
self.query_and_process_orders()
except Exception, ex:
if isinstance(ex, top.api.base.TopException):
if ex.subcode == 'isv.trade-service-rejection':
print 'Error: isv.trade-service-rejection, pause 3 minutes'
time.sleep(3 * 60)
traceback.print_exc()
common.trace_exception(ex)
#time.sleep(self.freq)
raw_input()
def get_full_info(self, tradeid):
request = self.create_request(topapi.TradeFullinfoGetRequest)
request.session = self.session
request.fields = self._tradefields
request.tid = tradeid
trade = request.getResponse()['trade_fullinfo_get_response']['trade']
if not 'buyer_message' in trade:
trade['buyer_message'] = u''
if not 'buyer_email' in trade:
trade['buyer_email'] = u''
if 'pay_time' in trade:
trade['pay_time'] = datetime.strptime(
trade['pay_time'], '%Y-%m-%d %H:%M:%S')
else:
trade['pay_time'] = datetime.fromtimestamp(0)
return trade
def make_record(self):
trades = self.get_paid_orders()
f = open('trades.csv', 'w')
print >>f, self._tradefields
fields = self._tradefields.split(',')
trades.reverse()
sum = 0
for tradeid in trades:
trade = self.get_full_info(tradeid['tid'])
if trade['status'] not in ['WAIT_BUYER_PAY', 'TRADE_CLOSED_BY_TAOBAO']:
newtrade = dict(trade)
newtrade.setdefault('pay_time', '')
newtrade['tid'] = '="%s"' % trade['tid']
newtrade['num_iid'] = '="%s"' % trade['num_iid']
items = [newtrade.get(field, '') for field in fields]
for i in range(len(items)):
if not isinstance(items[i], basestring):
items[i] = str(items[i])
s = u','.join(items)
sum += float(trade['payment'])
print >>f, s.encode('gbk')
f.close()
print 'Total: ', sum
def run_background(self):
runner = TaobaoBackground(self)
runner.onNewPaidOrder += [self.on_new_order]
runner.onConfirmedOrder += [self.on_confirmed_order]
runner.run()
def on_confirmed_order(self, order):
self.evaluate_buyer(order)
def on_new_order(self, order):
self.process_order(order['tid'])
def create_request(self, requestType):
val = requestType(self.site, 80)
val.set_app_info(self.appinfo)
return val
def main():
cp = ConfigParser()
cp.read(configfile)
logger = log.Logger({'logfile': cp.get('log', 'logfile')})
instance = TaobaoAx(cp, logger)
instance.read_config()
instance.init()
instance.query_and_process_orders()
if __name__ == '__main__':
main()
| zzhongster-wxtlactivex | Tools/donation/taobao.py | Python | mpl11 | 11,377 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
replaceSubElements(document);
pageDOMLoaded = true;
if (needNotifyBar) {
showNotifyBar();
}
| zzhongster-wxtlactivex | chrome/inject_doreplace.js | JavaScript | mpl11 | 286 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var tabStatus = {};
var version;
var firstRun = false;
var firstUpgrade = false;
var blackList = [
/^https?:\/\/[^\/]*\.taobao\.com\/.*/i,
/^https?:\/\/[^\/]*\.alipay\.com\/.*/i
];
var MAX_LOG = 400;
(function getVersion() {
$.ajax('manifest.json', {
success: function(v) {
v = JSON.parse(v);
version = v.version;
trackVersion(version);
}
});
})();
function startListener() {
chrome.extension.onConnect.addListener(function(port) {
if (!port.sender.tab) {
console.error('Not connect from tab');
return;
}
initPort(port);
});
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (!sender.tab) {
console.error('Request from non-tab');
} else if (request.command == 'Configuration') {
var config = setting.getPageConfig(request.href);
sendResponse(config);
if (request.top) {
resetTabStatus(sender.tab.id);
var dummy = {href: request.href, clsid: 'NULL', urldetect: true};
if (!config.pageRule &&
setting.getFirstMatchedRule(
dummy, setting.defaultRules)) {
detectControl(dummy, sender.tab.id, 0);
}
}
} else if (request.command == 'GetNotification') {
getNotification(request, sender, sendResponse);
} else if (request.command == 'DismissNotification') {
chrome.tabs.sendRequest(
sender.tab.id, {command: 'DismissNotificationPage'});
sendResponse({});
} else if (request.command == 'BlockSite') {
setting.blocked.push({type: 'wild', value: request.site});
setting.update();
sendResponse({});
}
}
);
}
var blocked = {};
function notifyUser(request, tabId) {
var s = tabStatus[tabId];
if (s.notify && (s.urldetect || s.count > s.actived)) {
console.log('Notify the user on tab ', tabId);
chrome.tabs.sendRequest(tabId, {command: 'NotifyUser', tabid: tabId}, null);
}
}
var greenIcon = chrome.extension.getURL('icon16.png');
var grayIcon = chrome.extension.getURL('icon16-gray.png');
var errorIcon = chrome.extension.getURL('icon16-error.png');
var responseCommands = {};
function resetTabStatus(tabId) {
tabStatus[tabId] = {
count: 0,
actived: 0,
error: 0,
urldetect: 0,
notify: true,
issueId: null,
logs: {'0': []},
objs: {'0': []},
frames: 1,
tracking: false
};
}
function initPort(port) {
var tabId = port.sender.tab.id;
if (!(tabId in tabStatus)) {
resetTabStatus(tabId);
}
var status = tabStatus[tabId];
var frameId = tabStatus[tabId].frames++;
status.logs[frameId] = [];
status.objs[frameId] = [];
port.onMessage.addListener(function(request) {
var resp = responseCommands[request.command];
if (resp) {
delete request.command;
resp(request, tabId, frameId);
} else {
console.error('Unknown command ' + request.command);
}
});
port.onDisconnect.addListener(function() {
for (var i = 0; i < status.objs[frameId].length; ++i) {
countTabObject(status, status.objs[frameId][i], -1);
}
showTabStatus(tabId);
if (status.tracking) {
if (status.count == 0) {
// Open the log page.
window.open('log.html?tabid=' + tabId);
status.tracking = false;
}
} else {
// Clean up after 1 min.
window.setTimeout(function() {
status.logs[frameId] = [];
status.objs[frameId] = [];
}, 60 * 1000);
}
});
}
chrome.tabs.onRemoved.addListener(function(tabId, removeInfo) {
if (tabStatus[tabId]) {
tabStatus[tabId].removed = true;
var TIMEOUT = 1000 * 60 * 5;
// clean up after 5 mins.
window.setTimeout(function() {
delete tabStatus[tabId];
}, TIMEOUT);
}
});
function countTabObject(status, info, delta) {
for (var i = 0; i < blackList.length; ++i) {
if (info.href.match(blackList[i])) {
return;
}
}
if (setting.getFirstMatchedRule(info, setting.blocked)) {
status.notify = false;
}
if (info.urldetect) {
status.urldetect += delta;
// That's not a object.
return;
}
if (info.actived) {
status.actived += delta;
if (delta > 0) {
trackUse(info.rule);
}
} else if (delta > 0) {
trackNotUse(info.href);
}
status.count += delta;
var issue = setting.getMatchedIssue(info);
if (issue) {
status.error += delta;
status.issueId = issue.identifier;
if (delta > 0) {
trackIssue(issue);
}
}
}
function showTabStatus(tabId) {
if (tabStatus[tabId].removed) {
return;
}
var status = tabStatus[tabId];
var title = '';
var iconPath = greenIcon;
if (!status.count && !status.urldetect) {
chrome.pageAction.hide(tabId);
return;
} else {
chrome.pageAction.show(tabId);
}
if (status.urldetect) {
// Matched some rule.
iconPath = grayIcon;
title = $$('status_urldetect');
} else if (status.count == 0) {
// Do nothing..
} else if (status.error != 0) {
// Error
iconPath = errorIcon;
title = $$('status_error');
} else if (status.count != status.actived) {
// Disabled..
iconPath = grayIcon;
title = $$('status_disabled');
} else {
// OK
iconPath = greenIcon;
title = $$('status_ok');
}
chrome.pageAction.setIcon({
tabId: tabId,
path: iconPath
});
chrome.pageAction.setTitle({
tabId: tabId,
title: title
});
chrome.pageAction.setPopup({
tabId: tabId,
popup: 'popup.html?tabid=' + tabId
});
}
function detectControl(request, tabId, frameId) {
var status = tabStatus[tabId];
if (frameId != 0 && status.objs[0].length) {
// Remove the item to identify the page.
countTabObject(status, status.objs[0][0], -1);
status.objs[0] = [];
}
status.objs[frameId].push(request);
countTabObject(status, request, 1);
showTabStatus(tabId);
notifyUser(request, tabId);
}
responseCommands.DetectControl = detectControl;
responseCommands.Log = function(request, tabId, frameId) {
var logs = tabStatus[tabId].logs[frameId];
if (logs.length < MAX_LOG) {
logs.push(request.message);
} else if (logs.length == MAX_LOG) {
logs.push('More logs clipped');
}
};
function generateLogFile(tabId) {
var status = tabStatus[tabId];
if (!status) {
return 'No log for tab ' + tabId;
}
var ret = '---------- Start of log --------------\n';
ret += 'UserAgent: ' + navigator.userAgent + '\n';
ret += 'Extension version: ' + version + '\n';
ret += '\n';
var frameCount = 0;
for (var i = 0; i < status.frames; ++i) {
if (status.objs[i].length == 0 && status.logs[i].length == 0) {
continue;
}
if (frameCount) {
ret += '\n\n';
}
++frameCount;
ret += '------------ Frame ' + (i + 1) + ' ------------------\n';
ret += 'Objects:\n';
for (var j = 0; j < status.objs[i].length; ++j) {
ret += JSON.stringify(status.objs[i][j]) + '\n';
}
ret += '\n';
ret += 'Log:\n';
for (var j = 0; j < status.logs[i].length; ++j) {
ret += status.logs[i][j] + '\n';
}
}
ret += '\n---------------- End of log ---------------\n';
ret += stringHash(ret);
if (frameCount == 0) {
return 'No log for tab ' + tabId;
}
return ret;
}
function getNotification(request, sender, sendResponse) {
var tabid = sender.tab.id;
chrome.tabs.get(tabid, function(tab) {
var config = {};
config.tabId = tab.id;
config.site = tab.url.replace(/[^:]*:\/\/([^\/]*).*/, '$1');
config.sitePattern = tab.url.replace(/([^:]*:\/\/[^\/]*).*/, '$1/*');
if (tabStatus[tabid].urldetect) {
config.message = $$('status_urldetect');
} else {
config.message = $$('status_disabled');
}
config.closeMsg = $$('bar_close');
config.enableMsg = $$('bar_enable');
config.blockMsg = $$('bar_block', config.site);
sendResponse(config);
});
}
| zzhongster-wxtlactivex | chrome/common.js | JavaScript | mpl11 | 8,465 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
/*
Rule: {
identifier: an unique identifier
title: description
type: Can be "wild", "regex", "clsid"
value: pattern, correspond to type
userAgent: the useragent value. See var "agents" for options.
script: script to inject. Separated by spaces
}
Order: {
status: enabled / disabled / custom
position: default / custom
identifier: identifier of rule
}
Issue: {
type: Can be "wild", "regex", "clsid"
value: pattern, correspond to type
description: The description of this issue
issueId: Issue ID on issue tracking page
url: optional, support page for issue tracking.
Use code.google.com if omitted.
}
ServerSide:
ActiveXConfig: {
version: version
rules: object of user-defined rules, propertied by identifiers
defaultRules: ojbect of default rules
scripts: mapping of workaround scripts, by identifiers.
order: the order of rules
cache: to accerlerate processing
issues: The bugs/unsuppoted sites that we have accepted.
misc:{
lastUpdate: last timestamp of updating
logEnabled: log
tracking: Allow GaS tracking.
verbose: verbose level of logging
}
}
PageSide:
ActiveXConfig: {
pageSide: Flag of pageSide.
pageScript: Helper script to execute on context of page
extScript: Helper script to execute on context of extension
pageRule: If page is matched.
clsidRules: If page is not matched or disabled. valid CLSID rules
logEnabled: log
verbose: verbose level of logging
}
*/
function ActiveXConfig(input)
{
var settings;
if (input === undefined) {
var defaultSetting = {
version: 3,
rules: {},
defaultRules: {},
scriptContents: {},
scripts: {},
order: [],
notify: [],
issues: [],
blocked: [],
misc: {
lastUpdate: 0,
logEnabled: false,
tracking: true,
verbose: 3
}
};
input = defaultSetting;
}
settings = ActiveXConfig.convertVersion(input);
settings.removeInvalidItems();
settings.update();
return settings;
}
var settingKey = 'setting';
clsidPattern = /[^0-9A-F][0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}[^0-9A-F]/;
var agents = {
ie9: 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
ie8: 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0)',
ie7: 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64;)',
ff7win: 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0.1)' +
' Gecko/20100101 Firefox/7.0.1',
ip5: 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X)' +
' AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1' +
' Mobile/9A334 Safari/7534.48.3',
ipad5: 'Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46' +
'(KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3'
};
function getUserAgent(key) {
// This script is always run under sandbox, so useragent should be always
// correct.
if (!key || !(key in agents)) {
return '';
}
var current = navigator.userAgent;
var wow64 = current.indexOf('WOW64') >= 0;
var value = agents[key];
if (!wow64) {
value = value.replace(' WOW64;', '');
}
return value;
}
ActiveXConfig.convertVersion = function(setting) {
if (setting.version == 3) {
if (!setting.blocked) {
setting.blocked = [];
}
setting.__proto__ = ActiveXConfig.prototype;
return setting;
} else if (setting.version == 2) {
function parsePattern(pattern) {
pattern = pattern.trim();
var title = pattern.match(/###(.*)/);
if (title) {
return {
pattern: pattern.match(/(.*)###/)[1].trim(),
title: title[1].trim()
};
} else {
return {
pattern: pattern,
title: 'Rule'
};
}
}
var ret = new ActiveXConfig();
if (setting.logEnabled) {
ret.misc.logEnabled = true;
}
var urls = setting.url_plain.split('\n');
for (var i = 0; i < urls.length; ++i) {
var rule = ret.createRule();
var pattern = parsePattern(urls[i]);
rule.title = pattern.title;
var url = pattern.pattern;
if (url.substr(0, 2) == 'r/') {
rule.type = 'regex';
rule.value = url.substr(2);
} else {
rule.type = 'wild';
rule.value = url;
}
ret.addCustomRule(rule, 'convert');
}
var clsids = setting.trust_clsids.split('\n');
for (var i = 0; i < clsids.length; ++i) {
var rule = ret.createRule();
rule.type = 'clsid';
var pattern = parsePattern(clsids[i]);
rule.title = pattern.title;
rule.value = pattern.pattern;
ret.addCustomRule(rule, 'convert');
}
firstUpgrade = true;
return ret;
}
};
ActiveXConfig.prototype = {
// Only used for user-scripts
shouldEnable: function(object) {
if (this.pageRule) {
return this.pageRule;
}
var clsidRule = this.getFirstMatchedRule(object, this.clsidRules);
if (clsidRule) {
return clsidRule;
} else {
return null;
}
},
createRule: function() {
return {
title: 'Rule',
type: 'wild',
value: '',
userAgent: '',
scriptItems: ''
};
},
removeInvalidItems: function() {
if (this.pageSide) {
return;
}
function checkIdentifierMatches(item, prop) {
if (typeof item[prop] != 'object') {
console.log('reset ', prop);
item[prop] = {};
}
for (var i in item[prop]) {
var ok = true;
if (typeof item[prop][i] != 'object') {
ok = false;
}
if (ok && item[prop][i].identifier != i) {
ok = false;
}
if (!ok) {
console.log('remove corrupted item ', i, ' in ', prop);
delete item[prop][i];
}
}
}
checkIdentifierMatches(this, 'rules');
checkIdentifierMatches(this, 'defaultRules');
checkIdentifierMatches(this, 'scripts');
checkIdentifierMatches(this, 'issues');
var newOrder = [];
for (var i = 0; i < this.order.length; ++i) {
if (this.getItem(this.order[i])) {
newOrder.push(this.order[i]);
} else {
console.log('remove order item ', this.order[i]);
}
}
this.order = newOrder;
},
addCustomRule: function(newItem, auto) {
if (!this.validateRule(newItem)) {
return;
}
var identifier = this.createIdentifier();
newItem.identifier = identifier;
this.rules[identifier] = newItem;
this.order.push({
status: 'custom',
position: 'custom',
identifier: identifier
});
this.update();
trackAddCustomRule(newItem, auto);
},
updateDefaultRules: function(newRules) {
var deleteAll = false, ruleToDelete = {};
if (typeof this.defaultRules != 'object') {
// There might be some errors!
// Clear all defaultRules
console.log('Corrupted default rules, reload all');
deleteAll = true;
this.defaultRules = {};
} else {
for (var i in this.defaultRules) {
if (!(i in newRules)) {
console.log('Remove rule ' + i);
ruleToDelete[i] = true;
delete this.defaultRules[i];
}
}
}
var newOrder = [];
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].position == 'custom' ||
(!deleteAll && !ruleToDelete[this.order[i].identifier])) {
newOrder.push(this.order[i]);
}
}
this.order = newOrder;
var position = 0;
for (var i in newRules) {
if (!(i in this.defaultRules)) {
this.addDefaultRule(newRules[i], position);
position++;
}
this.defaultRules[i] = newRules[i];
}
},
loadDefaultConfig: function() {
var setting = this;
$.ajax({
url: '/settings/setting.json',
dataType: 'json',
success: function(nv, status, xhr) {
console.log('Update default rules');
setting.updateDefaultRules(nv);
setting.update();
}
});
$.ajax({
url: '/settings/scripts.json',
dataType: 'json',
success: function(nv, status, xhr) {
console.log('Update scripts');
setting.scripts = nv;
setting.loadAllScripts();
setting.update();
}
});
$.ajax({
url: '/settings/issues.json',
dataType: 'json',
success: function(nv, status, xhr) {
setting.issues = nv;
setting.update();
}
});
},
getPageConfig: function(href) {
var ret = {};
ret.pageSide = true;
ret.version = this.version;
ret.verbose = this.misc.verbose;
ret.logEnabled = this.misc.logEnabled;
ret.pageRule = this.getFirstMatchedRule({href: href});
if (!ret.pageRule) {
ret.clsidRules = this.cache.clsidRules;
} else {
var script = this.getScripts(ret.pageRule.script);
ret.pageScript = script.page;
ret.extScript = script.extension;
}
return ret;
},
getFirstMatchedRule: function(object, rules) {
var useCache = false;
if (!rules) {
rules = this.cache.validRules;
useCache = true;
}
if (Array.isArray(rules)) {
for (var i = 0; i < rules.length; ++i) {
if (this.isRuleMatched(rules[i], object, useCache ? i : -1)) {
return rules[i];
}
}
} else {
for (var i in rules) {
if (this.isRuleMatched(rules[i], object)) {
return rules[i];
}
}
}
return null;
},
getMatchedIssue: function(filter) {
return this.getFirstMatchedRule(filter, this.issues);
},
activeRule: function(rule) {
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].identifier == rule.identifier) {
if (this.order[i].status == 'disabled') {
this.order[i].status = 'enabled';
trackAutoEnable(rule.identifier);
}
break;
}
}
this.update();
},
validateRule: function(rule) {
var ret = true;
try {
if (rule.type == 'wild') {
ret &= this.convertUrlWildCharToRegex(rule.value) != null;
} else if (rule.type == 'regex') {
ret &= rule.value != '';
var r = new RegExp(rule.value, 'i');
} else if (rule.type == 'clsid') {
var v = rule.value.toUpperCase();
if (!clsidPattern.test(v) || v.length > 55)
ret = false;
}
} catch (e) {
ret = false;
}
return ret;
},
isRuleMatched: function(rule, object, id) {
if (rule.type == 'wild' || rule.type == 'regex') {
var regex;
if (id >= 0) {
regex = this.cache.regex[id];
} else if (rule.type == 'wild') {
regex = this.convertUrlWildCharToRegex(rule.value);
} else if (rule.type == 'regex') {
regex = new RegExp('^' + rule.value + '$', 'i');
}
if (object.href && regex.test(object.href)) {
return true;
}
} else if (rule.type == 'clsid') {
if (object.clsid) {
var v1 = clsidPattern.exec(rule.value.toUpperCase());
var v2 = clsidPattern.exec(object.clsid.toUpperCase());
if (v1 && v2 && v1[0] == v2[0]) {
return true;
}
}
}
return false;
},
getScripts: function(script) {
var ret = {
page: '',
extension: ''
};
if (!script) {
return ret;
}
var items = script.split(' ');
for (var i = 0; i < items.length; ++i) {
if (!items[i] || !this.scripts[items[i]]) {
continue;
}
var name = items[i];
var val = '// ';
val += items[i] + '\n';
val += this.scriptsContents[name];
val += '\n\n';
ret[this.scripts[name].context] += val;
}
return ret;
},
convertUrlWildCharToRegex: function(wild) {
try {
function escapeRegex(str, star) {
if (!star) star = '*';
var escapeChars = /([\.\\\/\?\{\}\+\[\]])/g;
return str.replace(escapeChars, '\\$1').replace('*', star);
}
wild = wild.toLowerCase();
if (wild == '<all_urls>') {
wild = '*://*/*';
}
var pattern = /^(.*?):\/\/(\*?[^\/\*]*)\/(.*)$/i;
// pattern: [all, scheme, host, page]
var parts = pattern.exec(wild);
if (parts == null) {
return null;
}
var scheme = parts[1];
var host = parts[2];
var page = parts[3];
var regex = '^' + escapeRegex(scheme, '[^:]*') + ':\\/\\/';
regex += escapeRegex(host, '[^\\/]*') + '/';
regex += escapeRegex(page, '.*');
return new RegExp(regex, 'i');
} catch (e) {
return null;
}
},
update: function() {
if (this.pageSide) {
return;
}
this.updateCache();
if (this.cache.listener) {
this.cache.listener.trigger('update');
}
this.save();
},
// Please remember to call update() after all works are done.
addDefaultRule: function(rule, position) {
console.log('Add new default rule: ', rule);
var custom = null;
if (rule.type == 'clsid') {
for (var i in this.rules) {
var info = {href: 'not-a-URL-/', clsid: rule.value};
if (this.isRuleMatched(this.rules[i], info, -1)) {
custom = this.rules[i];
break;
}
}
} else if (rule.keyword && rule.testUrl) {
// Try to find matching custom rule
for (var i in this.rules) {
if (this.isRuleMatched(this.rules[i], {href: rule.testUrl}, -1)) {
if (this.rules[i].value.toLowerCase().indexOf(rule.keyword) != -1) {
custom = this.rules[i];
break;
}
}
}
}
var newStatus = 'disabled';
if (custom) {
console.log('Convert custom rule', custom, ' to default', rule);
// Found a custom rule which is similiar to this default rule.
newStatus = 'enabled';
// Remove old one
delete this.rules[custom.identifier];
for (var i = 0; i < this.order.length; ++i) {
if (this.order[i].identifier == custom.identifier) {
this.order.splice(i, 1);
break;
}
}
}
this.order.splice(position, 0, {
position: 'default',
status: newStatus,
identifier: rule.identifier
});
this.defaultRules[rule.identifier] = rule;
},
updateCache: function() {
if (this.pageSide) {
return;
}
this.cache = {
validRules: [],
regex: [],
clsidRules: [],
userAgentRules: [],
listener: (this.cache || {}).listener
};
for (var i = 0; i < this.order.length; ++i) {
if (['custom', 'enabled'].indexOf(this.order[i].status) >= 0) {
var rule = this.getItem(this.order[i]);
var cacheId = this.cache.validRules.push(rule) - 1;
if (rule.type == 'clsid') {
this.cache.clsidRules.push(rule);
} else if (rule.type == 'wild') {
this.cache.regex[cacheId] =
this.convertUrlWildCharToRegex(rule.value);
} else if (rule.type == 'regex') {
this.cache.regex[cacheId] = new RegExp('^' + rule.value + '$', 'i');
}
if (rule.userAgent != '') {
this.cache.userAgentRules.push(rule);
}
}
}
},
save: function() {
if (location.protocol == 'chrome-extension:') {
// Don't include cache in localStorage.
var cache = this.cache;
delete this.cache;
var scripts = this.scriptsContents;
delete this.scriptsContents;
localStorage[settingKey] = JSON.stringify(this);
this.cache = cache;
this.scriptsContents = scripts;
}
},
createIdentifier: function() {
var base = 'custom_' + Date.now() + '_' + this.order.length + '_';
var ret;
do {
ret = base + Math.round(Math.random() * 65536);
} while (this.getItem(ret));
return ret;
},
getItem: function(item) {
var identifier = item;
if (typeof identifier != 'string') {
identifier = item.identifier;
}
if (identifier in this.rules) {
return this.rules[identifier];
} else {
return this.defaultRules[identifier];
}
},
loadAllScripts: function() {
this.scriptsContents = {};
setting = this;
for (var i in this.scripts) {
var item = this.scripts[i];
$.ajax({
url: '/settings/' + item.url,
datatype: 'text',
context: item,
success: function(nv, status, xhr) {
setting.scriptsContents[this.identifier] = nv;
}
});
}
}
};
function loadLocalSetting() {
var setting = undefined;
if (localStorage[settingKey]) {
try {
setting = JSON.parse(localStorage[settingKey]);
} catch (e) {
setting = undefined;
}
}
if (!setting) {
firstRun = true;
}
return new ActiveXConfig(setting);
}
function clearSetting() {
localStorage.removeItem(settingKey);
setting = loadLocalSetting();
}
| zzhongster-wxtlactivex | chrome/configure.js | JavaScript | mpl11 | 17,848 |
if (chrome.extension.getBackgroundPage().firstRun) {
document.getElementById('hint').style.display = '';
chrome.extension.getBackgroundPage().firstRun = false;
}
$(document).ready(function() {
$('#share').load('share.html');
});
| zzhongster-wxtlactivex | chrome/donate.js | JavaScript | mpl11 | 242 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var tabId = parseInt(location.href.replace(/.*tabid=([0-9]*).*/, '$1'));
if (isNaN(tabId)) {
alert('Invalid tab id');
}
var backgroundPage = chrome.extension.getBackgroundPage();
var tabInfo = backgroundPage.tabStatus[tabId];
var setting = backgroundPage.setting;
if (!tabInfo) {
alert('Cannot get tab tabInfo');
}
$(document).ready(function() {
$('.status').hide();
$('#submitissue').hide();
if (tabInfo.urldetect) {
$('#status_urldetect').show();
} else if (!tabInfo.count) {
// Shouldn't have this popup
} else if (tabInfo.error) {
$('#status_error').show();
} else if (tabInfo.count != tabInfo.actived) {
$('#status_disabled').show();
} else {
$('#status_ok').show();
$('#submitissue').show();
}
});
$(document).ready(function() {
$('#issue_view').hide();
if (tabInfo.error !== 0) {
var errorid = tabInfo.issueId;
var issue = setting.issues[errorid];
$('#issue_content').text(issue.description);
var url = issue.url;
if (!url) {
var issueUrl = 'http://code.google.com/p/np-activex/issues/detail?id=';
url = issueUrl + issue.issueId;
}
$('#issue_track').click(function() {
chrome.tabs.create({url: url});
window.close();
});
$('#issue_view').show();
}
});
function refresh() {
alert($$('refresh_needed'));
window.close();
}
function showEnableBtns() {
var list = $('#enable_btns');
list.hide();
if (tabInfo.urldetect || tabInfo.count > tabInfo.actived) {
list.show();
var info = {actived: true};
for (var i = 0; i < tabInfo.frames && info.actived; ++i) {
for (var j = 0; j < tabInfo.objs[i].length && info.actived; ++j) {
info = tabInfo.objs[i][j];
}
}
if (info.actived) {
return;
}
var rule = setting.getFirstMatchedRule(info, setting.defaultRules);
if (rule) {
var button = $('<button>').addClass('defaultRule');
button.text($$('enable_default_rule', rule.title));
button.click(function() {
setting.activeRule(rule);
refresh();
});
list.append(button);
} else {
var site = info.href.replace(/[^:]*:\/\/([^\/]*).*/, '$1');
var sitepattern = info.href.replace(/([^:]*:\/\/[^\/]*).*/, '$1/*');
var btn1 = $('<button>').addClass('customRule').
text($$('add_rule_site', site)).click(function() {
var rule = setting.createRule();
rule.type = 'wild';
rule.value = sitepattern;
setting.addCustomRule(rule, 'popup');
refresh();
});
var clsid = info.clsid;
var btn2 = $('<button>').addClass('customRule').
text($$('add_rule_clsid')).click(function() {
var rule = setting.createRule();
rule.type = 'clsid';
rule.value = clsid;
setting.addCustomRule(rule, 'popup');
refresh();
});
list.append(btn1).append(btn2);
}
}
}
$(document).ready(function() {
$('#submitissue').click(function() {
tabInfo.tracking = true;
alert($$('issue_submitting_desp'));
window.close();
});
});
$(document).ready(showEnableBtns);
| zzhongster-wxtlactivex | chrome/popup.js | JavaScript | mpl11 | 3,454 |
var setting = loadLocalSetting();
var updateSession = new ObjectWithEvent();
setting.cache.listener = updateSession;
startListener();
registerRequestListener();
// If you want to build your own copy with a different id, please keep the
// tracking enabled.
var default_id = 'lgllffgicojgllpmdbemgglaponefajn';
var debug = chrome.i18n.getMessage('@@extension_id') != default_id;
if (debug && firstRun) {
if (confirm('Debugging mode. Disable tracking?')) {
setting.misc.tracking = false;
setting.misc.logEnabled = true;
}
}
window.setTimeout(function() {
setting.loadDefaultConfig();
if (firstRun || firstUpgrade) {
open('donate.html');
}
}, 1000);
| zzhongster-wxtlactivex | chrome/background.js | JavaScript | mpl11 | 696 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"></meta>
<link rel="stylesheet" type="text/css" href="/popup.css" />
<script src="/jquery.js"></script>
<script src="/popup.js"></script>
<script src="/i18n.js"></script>
<script src="/gas.js"></script>
</head>
<body>
<div class="main">
<div>
<div id="status_ok" class="status">
<span i18n="status_ok"></span>
<button id="submitissue" i18n="submitissue"></button>
</div>
<div id="status_urldetect" class="status" i18n="status_urldetect"></div>
<div id="status_disabled" class="status" i18n="status_disabled"></div>
<div id="status_error" class="status" i18n="status_error"></div>
</div>
<div id="enable_btns">
</div>
<div id="issue_view">
<div i18n="issue_desp">
</div>
<div id="issue_content">
</div>
<div>
<a id="issue_track" i18n="issue_track" href="#"></a>
</div>
</div>
<script src="share.js"></script>
</div>
</body>
</html>
| zzhongster-wxtlactivex | chrome/popup.html | HTML | mpl11 | 1,145 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var controlLogFName = '__npactivex_log';
var controlLogEvent = '__npactivex_log_event__';
var config = null;
var port = null;
var logs = [];
var scriptConfig = {
none2block: false,
formid: false,
documentid: false
};
function onControlLog(event) {
var message = event.data;
log(message);
}
window.addEventListener(controlLogEvent, onControlLog, false);
function connect() {
if (port) {
return;
}
port = chrome.extension.connect();
for (var i = 0; i < logs.length; ++i) {
port.postMessage({command: 'Log', message: logs[i]});
}
if (port && config) {
logs = undefined;
}
}
function log(message) {
var time = (new Date()).toLocaleTimeString();
message = time + ' ' + message;
if (config && config.logEnabled) {
console.log(message);
}
if (port) {
port.postMessage({command: 'Log', message: message});
}
if (!config || !port) {
logs.push(message);
}
}
log('PageURL: ' + location.href);
var pendingObjects = [];
function init(response) {
config = new ActiveXConfig(response);
if (config.logEnabled) {
for (var i = 0; i < logs.length; ++i) {
console.log(logs[i]);
}
}
eval(config.extScript);
executeScript(config.pageScript);
setUserAgent();
log('Page rule:' + JSON.stringify(config.pageRule));
for (var i = 0; i < pendingObjects.length; ++i) {
pendingObjects[i].activex_process = false;
process(pendingObjects[i]);
cacheConfig();
}
delete pendingObjects;
}
function cacheConfig() {
sessionStorage.activex_config_cache = JSON.stringify(config);
}
function loadConfig(response) {
if (config) {
config = new ActiveXConfig(response);
var cache = sessionStorage.activex_config_cache;
if (cache) {
cacheConfig();
}
} else {
init(response);
}
if (config.pageRule) {
cacheConfig();
}
}
function loadSessionConfig() {
var cache = sessionStorage.activex_config_cache;
if (cache) {
log('Loading config from session cache');
init(JSON.parse(cache));
}
}
loadSessionConfig();
var notifyBar = null;
var pageDOMLoaded = false;
var needNotifyBar = false;
function showNotifyBar(request) {
if (notifyBar) {
return;
}
if (!pageDOMLoaded) {
needNotifyBar = true;
return;
}
notifyBar = {};
log('Create notification bar');
var barurl = chrome.extension.getURL('notifybar.html');
if (document.body.tagName == 'BODY') {
var iframe = document.createElement('iframe');
iframe.frameBorder = 0;
iframe.src = barurl;
iframe.height = '35px';
iframe.width = '100%';
iframe.style.top = '0px';
iframe.style.left = '0px';
iframe.style.zIndex = '2000';
iframe.style.position = 'fixed';
notifyBar.iframe = iframe;
document.body.insertBefore(iframe, document.body.firstChild);
var placeHolder = document.createElement('div');
placeHolder.style.height = iframe.height;
placeHolder.style.zIndex = '1999';
placeHolder.style.borderWidth = '0px';
placeHolder.style.borderStyle = 'solid';
placeHolder.style.borderBottomWidth = '1px';
document.body.insertBefore(placeHolder, document.body.firstChild);
notifyBar.placeHolder = placeHolder;
} else if (document.body.tagName == 'FRAMESET') {
// We can't do this..
return;
}
}
function dismissNotifyBar() {
if (!notifyBar || !notifyBar.iframe) {
return;
}
notifyBar.iframe.parentNode.removeChild(notifyBar.iframe);
notifyBar.placeHolder.parentNode.removeChild(notifyBar.placeHolder);
}
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (self == top && request.command == 'NotifyUser') {
showNotifyBar(request);
sendResponse({});
} else if (self == top && request.command == 'DismissNotificationPage') {
dismissNotifyBar();
sendResponse({});
}
});
chrome.extension.sendRequest(
{command: 'Configuration', href: location.href, top: self == top},
loadConfig);
window.addEventListener('beforeload', onBeforeLoading, true);
document.addEventListener('DOMSubtreeModified', onSubtreeModified, true);
| zzhongster-wxtlactivex | chrome/inject_start.js | JavaScript | mpl11 | 4,465 |
// Copyright (c) 2010 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var $$ = chrome.i18n.getMessage;
function loadI18n() {
var spans = document.querySelectorAll('[i18n]');
for (var i = 0; i < spans.length; ++i) {
var obj = spans[i];
v = $$(obj.getAttribute('i18n'));
if (v == '')
v = obj.getAttribute('i18n');
if (obj.tagName == 'INPUT') {
obj.value = v;
} else {
obj.innerText = v;
}
}
document.removeEventListener('DOMContentLoaded', loadI18n, false);
}
document.addEventListener('DOMContentLoaded', loadI18n, false);
| zzhongster-wxtlactivex | chrome/i18n.js | JavaScript | mpl11 | 704 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var backgroundPage = chrome.extension.getBackgroundPage();
var defaultTabId = parseInt(location.href.replace(/.*tabid=([0-9]*).*/, '$1'));
function insertTabInfo(tab) {
if (isNaN(defaultTabId)) {
defaultTabId = tab.id;
}
if (uls[tab.id]) {
return;
}
var ul = $('<ul>').appendTo($('#logs_items'));
uls[tab.id] = ul;
var title = tab.title;
if (!title) {
title = 'Tab ' + tab.id;
}
$('<a>').attr('href', '#')
.attr('tabid', tab.id)
.text(title)
.click(function(e) {
loadTabInfo(parseInt($(e.target).attr('tabid')));
}).appendTo(ul);
}
var uls = {};
$(document).ready(function() {
chrome.tabs.query({}, function(tabs) {
for (var i = 0; i < tabs.length; ++i) {
var protocol = tabs[i].url.replace(/(^[^:]*).*/, '$1');
if (protocol != 'http' && protocol != 'https' && protocol != 'file') {
continue;
}
insertTabInfo(tabs[i]);
}
for (var i in backgroundPage.tabStatus) {
insertTabInfo({id: i});
}
$('#tracking').change(function() {
var tabStatus = backgroundPage.tabStatus[currentTab];
if (tabStatus) {
tabStatus.tracking = tracking.checked;
}
});
loadTabInfo(defaultTabId);
});
});
$(document).ready(function() {
$('#beforeSubmit').click(function() {
var link = $('#submitLink');
if (beforeSubmit.checked) {
link.show();
} else {
link.hide();
}
});
});
var currentTab = -1;
function loadTabInfo(tabId) {
if (isNaN(tabId)) {
return;
}
if (tabId != currentTab) {
if (currentTab != -1) {
uls[currentTab].removeClass('selected');
}
currentTab = tabId;
uls[tabId].addClass('selected');
var s = backgroundPage.generateLogFile(tabId);
$('#text').val(s);
tracking.checked = backgroundPage.tabStatus[tabId].tracking;
}
}
| zzhongster-wxtlactivex | chrome/log.js | JavaScript | mpl11 | 2,108 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
function ObjectWithEvent() {
this._events = {};
}
ObjectWithEvent.prototype = {
bind: function(name, func) {
if (!Array.isArray(this._events[name])) {
this._events[name] = [];
}
this._events[name].push(func);
},
unbind: function(name, func) {
if (!Array.isArray(this._events[name])) {
return;
}
for (var i = 0; i < this._events[name].length; ++i) {
if (this._events[name][i] == func) {
this._events[name].splice(i, 1);
break;
}
}
},
trigger: function(name, argument) {
if (this._events[name]) {
var handlers = this._events[name];
for (var i = 0; i < handlers.length; ++i) {
handlers[i].apply(this, argument);
}
}
}
};
| zzhongster-wxtlactivex | chrome/ObjectWithEvent.js | JavaScript | mpl11 | 953 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"></meta>
<style>
.line {
clear: both;
margin: 4px 0px;
}
.item {
margin: 4px 3px;
float: left;
}
</style>
</head>
<body>
<div id="fb-root"></div>
<div class="line">
<div class="fb-like" data-href="https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn" data-send="true" data-width="450" data-show-faces="false"></div>
</div>
<div class="line">
<!-- Place this tag where you want the +1 button to render -->
<g:plusone annotation="inline" href="https://chrome.google.com/webstore/detail/lgllffgicojgllpmdbemgglaponefajn" expandTo="top"></g:plusone>
<!-- Place this render call where appropriate -->
</div>
<div class="line">
<div class="item">
<div id="weiboshare">
</div>
</div>
<div class="item">
<div id="renrenshare"></div>
<a id="xn_share" name="xn_share" type="icon_medium" href="#"></a>
</div>
<div class="item">
<a id="qqweibo" class="tmblog">
<img src="http://mat1.gtimg.com/app/opent/images/websites/share/weiboicon24.png" border="0" alt="转播到腾讯微博" />
</a>
</div>
<div class="item">
<iframe allowTransparency='true' id='like_view' frameborder='0' scrolling='no' marginheight='0' marginwidth='0' hspace='0' vspace='0' style='height:24px;width:65px;' src='http://www.kaixin001.com/like/like.php?url=https%3A%2F%2Fchrome.google.com%2Fwebstore%2Fdetail%2Flgllffgicojgllpmdbemgglaponefajn&show_faces=false'></iframe>
</div>
<div class="item">
<a id="doubanshare" href="#">
<img style="margin:auto" src="http://img2.douban.com/pics/fw2douban_s.png" alt="推荐到豆瓣" />
</a>
</div>
</div>
</body>
</html>
| zzhongster-wxtlactivex | chrome/share.html | HTML | mpl11 | 1,954 |
<script src="jquery.js" > </script>
<script src="i18n.js" > </script>
<script src="common.js" > </script>
<script src="ObjectWithEvent.js"> </script>
<script src="configure.js"> </script>
<script src="web.js"> </script>
<script src="gas.js"> </script>
<script src="background.js"></script>
| zzhongster-wxtlactivex | chrome/background.html | HTML | mpl11 | 298 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var config;
function loadConfig(_resp) {
config = _resp;
$(document).ready(init);
}
function openPopup() {
var url = chrome.extension.getURL('popup.html?tabid=' + config.tabId);
var windowConfig = 'height=380,width=560,toolbar=no,menubar=no,' +
'scrollbars=no,resizable=no,location=no,status=no';
window.open(url, 'popup', windowConfig);
dismiss();
}
function blockSite() {
chrome.extension.sendRequest(
{command: 'BlockSite', site: config.sitePattern});
dismiss();
}
function dismiss() {
chrome.extension.sendRequest({command: 'DismissNotification'});
}
function init() {
$('#enable').click(openPopup);
$('#close').click(dismiss);
$('#block').click(blockSite);
$('#close').text(config.closeMsg);
$('#enable').text(config.enableMsg);
$('#info').text(config.message);
$('#block').text(config.blockMsg);
}
chrome.extension.sendRequest({command: 'GetNotification'}, loadConfig);
| zzhongster-wxtlactivex | chrome/notifybar.js | JavaScript | mpl11 | 1,147 |
body {
background: -webkit-gradient(
linear, left top, left bottom, from(#feefae), to(#fee692));
margin: 0;
margin-top: 1px;
margin-left: 5px;
border-bottom-width: 1px;
overflow: hidden;
}
span {
word-break:keep-all;
white-space:nowrap;
overflow: hidden;
}
button {
background: -webkit-gradient(
linear, left top, left bottom, from(#fffbe9), to(#fcedb2));
height: 28px;
margin: 2px 3px;
border-radius: 3px;
border-width: 1px;
border-color: #978d60;
}
button:hover {
border-color: #4b4630;
}
| zzhongster-wxtlactivex | chrome/notifybar.css | CSS | mpl11 | 560 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
body {
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#CCF), color-stop(0.4, white), to(white)) no-repeat
}
#main {
margin: auto;
width: 600px;
}
#main > * {
clear: both;
margin: 30px;
}
#header {
text-align: center;
font-size: 30px;
}
#hint {
font-size: 20px;
border-color: red;
border-width: 2px;
border-style: dashed;
padding: 10px;
}
</style>
<script src="jquery.js"></script>
<script src="i18n.js"></script>
<script src="gas.js"></script>
<script src="donate.js"></script>
<title i18n="donate"></title>
</head>
<body>
<div id="main">
<div id="header">ActiveX for Chrome -- <span i18n="donate"></span></div>
<div i18n="donate_label"></div>
<div id="paymentoptions">
<form name="_xclick" target="_blank" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="qiuc12@gmail.com">
<input type="hidden" name="item_name" value="ActiveX for Chrome">
<input type="hidden" name="item_number" value="npax">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="notify_url" value="http://eagleonhill.oicp.net/editor/paypal.php">
<input type="hidden" name="charset" value="utf-8">
<input type="hidden" name="amount" value="">
<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donate_LG.gif" border="0" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
</form>
<a target="_blank" href="http://item.taobao.com/item.htm?id=18573312489" i18n="taobao_donate"></a>
</div>
<div><a target="_blank" href="http://code.google.com/p/np-activex/wiki/Donations" i18n="donate_record"></a></div>
<div></div>
<div i18n="donate_share">
</div>
<script src="share.js"></script>
<div></div>
<div id="hint" style="display:none">
<a id="hintonfirst" href="options.html" i18n="donate_gotooptions"></a>
</div>
</div>
</body>
</html>
| zzhongster-wxtlactivex | chrome/donate.html | HTML | mpl11 | 2,431 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
// Permission for experimental not given.
var handler = chrome.webRequest;
function onBeforeSendHeaders(details) {
var rule = setting.getFirstMatchedRule(
{href: details.url}, setting.cache.userAgent);
if (!rule || !(rule.userAgent in agents)) {
return {};
}
for (var i = 0; i < details.requestHeaders.length; ++i) {
if (details.requestHeaders[i].name == 'User-Agent') {
details.requestHeaders[i].value = agents[rule.userAgent];
break;
}
}
return {requestHeaders: details.requestHeaders};
}
function registerRequestListener() {
if (!handler) {
return;
}
var filters = {
urls: ['<all_urls>'],
types: ['main_frame', 'sub_frame', 'xmlhttprequest']
};
try {
handler.onBeforeSendHeaders.addListener(
onBeforeSendHeaders, filters, ['requestHeaders', 'blocking']);
} catch (e) {
console.log('Your browser doesn\'t support webRequest');
}
}
| zzhongster-wxtlactivex | chrome/web.js | JavaScript | mpl11 | 1,139 |
<html>
<head>
<title i18n="view_log"></title>
<script src="jquery.js"></script>
<script src="gas.js"></script>
<script src="i18n.js"></script>
<script src="log.js"></script>
<style>
#text {
width: 800px;
height: 500px;
}
div {
margin: 10px 0px;
}
body > div {
float:left;
}
#logs_items {
margin-top: 40px;
margin-right: 20px;
overflow-x: hidden;
overflow-y: scroll;
width: 300px;
height: 500px;
white-space: nowrap;
border-width: 1px;
border-style: solid;
}
ul.selected {
background-color: aqua;
}
</style>
</head>
<body>
<div id="left">
<div id="logs_items">
</div>
</div>
<div id="logs_show">
<div i18n="log">
</div>
<textarea id="text" wrap="off">
</textarea>
<div>
<input id="tracking" type="checkbox"></input>
<label for="tracking" i18n="log_tracking"></label>
</div>
<div>
<input id="beforeSubmit" type="checkbox"></input>
<label for="beforeSubmit" i18n="issue_submit_desp"></label>
<a id="submitLink" i18n="issue_submit_goto" style="margin-left:50px;display:none" href="http://code.google.com/p/np-activex/issues/entry?template=Defect%20report%20from%20log" target="_blank"></a>
</div>
</div>
</body>
</html>
| zzhongster-wxtlactivex | chrome/log.html | HTML | mpl11 | 1,496 |
body {
background-color: #ffd;
}
body > div {
margin: 10px;
max-width: 1000px;
}
#tbSetting {
width: 1000px;
height: 500px;
}
.itemline.newline:not(.editing) {
display:none;
}
div[property=status] {
width: 75px
}
div[property=title] {
width: 200px
}
div[property=type] {
width: 60px
}
div[property=value] {
width: 320px
}
div[property=userAgent] {
width: 80px
}
div[property=script] {
width: 350px
}
[property=status] button {
width: 70px;
}
#ruleCmds button {
width: 100px;
margin: 4px 8px 3px 8px;
}
#share {
float:left;
padding: 5px 0 0 40px;
height: 100px;
}
#footer * {
margin: 0 10px;
}
| zzhongster-wxtlactivex | chrome/options.css | CSS | mpl11 | 696 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
List.types.input = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input></input>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
this.label.click(function(e) {
setTimeout(function() {
input.focus();
}, 10);
});
this.input.focus(function(e) {
input.select();
});
this.input.keypress(function(e) {
p.trigger('change');
});
this.input.keyup(function(e) {
p.trigger('change');
});
this.input.change(function(e) {
p.trigger('change');
});
p.append(this.input).append(this.label);
};
List.types.input.prototype.__defineSetter__('value', function(val) {
this.input.val(val);
this.label.text(val);
});
List.types.input.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<select></select>').addClass('valinput');
this.label = $('<span></span>').addClass('valdisp');
if (prop.option == 'static') {
this.loadOptions(prop.options);
}
var select = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
select.value = select.lastval;
} else {
p.trigger('change');
}
});
this.label.click(function(e) {
setTimeout(function() {
input.focus();
}, 10);
});
p.append(this.input).append(this.label);
};
List.types.select.prototype.loadOptions = function(options) {
this.options = options;
this.mapping = {};
this.input.html('');
for (var i = 0; i < options.length; ++i) {
this.mapping[options[i].value] = options[i].text;
var o = $('<option></option>').val(options[i].value).text(options[i].text);
this.input.append(o);
}
};
List.types.select.prototype.__defineGetter__('value', function() {
return this.input.val();
});
List.types.select.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input.val(val);
this.label.text(this.mapping[val]);
});
List.types.checkbox = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<input type="checkbox">').addClass('valcheck');
var box = this;
this.input.change(function(e) {
if (p.hasClass('readonly')) {
box.value = box.lastval;
} else {
p.trigger('change');
}
});
p.append(this.input);
};
List.types.checkbox.prototype.__defineGetter__('value', function() {
return this.input[0].checked;
});
List.types.checkbox.prototype.__defineSetter__('value', function(val) {
this.lastval = val;
this.input[0].checked = val;
});
List.types.button = function(p, prop) {
p[0].listdata = this;
this.p = p;
var input = this.input = $('<button>');
if (prop.caption) {
input.text(prop.caption);
}
input.click(function(e) {
p.trigger('command');
return false;
});
p.append(this.input);
};
List.types.button.prototype.__defineGetter__('value', function() {
return undefined;
});
| zzhongster-wxtlactivex | chrome/listtypes.js | JavaScript | mpl11 | 3,299 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var USE_RECORD_GAP = 3 * 60 * 1000; // 3 minutes
var _gaq = window._gaq || [];
_gaq.push(['_setAccount', 'UA-28870762-4']);
_gaq.push(['_trackPageview', location.href.replace(/\?.*$/, '')]);
function initGAS() {
var setting = chrome.extension.getBackgroundPage().setting;
if (setting.misc.tracking) {
var ga = document.createElement('script');
ga.type = 'text/javascript'; ga.async = true;
ga.src = 'https://ssl.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
} else {
// dummy it. Non-debug && non-track
_gaq.push = function() {};
}
}
window.addEventListener('load', initGAS, false);
var useHistory = {};
var issueHistory = {};
function trackCheckSpan(history, item) {
var last = history[item];
if (last && Date.now() - last < USE_RECORD_GAP) {
return false;
}
history[item] = Date.now();
return true;
}
function trackIssue(issue) {
if (!trackCheckSpan(issueHistory, issue.identifier)) {
return;
}
_gaq.push(['_trackEvent', 'usage', 'error', '' + issue.identifier]);
}
function trackVersion(version) {
_gaq.push(['_trackEvent', 'option', 'version', version]);
}
function serializeRule(rule) {
return rule.type[0] + ' ' + rule.value;
}
function trackUse(identifier) {
if (!trackCheckSpan(useHistory, identifier)) {
return;
}
if (identifier.substr(0, 7) == 'custom_') {
var rule = setting.getItem(identifier);
_gaq.push(['_trackEvent', 'usage', 'use-custom', serializeRule(rule)]);
} else {
_gaq.push(['_trackEvent', 'usage', 'use', identifier]);
}
}
var urlHistory = {};
function trackNotUse(url) {
if (!trackCheckSpan(urlHistory, url)) {
return;
}
_gaq.push(['_trackEvent', 'usage', 'notuse', url]);
}
function trackDisable(identifier) {
_gaq.push(['_trackEvent', 'option', 'disable', identifier]);
}
function trackAutoEnable(identifier) {
_gaq.push(['_trackEvent', 'option', 'autoenable', identifier]);
}
function trackEnable(identifier) {
_gaq.push(['_trackEvent', 'option', 'enable', identifier]);
}
function trackAddCustomRule(rule, auto) {
var cmd = 'add';
if (auto) {
cmd = 'add-' + auto;
}
_gaq.push(['_trackEvent', 'option', cmd, serializeRule(rule)]);
}
function trackManualUpdate() {
_gaq.push(['_trackEvent', 'update', 'manual']);
}
function trackUpdateFile(url) {
_gaq.push(['_trackEvent', 'update', 'file', url]);
}
| zzhongster-wxtlactivex | chrome/gas.js | JavaScript | mpl11 | 2,718 |
body {
background-color: #ffd;
}
.main {
width: 500px;
height: 340px;
padding: 10px;
}
.status {
font-size: 18px;
margin: 0 20px;
}
#issue_view {
margin: 15px 10px;
}
#issue_view > div {
margin: 7px 0px;
}
#share {
position: absolute;
top: 250px;
left: 30px;
height: 90px;
}
button {
width: 350px;
height: 30px;
margin: 4px;
}
button.defaultRule {
background-color: #0A0;
}
button.customRule {
background-color: #aaf;
}
| zzhongster-wxtlactivex | chrome/popup.css | CSS | mpl11 | 507 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="/list.css" />
<link rel="stylesheet" type="text/css" href="/options.css" />
<script src="/jquery.js"></script>
<script src="/configure.js"></script>
<script src="/i18n.js"></script>
<script src="/list.js"></script>
<script src="/listtypes.js"></script>
<script src="/options.js"></script>
<script src="/gas.js"></script>
<title i18n="option_title"></title>
</head>
<body>
<div class="description">
<span i18n="option_help"></span>
<a class="help" i18n="help" target="_blank"></a>
<a href="donate.html" target="_blank" i18n="donate"></a>
</div>
<div id="tbSetting">
</div>
<div>
<div style="float:left">
<div id="ruleCmds">
<button id="addRule" i18n="add"></button>
<button id="deleteRule" i18n="delete"></button>
<button id="moveUp" i18n="moveUp"></button>
<button id="moveDown" i18n="moveDown"></button>
</div>
<div style="margin-top:15px">
<input id="log_enable" type="checkbox">
<span i18n="log_enable">
</span>
</input>
<input id="tracking" type="checkbox">
<span i18n="tracking">
</span>
</input>
</div>
</div>
<script src="share.js"></script>
</div>
<div id="footer" style="clear:both">
<span i18n="copyright">
</span>
<a href="donate.html" target="_blank" i18n="donate"></a>
<a class="help" i18n="help" target="_blank"></a>
<a href="log.html" i18n="view_log" target="_blank"></a>
<span id="follow">
<iframe width="136" height="24" frameborder="0" allowtransparency="true" marginwidth="0" marginheight="0" scrolling="no" border="0" src="http://widget.weibo.com/relationship/followbutton.php?language=zh_cn&width=136&height=24&uid=2356524070&style=2&btn=red&dpc=1"></iframe>
</span>
</div>
</body>
</html>
| zzhongster-wxtlactivex | chrome/options.html | HTML | mpl11 | 2,115 |
var Renren = Renren || {};
if(!Renren.share){
Renren.share = function() {
var isIE = navigator.userAgent.match(/(msie) ([\w.]+)/i);
var hl = location.href.indexOf('#');
var resUrl = (hl == -1 ? location.href : location.href.substr(0, hl));
var shareImgs = "";
var sl = function(str) {
var placeholder = new Array(23).join('x');
str = str
.replace(
/(https?|ftp|gopher|telnet|prospero|wais|nntp){1}:\/\/\w*[\u4E00-\u9FA5]*((?![\"| |\t|\r|\n]).)+/ig,
function(match) {
return placeholder + match.substr(171);
}).replace(/[^\u0000-\u00ff]/g, "xx");
return Math.ceil(str.length / 2);
};
var cssImport = function(){
var static_url = 'http://xnimg.cn/xnapp/share/css/v2/rrshare.css';
var b = document.createElement("link");
b.rel = "stylesheet";
b.type = "text/css";
b.href = static_url;
(document.getElementsByTagName("head")[0] || document.body).appendChild(b)
};
var getShareType = function (dom) {
return dom.getAttribute("type") || "button"
};
var opts = {};
if(typeof(imgMinWidth)!='undefined'){
opts.imgMinWidth = imgMinWidth || 60;
} else {
opts.imgMinWidth = 60;
}
if(typeof(imgMinHeight)!='undefined'){
opts.imgMinHeight = imgMinHeight || 60;
} else {
opts.imgMinHeight = 60;
}
var renderShareButton = function (btn,index) {
if(btn.rendered){
return;
}
btn.paramIndex = index;
var shareType = getShareType(btn).split("_");
var showType = shareType[0] == "icon" ? "icon" : "button";
var size = shareType[1] || "small";
var shs = "xn_share_"+showType+"_"+size;
var innerHtml = [
'<span class="xn_share_wrapper ',shs,'"></span>'
];
btn.innerHTML = innerHtml.join("");
btn.rendered = true;
};
var postTarget = function(opts) {
var form = document.createElement('form');
form.action = opts.url;
form.target = opts.target;
form.method = 'POST';
form.acceptCharset = "UTF-8";
for (var key in opts.params) {
var val = opts.params[key];
if (val !== null && val !== undefined) {
var input = document.createElement('textarea');
input.name = key;
input.value = val;
form.appendChild(input);
}
}
var hidR = document.getElementById('renren-root-hidden');
if (!hidR) {
hidR = document.createElement('div'), syl = hidR.style;
syl.positon = 'absolute';
syl.top = '-10000px';
syl.width = syl.height = '0px';
hidR.id = 'renren-root-hidden';
(document.body || document.getElementsByTagName('body')[0])
.appendChild(hidR);
}
hidR.appendChild(form);
try {
var cst = null;
if (isIE && document.charset.toUpperCase() != 'UTF-8') {
cst = document.charset;
document.charset = 'UTF-8';
}
form.submit();
} finally {
form.parentNode.removeChild(form);
if (cst) {
document.charset = cst;
}
}
};
var getCharSet = function(){
if(document.charset){
return document.charset.toUpperCase();
} else {
var metas = document.getElementsByTagName("meta");
for(var i=0;i < metas.length;i++){
var meta = metas[i];
var metaCharset = meta.getAttribute('charset');
if(metaCharset){
return meta.getAttribute('charset');
}
var metaContent = meta.getAttribute('content');
if(metaContent){
var contenxt = metaContent.toLowerCase();
var begin = contenxt.indexOf("charset=");
if(begin!=-1){
var end = contenxt.indexOf(";",begin+"charset=".length);
if(end != -1){
return contenxt.substring(begin+"charset=".length,end);
}
return contenxt.substring(begin+"charset=".length);
}
}
}
}
return '';
}
var charset = getCharSet();
var getParam = function (param){
param = param || {};
param.api_key = param.api_key || '';
param.resourceUrl = param.resourceUrl || resUrl;
param.title = param.title || '';
param.pic = param.pic || '';
param.description = param.description || '';
if(resUrl == param.resourceUrl){
param.images = param.images || shareImgs;//一般就是当前页面的分享,因此取当前页面的img
}
param.charset = param.charset || charset || '';
return param;
}
var onclick = function(data) {
var submitUrl = 'http://widget.renren.com/dialog/share';
var p = getParam(data);
var prm = [];
for (var i in p) {
if (p[i])
prm.push(i + '=' + encodeURIComponent(p[i]));
}
var url = submitUrl+"?" + prm.join('&'), maxLgh = (isIE ? 2048 : 4100), wa = 'width=700,height=650,left=0,top=0,resizable=yes,scrollbars=1';
if (url.length > maxLgh) {
window.open('about:blank', 'fwd', wa);
postTarget({
url : submitUrl,
target : 'fwd',
params : p
});
} else {
window.open(url, 'fwd', wa);
}
return false;
};
window["rrShareOnclick"] = onclick;
var init = function() {
if (Renren.share.isReady || document.readyState !== 'complete')
return;
var imgs = document.getElementsByTagName('img'), imga = [];
for (var i = 0; i < imgs.length; i++) {
if (imgs[i].width >= opts.imgMinWidth
&& imgs[i].height >= opts.imgMinHeight) {
imga.push(imgs[i].src);
}
}
window["rrShareImgs"] = imga;
if (imga.length > 0)
shareImgs = imga.join('|');
if (document.addEventListener) {
document.removeEventListener('DOMContentLoaded', init, false);
} else {
document.detachEvent('onreadystatechange', init);
}
cssImport();
var shareBtn = document.getElementsByName("xn_share");
var len = shareBtn?shareBtn.length:0;
for (var b = 0; b < len; b++) {
var a = shareBtn[b];
renderShareButton(a,b);
}
Renren.share.isReady = true;
};
if (document.readyState === 'complete') {
init();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', init, false);
window.addEventListener('load', init, false);
} else {
document.attachEvent('onreadystatechange', init);
window.attachEvent('onload', init);
}
};
}
| zzhongster-wxtlactivex | chrome/rrshare.js | JavaScript | mpl11 | 6,671 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var background = chrome.extension.getBackgroundPage();
var setting = background.setting;
var updateSession = background.updateSession;
function toggleRule(e) {
var line = e.data.line;
var index = line.attr('row');
var item = setting.order[index];
if (item.position == 'default') {
if (item.status == 'enabled') {
item.status = 'disabled';
trackDisable(item.identifier);
} else if (item.status == 'disabled') {
item.status = 'enabled';
trackEnable(item.identifier);
}
}
line.blur();
e.data.list.finishEdit(line);
e.data.list.updateLine(line);
save();
}
var settingProps = [{
header: '',
property: 'status',
type: 'button',
caption: '',
events: {
command: toggleRule,
update: setStatus,
createNew: setStatusNew
}
}, {
header: $$('title'),
property: 'title',
type: 'input'
}, {
header: $$('mode'),
property: 'type',
type: 'select',
option: 'static',
options: [
{value: 'wild', text: $$('WildChar')},
{value: 'regex', text: $$('RegEx')},
{value: 'clsid', text: $$('CLSID')}
]
}, {
header: $$('pattern'),
property: 'value',
type: 'input'
}, {
header: $$('user_agent'),
property: 'userAgent',
type: 'select',
option: 'static',
options: [
{value: '', text: 'Chrome'},
{value: 'ie9', text: 'MSIE9'},
{value: 'ie8', text: 'MSIE8'},
{value: 'ie7', text: 'MSIE7'},
{value: 'ff7win', text: 'Firefox 7'},
{value: 'ip5', text: 'iPhone'},
{value: 'ipad5', text: 'iPad'}
]
}, {
header: $$('helper_script'),
property: 'script',
type: 'input'
}
];
var table;
var dirty = false;
function save() {
dirty = true;
}
function doSave() {
if (dirty) {
dirty = false;
setting.update();
}
}
function setReadonly(e) {
var line = e.data.line;
var id = line.attr('row');
if (id < 0) {
return;
}
var order = setting.order[id];
var divs = $('.listvalue', line);
if (order.position != 'custom') {
divs.addClass('readonly');
} else {
divs.removeClass('readonly');
}
}
$(window).blur(doSave);
function refresh() {
table.refresh();
}
// Main setting
$(document).ready(function() {
table = new List({
props: settingProps,
main: $('#tbSetting'),
lineEvents: {
update: setReadonly
},
getItems: function() {
return setting.order;
},
getItemProp: function(i, prop) {
if (prop in setting.order[i]) {
return setting.order[i][prop];
}
return setting.getItem(setting.order[i])[prop];
},
setItemProp: function(i, prop, value) {
if (prop in setting.order[i]) {
setting.order[i][prop] = value;
} else {
setting.getItem(setting.order[i])[prop] = value;
}
},
defaultValue: setting.createRule(),
count: function() {
return setting.order.length;
},
insert: function(id, newItem) {
setting.addCustomRule(newItem);
this.move(setting.order.length - 1, id);
},
remove: function(id) {
if (setting.order[id].position != 'custom') {
return true;
}
var identifier = setting.order[id].identifier;
delete setting.rules[identifier];
setting.order.splice(id, 1);
},
validate: function(id, rule) {
return setting.validateRule(rule);
}
});
$(table).bind('updated', save);
$('#addRule').bind('click', function() {
table.editNewLine();
});
$(table).bind('select', function() {
var line = table.selectedLine;
if (line < 0) {
$('#moveUp').attr('disabled', 'disabled');
$('#moveDown').attr('disabled', 'disabled');
$('#deleteRule').attr('disabled', 'disabled');
} else {
if (line != 0) {
$('#moveUp').removeAttr('disabled');
} else {
$('#moveUp').attr('disabled', 'disabled');
}
if (line != setting.order.length - 1) {
$('#moveDown').removeAttr('disabled');
} else {
$('#moveDown').attr('disabled', 'disabled');
}
if (setting.order[line].position != 'custom') {
$('#deleteRule').attr('disabled', 'disabled');
} else {
$('#deleteRule').removeAttr('disabled');
}
}
});
$('#moveUp').click(function() {
var line = table.selectedLine;
table.move(line, line - 1, true);
});
$('#moveDown').click(function() {
var line = table.selectedLine;
table.move(line, line + 1, true);
});
$('#deleteRule').click(function() {
var line = table.selectedLine;
table.remove(line);
});
table.init();
updateSession.bind('update', refresh);
});
window.onbeforeunload = function() {
updateSession.unbind('update', refresh);
};
function setStatusNew(e) {
with (e.data) {
s = 'Custom';
color = '#33f';
$('button', line).text(s).css('background-color', color);
}
}
function setStatus(e) {
with (e.data) {
var id = line.attr('row');
var order = setting.order[id];
var rule = setting.getItem(order);
var s, color;
if (order.status == 'enabled') {
s = $$('Enabled');
color = '#0A0';
} else if (order.status == 'disabled') {
s = $$('Disabled');
color = 'indianred';
} else {
s = $$('Custom');
color = '#33f';
}
$('button', line).text(s).css('background-color', color);
}
}
function showTime(time) {
var never = 'Never';
if (time == 0) {
return never;
}
var delta = Date.now() - time;
if (delta < 0) {
return never;
}
function getDelta(delta) {
var sec = delta / 1000;
if (sec < 60) {
return [sec, 'second'];
}
var minute = sec / 60;
if (minute < 60) {
return [minute, 'minute'];
}
var hour = minute / 60;
if (hour < 60) {
return [hour, 'hour'];
}
var day = hour / 24;
return [day, 'day'];
}
var disp = getDelta(delta);
var v1 = Math.floor(disp[0]);
return v1 + ' ' + disp[1] + (v1 != 1 ? 's' : '') + ' ago';
}
$(document).ready(function() {
$('#log_enable').change(function(e) {
setting.misc.logEnabled = e.target.checked;
save();
})[0].checked = setting.misc.logEnabled;
$('#tracking').change(function(e) {
setting.misc.tracking = e.target.checked;
save();
})[0].checked = setting.misc.tracking;
});
$(document).ready(function() {
var help = 'http://code.google.com/p/np-activex/wiki/ExtensionHelp?wl=';
help = help + $$('wikicode');
$('.help').each(function() {
this.href = help;
});
});
$(window).load(function() {
if (background.firstUpgrade) {
background.firstUpgrade = false;
alert($$('upgrade_show'));
}
});
| zzhongster-wxtlactivex | chrome/options.js | JavaScript | mpl11 | 7,041 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
var FLASH_CLSID = '{d27cdb6e-ae6d-11cf-96b8-444553540000}';
var typeId = 'application/x-itst-activex';
var updating = false;
function executeScript(script) {
var scriptobj = document.createElement('script');
scriptobj.innerHTML = script;
var element = document.head || document.body ||
document.documentElement || document;
element.insertBefore(scriptobj, element.firstChild);
element.removeChild(scriptobj);
}
function checkParents(obj) {
var parent = obj;
var level = 0;
while (parent && parent.nodeType == 1) {
if (getComputedStyle(parent).display == 'none') {
var desp = obj.id + ' at level ' + level;
if (scriptConfig.none2block) {
parent.style.display = 'block';
parent.style.height = '0px';
parent.style.width = '0px';
log('Remove display:none for ' + desp);
} else {
log('Warning: Detected display:none for ' + desp);
}
}
parent = parent.parentNode;
++level;
}
}
function getLinkDest(url) {
if (typeof url != 'string') {
return url;
}
url = url.trim();
if (/^https?:\/\/.*/.exec(url)) {
return url;
}
if (url[0] == '/') {
if (url[1] == '/') {
return location.protocol + url;
} else {
return location.origin + url;
}
}
return location.href.replace(/\/[^\/]*$/, '/' + url);
}
var hostElement = null;
function enableobj(obj) {
updating = true;
// We can't use classid directly because it confuses the browser.
obj.setAttribute('clsid', getClsid(obj));
obj.removeAttribute('classid');
checkParents(obj);
var newObj = obj.cloneNode(true);
newObj.type = typeId;
// Remove all script nodes. They're executed.
var scripts = newObj.getElementsByTagName('script');
for (var i = 0; i < scripts.length; ++i) {
scripts[i].parentNode.removeChild(scripts[i]);
}
// Set codebase to full path.
var codebase = newObj.getAttribute('codebase');
if (codebase && codebase != '') {
newObj.setAttribute('codebase', getLinkDest(codebase));
}
newObj.activex_process = true;
obj.parentNode.insertBefore(newObj, obj);
obj.parentNode.removeChild(obj);
obj = newObj;
if (obj.id) {
var command = '';
if (obj.form && scriptConfig.formid) {
var form = obj.form.name;
command += 'document.all.' + form + '.' + obj.id;
command += ' = document.all.' + obj.id + ';\n';
log('Set form[obj.id]: form: ' + form + ', object: ' + obj.id);
}
// Allow access by document.obj.id
if (obj.id && scriptConfig.documentid) {
command += 'delete document.' + obj.id + ';\n';
command += 'document.' + obj.id + '=' + obj.id + ';\n';
}
if (command) {
executeScript(command);
}
}
log('Enabled object, id: ' + obj.id + ' clsid: ' + getClsid(obj));
updating = false;
return obj;
}
function getClsid(obj) {
if (obj.hasAttribute('clsid'))
return obj.getAttribute('clsid');
var clsid = obj.getAttribute('classid');
var compos = clsid.indexOf(':');
if (clsid.substring(0, compos).toLowerCase() != 'clsid')
return;
clsid = clsid.substring(compos + 1);
return '{' + clsid + '}';
}
function notify(data) {
connect();
data.command = 'DetectControl';
port.postMessage(data);
}
function process(obj) {
if (obj.activex_process)
return;
if (onBeforeLoading.caller == enableobj ||
onBeforeLoading.caller == process ||
onBeforeLoading.caller == checkParents) {
log('Nested onBeforeLoading ' + obj.id);
return;
}
if (obj.type == typeId) {
if (!config || !config.pageRule) {
// hack??? Deactive this object.
log('Deactive unexpected object ' + obj.outerHTML);
return true;
}
log('Found objects created by client scripts');
notify({
href: location.href,
clsid: clsid,
actived: true,
rule: config.pageRule.identifier
});
obj.activex_process = true;
return;
}
if ((obj.type != '' && obj.type != 'application/x-oleobject') ||
!obj.hasAttribute('classid'))
return;
if (getClsid(obj).toLowerCase() == FLASH_CLSID) {
return;
}
if (config == null) {
// Delay the process of this object.
// Hope config will be load soon.
log('Pending object ', obj.id);
pendingObjects.push(obj);
return;
}
obj.activex_process = true;
connect();
var clsid = getClsid(obj);
var rule = config.shouldEnable({href: location.href, clsid: clsid});
if (rule) {
obj = enableobj(obj);
notify({
href: location.href,
clsid: clsid,
actived: true,
rule: rule.identifier
});
} else {
notify({href: location.href, clsid: clsid, actived: false});
}
}
function replaceSubElements(obj) {
var s = obj.querySelectorAll('object[classid]');
if (obj.tagName == 'OBJECT' && obj.hasAttribute('classid')) {
s.push(obj);
}
for (var i = 0; i < s.length; ++i) {
process(s[i]);
}
}
function onBeforeLoading(event) {
var obj = event.target;
if (obj.nodeName == 'OBJECT') {
log('BeforeLoading ' + obj.id);
if (process(obj)) {
event.preventDefault();
}
}
}
function onError(event) {
var message = 'Error: ';
message += event.message;
message += ' at ';
message += event.filename;
message += ':';
message += event.lineno;
log(message);
return false;
}
function setUserAgent() {
if (!config.pageRule) {
return;
}
var agent = getUserAgent(config.pageRule.userAgent);
if (agent && agent != '') {
log('Set userAgent: ' + config.pageRule.userAgent);
var js = '(function(agent) {';
js += 'delete navigator.userAgent;';
js += 'navigator.userAgent = agent;';
js += 'delete navigator.appVersion;';
js += "navigator.appVersion = agent.substr(agent.indexOf('/') + 1);";
js += "if (agent.indexOf('MSIE') >= 0) {";
js += 'delete navigator.appName;';
js += 'navigator.appName = "Microsoft Internet Explorer";}})("';
js += agent;
js += '")';
executeScript(js);
}
}
function onSubtreeModified(e) {
if (updating) {
return;
}
if (e.nodeType == e.TEXT_NODE) {
return;
}
replaceSubElements(e.srcElement);
}
| zzhongster-wxtlactivex | chrome/inject_actions.js | JavaScript | mpl11 | 6,568 |
<html>
<head>
<script src="jquery.js"></script>
<script src="notifybar.js"> </script>
<script src="i18n.js"> </script>
<link rel="stylesheet" type="text/css" href="notifybar.css" />
</head>
<body>
<span>
<span id="info">ActiveX controls can be used on this site</span>
<button id="enable">Enable them now!</button>
<button id="block" style="font-size:0.8em">Don't notify me for this site</button>
<button id="close">Close</button>
</span>
</body>
</html>
| zzhongster-wxtlactivex | chrome/notifybar.html | HTML | mpl11 | 527 |
.list {
width: 800px;
height: 400px;
font-family: Arial, sans-serif;
overflow-x: hidden;
border: 3px solid #0D5995;
background-color: #0D5995;
padding: 1px;
padding-top: 10px;
border-top-left-radius: 15px;
border-top-right-radius: 15px;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
}
.listscroll {
overflow-x: scroll;
overflow-y: scroll;
background-color: white;
}
.listitems {
display: inline-block;
}
.listvalue, .header {
display: inline-block;
width: 80px;
margin: 0px 6px;
}
.headers {
background-color: transparent;
position: relative;
white-space: nowrap;
display: inline-block;
color:white;
padding: 5px 0px;
}
.header{
white-space: normal;
}
.itemline {
height: 32px;
}
.itemline:nth-child(odd) {
background-color: white;
}
.itemline:nth-child(even) {
background-color: whitesmoke;
}
.itemline.selected {
background-color: #aaa;
}
.itemline:hover {
background-color: #bbcee9
}
.itemline.error,
.itemline.error:hover {
background-color: salmon;
}
.itemline > div {
white-space: nowrap;
padding: 4px 0px 0 0;
}
.itemline.editing > div{
padding: 3px 0px 0 0;
}
.valdisp, .valinput {
background-color: transparent;
width: 100%;
display: block;
}
.listvalue {
overflow-x: hidden;
}
.itemline.editing .listvalue:not(.readonly) .valdisp {
display: none;
}
.valdisp {
font-size: 13px;
}
.itemline:not(.editing) .valinput,
.listvalue.readonly .valinput {
display: none;
}
.itemline :focus {
outline: none;
}
.valinput {
border:1px solid #aaa;
background-color: white;
padding: 3px;
margin: 0;
}
.itemline .valinput:focus {
outline-color: rgba(0, 128, 256, 0.5);
outline: 5px auto rgba(0, 128, 256, 0.5);
}
| zzhongster-wxtlactivex | chrome/list.css | CSS | mpl11 | 1,865 |
document.addEventListener('DOMContentLoaded', function() {
if (window.PocoUpload) {
document.all.PocoUpload.Document = document;
}
}, false); | zzhongster-wxtlactivex | chrome/settings/poco_upload.js | JavaScript | mpl11 | 149 |
scriptConfig.formid = true;
| zzhongster-wxtlactivex | chrome/settings/formid.js | JavaScript | mpl11 | 29 |
(function(proto) {
proto.__defineGetter__("classid", function() {
var clsid = this.getAttribute("clsid");
if (clsid == null) {
return "";
}
return "CLSID:" + clsid.substring(1, clsid.length - 1);
})
proto.__defineSetter__("classid", function(value) {
var e = document.createEvent('TextEvent');
e.initTextEvent(
'__npactivex_log_event__', false, false, window,
'edit clsid ' + value);
window.dispatchEvent(e);
var oldstyle = this.style.display;
this.style.display = "none";
var pos = value.indexOf(":");
this.setAttribute("clsid", "{" + value.substring(pos + 1) + "}");
this.setAttribute("type", "application/x-itst-activex");
this.style.display = oldstyle;
})
})(HTMLObjectElement.prototype)
| zzhongster-wxtlactivex | chrome/settings/clsid.js | JavaScript | mpl11 | 795 |
scriptConfig.none2block = true;
| zzhongster-wxtlactivex | chrome/settings/none2block.js | JavaScript | mpl11 | 33 |
<?php
file_put_contents($_POST['file'], $_POST['data']);
?>
| zzhongster-wxtlactivex | chrome/settings/upload.php | PHP | mpl11 | 65 |
(function () {
var hiddenDivId = "__hiddendiv_activex";
window.__proto__.ActiveXObject = function(progid) {
progid = progid.trim();
var e = document.createEvent('TextEvent');
e.initTextEvent(
'__npactivex_log_event__', false, false, window,
'Dynamic create ' + progid);
window.dispatchEvent(e);
if (progid == 'Msxml2.XMLHTTP' || progid == 'Microsoft.XMLHTTP')
return new XMLHttpRequest();
var hiddenDiv = document.getElementById(hiddenDivId);
if (!hiddenDiv) {
if (!document.body) return null;
hiddenDiv = document.createElement("div");
hiddenDiv.id = hiddenDivId;
hiddenDiv.setAttribute("style", "width:0px; height:0px");
document.body.insertBefore(hiddenDiv, document.body.firstChild)
}
var obj = document.createElement("object");
obj.setAttribute("type", "application/x-itst-activex");
obj.setAttribute("progid", progid);
obj.setAttribute("style", "width:0px; height:0px");
obj.setAttribute("dynamic", "");
hiddenDiv.appendChild(obj);
if (obj.object === undefined) {
throw new Error('Dynamic create failed ' + progid)
}
return obj.object
}
//console.log("ActiveXObject declared");
})();
| zzhongster-wxtlactivex | chrome/settings/dynamic.js | JavaScript | mpl11 | 1,221 |
window.addEventListener('load', function() {Exobud.URL = objMmInfo[0].mmUrl}, false); | zzhongster-wxtlactivex | chrome/settings/_tipzap_player.js | JavaScript | mpl11 | 85 |
//**************************************
//*** \u663e\u793a\u65e5\u5386
//**************************************
var bMoveable=true; //\u8bbe\u7f6e\u65e5\u5386\u662f\u5426\u53ef\u4ee5\u62d6\u52a8
var strFrame; //\u5b58\u653e\u65e5\u5386\u5c42\u7684HTML\u4ee3\u7801
document.writeln('<iframe src="javascript:false" id=meizzDateLayer frameborder=0 style="position: absolute; width: 176px; height: 187px; z-index: 9998; display: none"></iframe>');
strFrame='<style>';
strFrame+='.calData { border:1px solid #a9a9a9; margin:0px; padding:0px; font-family:Verdana, Arial, Helvetica, sans-serif; }';
strFrame+='.calDay {font-decoration: none; font-family: arial; font-size: 12px; color: #000000; background-color: #F8F8F8;}';
strFrame+='.calHeadZh{font-size: 12px; color:#A50031}';
strFrame+='.calHead{font-size: 9px; color:#A50031}';
strFrame+='</style>';
strFrame+='<scr' + 'ipt>';
strFrame+='var datelayerx,datelayery; /*\u5b58\u653e\u65e5\u5386\u63a7\u4ef6\u7684\u9f20\u6807\u4f4d\u7f6e*/';
strFrame+='var bDrag; /*\u6807\u8bb0\u662f\u5426\u5f00\u59cb\u62d6\u52a8*/';
strFrame+='function document.onmousemove() /*\u5728\u9f20\u6807\u79fb\u52a8\u4e8b\u4ef6\u4e2d\uff0c\u5982\u679c\u5f00\u59cb\u62d6\u52a8\u65e5\u5386\uff0c\u5219\u79fb\u52a8\u65e5\u5386*/';
strFrame+='{if(bDrag && window.event.button==1)';
strFrame+=' {var DateLayer=parent.document.all.meizzDateLayer.style;';
strFrame+=' DateLayer.posLeft += window.event.clientX-datelayerx;/*\u7531\u4e8e\u6bcf\u6b21\u79fb\u52a8\u4ee5\u540e\u9f20\u6807\u4f4d\u7f6e\u90fd\u6062\u590d\u4e3a\u521d\u59cb\u7684\u4f4d\u7f6e\uff0c\u56e0\u6b64\u5199\u6cd5\u4e0ediv\u4e2d\u4e0d\u540c*/';
strFrame+=' DateLayer.posTop += window.event.clientY-datelayery;}}';
strFrame+='function DragStart() /*\u5f00\u59cb\u65e5\u5386\u62d6\u52a8*/';
strFrame+='{var DateLayer=parent.document.all.meizzDateLayer.style;';
strFrame+=' datelayerx=window.event.clientX;';
strFrame+=' datelayery=window.event.clientY;';
strFrame+=' bDrag=true;}';
strFrame+='function DragEnd(){ /*\u7ed3\u675f\u65e5\u5386\u62d6\u52a8*/';
strFrame+=' bDrag=false;}';
strFrame+='</scr' + 'ipt>';
strFrame+='<div style="z-index:9999;position: absolute; left:0; top:0;" onselectstart="return false"><span id=tmpSelectYearLayer style="z-index: 9999;position: absolute;top: 3; left: 19;display: none"></span>';
strFrame+='<span id=tmpSelectMonthLayer style="z-index: 9999;position: absolute;top: 3; left: 110;display: none"></span>';
strFrame+='<table border=1 class="calData" cellspacing=0 cellpadding=0 width=172 height=160 bordercolor=#cecece bgcolor=#ff9900>';
strFrame+=' <tr><td width=172 height=23 bgcolor=#FFFFFF><table border=0 cellspacing=1 cellpadding=0 width=172 height=23>';
strFrame+=' <tr align=center><td width=16 align=center bgcolor=#ffffff style="font-size:12px;cursor: hand;color: #A50031" ';
strFrame+=' onclick="parent.meizzPrevY()"><b><</b>';
strFrame+=' </td><td width=60 align=center style="font-size:12px;cursor:default" ';
strFrame+='onmouseover="style.backgroundColor=\'#cecece\'" onmouseout="style.backgroundColor=\'white\'" ';
strFrame+='onclick="parent.tmpSelectYearInnerHTML(this.innerText.substring(0,4))"><span id=meizzYearHead></span></td>';
strFrame+=' <td width=16 bgcolor=#ffffff align=center style="font-size:12px;cursor: hand;color: #A50031" ';
strFrame+=' onclick="parent.meizzNextY()"><b>></b></td>';
strFrame+='<td width=16 align=center bgcolor=#ffffff style="font-size:12px;cursor: hand;color: #A50031" onclick="parent.meizzPrevM()" title="\u5411\u524d\u7ffb 1 \u6708" ><b><</b></td>';
strFrame+='<td width=48 align=center style="font-size:12px;cursor:default" onmouseover="style.backgroundColor=\'#cecece\'" ';
strFrame+=' onmouseout="style.backgroundColor=\'white\'" onclick="parent.tmpSelectMonthInnerHTML(this.innerText)"';
strFrame+=' ><span id=meizzMonthHead ></span></td>';
strFrame+=' <td width=16 bgcolor=#ffffff align=center style="font-size:12px;cursor: hand;color: #A50031" ';
strFrame+=' onclick="parent.meizzNextM()"><b>></b></td></tr>';
strFrame+=' </table></td></tr>';
strFrame+=' <tr><td width=142 height=18>';
strFrame+='<table border=1 id="calHeadTable" cellspacing=0 cellpadding=0 bgcolor=#cecece ' + (bMoveable? 'onmousedown="DragStart()" onmouseup="DragEnd()"':'');
strFrame+=' BORDERCOLORLIGHT=#ffffff BORDERCOLORDARK=#ffffff width=172 height=20 style="cursor:' + (bMoveable ? 'move':'default') + '">';
strFrame+='<tr align=center valign=bottom><td>' + calDayArr[0] + '</td>';
strFrame+='<td>' + calDayArr[1] + '</td><td>' + calDayArr[2] + '</td>';
strFrame+='<td>' + calDayArr[3] + '</td><td>' + calDayArr[4] + '</td>';
strFrame+='<td>' + calDayArr[5] + '</td><td>' + calDayArr[6] + '</td></tr>';
strFrame+='</table></td></tr>';
strFrame+=' <tr><td width=142 height=120>';
strFrame+=' <table border=1 cellspacing=2 cellpadding=0 BORDERCOLORLIGHT=#ffffff BORDERCOLORDARK=#FFFFFF bgcolor=#ffffff width=172 height=120>';
var n=0; for (j=0;j<5;j++){ strFrame+= ' <tr align=center>'; for (i=0;i<7;i++){
strFrame+='<td width=20 height=20 id=meizzDay'+n+' class="calDay" onclick=parent.meizzDayClick(this.innerText,0)></td>';n++;}
strFrame+='</tr>';}
strFrame+=' <tr align=center>';
for (i=35;i<39;i++)strFrame+='<td width=20 height=20 id=meizzDay'+i+' class="calDay" onclick="parent.meizzDayClick(this.innerText,0)"></td>';
strFrame+=' <td colspan=3 align=right ><span onclick=parent.closeLayer() style="font-size:12px;cursor: hand;color: #A50031"';
strFrame+=' ><b>×</b></span></td></tr>';
strFrame+=' </table></td></tr>';
strFrame+='</table></div>';
window.frames.meizzDateLayer.document.writeln(strFrame);
window.frames.meizzDateLayer.document.close(); //\u89e3\u51b3ie\u8fdb\u5ea6\u6761\u4e0d\u7ed3\u675f\u7684\u95ee\u9898
//==================================================== WEB \u9875\u9762\u663e\u793a\u90e8\u5206 ======================================================
var outObject;
var outButton; //\u70b9\u51fb\u7684\u6309\u94ae
var outDate=""; //\u5b58\u653e\u5bf9\u8c61\u7684\u65e5\u671f
var odatelayer=window.frames.meizzDateLayer.document.all; //\u5b58\u653e\u65e5\u5386\u5bf9\u8c61
var yearPeriod = 12;
function showCalendar()
{
switch (arguments.length)
{
/** \u5982\u679c\u53c2\u6570\u4e2a\u6570\u4e3a2,\u8c03\u7528\u76f8\u5e94\u51fd\u6570\u5904\u7406 */
case 2:
showCalendarDeal(arguments[0],arguments[1]);
break;
/** \u5982\u679c\u53c2\u6570\u4e2a\u6570\u4e3a4,\u8c03\u7528\u76f8\u5e94\u51fd\u6570\u5904\u7406 */
case 3:
yearPeriod = arguments[2];
showCalendarDeal(arguments[0],arguments[1]);
break;
default:
showCalendarDeal(arguments[0],arguments[1]);
break;
}
}
function showCalendarDeal(tt,obj) //\u4e3b\u8c03\u51fd\u6570
{
if (arguments.length > 2){alert("\u5bf9\u4e0d\u8d77!\u4f20\u5165\u672c\u63a7\u4ef6\u7684\u53c2\u6570\u592a\u591a!");return;}
if (arguments.length == 0){alert("\u5bf9\u4e0d\u8d77!\u60a8\u6ca1\u6709\u4f20\u56de\u672c\u63a7\u4ef6\u4efb\u4f55\u53c2\u6570!");return;}
if (calLanguage == "zhCN")
odatelayer.calHeadTable.className = "calHeadZh";
else
odatelayer.calHeadTable.className = "calHead";
var dads = document.all.meizzDateLayer.style;
var th = tt;
var ttop = tt.offsetTop; //TT\u63a7\u4ef6\u7684\u5b9a\u4f4d\u70b9\u9ad8
var thei = tt.clientHeight; //TT\u63a7\u4ef6\u672c\u8eab\u7684\u9ad8
var tleft = tt.offsetLeft; //TT\u63a7\u4ef6\u7684\u5b9a\u4f4d\u70b9\u5bbd
var ttyp = tt.type; //TT\u63a7\u4ef6\u7684\u7c7b\u578b
while (tt = tt.offsetParent){ttop+=tt.offsetTop; tleft+=tt.offsetLeft;}
dads.top = (ttyp=="image")? ttop+thei : ttop+thei+6;
dads.left = tleft;
outObject = (arguments.length == 1) ? th : obj;
outButton = (arguments.length == 1) ? null : th; //\u8bbe\u5b9a\u5916\u90e8\u70b9\u51fb\u7684\u6309\u94ae
//\u6839\u636e\u5f53\u524d\u8f93\u5165\u6846\u7684\u65e5\u671f\u663e\u793a\u65e5\u5386\u7684\u5e74\u6708
var reg = /^(\d{4})\/(\d{1,2})\/(\d{1,2})$/;
var r = outObject.value.match(reg);
if(r!=null)
{
r[2]=r[2]-1;
var d= new Date(r[1], r[2],r[3]);
if(d.getFullYear()==r[1] && d.getMonth()==r[2] && d.getDate()==r[3])
{
outDate = d; //\u4fdd\u5b58\u5916\u90e8\u4f20\u5165\u7684\u65e5\u671f
meizzSetDay(r[1],r[2]+1);
}
else
{
outDate = "";
meizzSetDay(new Date().getFullYear(), new Date().getMonth() + 1);
}
}
else
{
outDate="";
meizzSetDay(new Date().getFullYear(), new Date().getMonth() + 1);
}
dads.display = '';
event.returnValue=false;
}
var MonHead = new Array(12); //\u5b9a\u4e49\u9633\u5386\u4e2d\u6bcf\u4e2a\u6708\u7684\u6700\u5927\u5929\u6570
MonHead[0] = 31; MonHead[1] = 28; MonHead[2] = 31; MonHead[3] = 30; MonHead[4] = 31; MonHead[5] = 30;
MonHead[6] = 31; MonHead[7] = 31; MonHead[8] = 30; MonHead[9] = 31; MonHead[10] = 30; MonHead[11] = 31;
var meizzTheYear=new Date().getFullYear(); //\u5b9a\u4e49\u5e74\u7684\u53d8\u91cf\u7684\u521d\u59cb\u503c
var meizzTheMonth=new Date().getMonth()+1; //\u5b9a\u4e49\u6708\u7684\u53d8\u91cf\u7684\u521d\u59cb\u503c
var meizzWDay=new Array(39); //\u5b9a\u4e49\u5199\u65e5\u671f\u7684\u6570\u7ec4
function document.onclick() //\u4efb\u610f\u70b9\u51fb\u65f6\u5173\u95ed\u8be5\u63a7\u4ef6 //ie6\u7684\u60c5\u51b5\u53ef\u4ee5\u7531\u4e0b\u9762\u7684\u5207\u6362\u7126\u70b9\u5904\u7406\u4ee3\u66ff
{
with(window.event)
{
if (srcElement.getAttribute("Author")==null && srcElement != outObject && srcElement != outButton)
closeLayer();
}
}
function document.onkeyup() //\u6309Esc\u952e\u5173\u95ed\uff0c\u5207\u6362\u7126\u70b9\u5173\u95ed
{
if (window.event.keyCode==27){
if(outObject)outObject.blur();
closeLayer();
}
else if(document.activeElement)
if(document.activeElement.getAttribute("Author")==null && document.activeElement != outObject && document.activeElement != outButton)
{
closeLayer();
}
}
function meizzWriteHead(yy,mm) //\u5f80 head \u4e2d\u5199\u5165\u5f53\u524d\u7684\u5e74\u4e0e\u6708
{
odatelayer.meizzYearHead.innerText = yy + calYear;
odatelayer.meizzMonthHead.innerText = calMonthArr[mm - 1];
}
function tmpSelectYearInnerHTML(strYear) //\u5e74\u4efd\u7684\u4e0b\u62c9\u6846
{
if (strYear.match(/\D/)!=null) return;//{alert("\u5e74\u4efd\u8f93\u5165\u53c2\u6570\u4e0d\u662f\u6570\u5b57!");return;}
var m = (strYear) ? strYear : new Date().getFullYear();
// var m = new Date().getFullYear();
if (m < 1000 || m > 9999) return;//{alert("\u5e74\u4efd\u503c\u4e0d\u5728 1000 \u5230 9999 \u4e4b\u95f4!");return;}
//xulc modify
var n = m - yearPeriod/2;
if (n < 1000) n = 1000;
if (n + 10 > 9999) n = 9974;
var s = "<select name=tmpSelectYear style='font-size: 12px' "
s += "onblur='document.all.tmpSelectYearLayer.style.display=\"none\"' "
s += "onchange='document.all.tmpSelectYearLayer.style.display=\"none\";"
s += "parent.meizzTheYear = this.value; parent.meizzSetDay(parent.meizzTheYear,parent.meizzTheMonth)'>\r\n";
var selectInnerHTML = s;
for (var i = n; i < n + yearPeriod; i++)
{
if (i == m)
{selectInnerHTML += "<option value='" + i + "' selected>" + i + "</option>\r\n";}
else {selectInnerHTML += "<option value='" + i + "'>" + i + "</option>\r\n";}
}
selectInnerHTML += "</select>";
odatelayer.tmpSelectYearLayer.style.display="";
odatelayer.tmpSelectYearLayer.innerHTML = selectInnerHTML;
odatelayer.tmpSelectYear.focus();
}
function tmpSelectMonthInnerHTML(strMonth) //\u6708\u4efd\u7684\u4e0b\u62c9\u6846
{
for(var i = 0; i < calMonthArr.length; i++)
{
if (calMonthArr[i] == strMonth)
{
strMonth = String(i + 1);
break;
}
}
if (strMonth.match(/\D/)!=null) return;//{alert("\u6708\u4efd\u8f93\u5165\u53c2\u6570\u4e0d\u662f\u6570\u5b57!");return;}
var m = (strMonth) ? strMonth : new Date().getMonth() + 1;
var s = "<select name=tmpSelectMonth style='font-size: 12px' "
s += "onblur='document.all.tmpSelectMonthLayer.style.display=\"none\"' "
s += "onchange='document.all.tmpSelectMonthLayer.style.display=\"none\";"
s += "parent.meizzTheMonth = this.value; parent.meizzSetDay(parent.meizzTheYear,parent.meizzTheMonth)'>\r\n";
var selectInnerHTML = s;
for (var i = 1; i < 13; i++)
{
if (i == m)
{selectInnerHTML += "<option value='"+i+"' selected>"+calMonthArr[i-1]+"</option>\r\n";}
else {selectInnerHTML += "<option value='"+i+"'>"+calMonthArr[i-1]+"</option>\r\n";}
}
selectInnerHTML += "</select>";
odatelayer.tmpSelectMonthLayer.style.display="";
odatelayer.tmpSelectMonthLayer.innerHTML = selectInnerHTML;
odatelayer.tmpSelectMonth.focus();
}
function closeLayer() //\u8fd9\u4e2a\u5c42\u7684\u5173\u95ed
{
document.all.meizzDateLayer.style.display="none";
}
function IsPinYear(year) //\u5224\u65ad\u662f\u5426\u95f0\u5e73\u5e74
{
if (0==year%4&&((year%100!=0)||(year%400==0))) return true;else return false;
}
function GetMonthCount(year,month) //\u95f0\u5e74\u4e8c\u6708\u4e3a29\u5929
{
var c=MonHead[month-1];if((month==2)&&IsPinYear(year)) c++;return c;
}
function GetDOW(day,month,year) //\u6c42\u67d0\u5929\u7684\u661f\u671f\u51e0
{
var dt=new Date(year,month-1,day).getDay()/7; return dt;
}
function meizzPrevY() //\u5f80\u524d\u7ffb Year
{
if(meizzTheYear > 999 && meizzTheYear <10000){meizzTheYear--;}
else return;//{alert("\u5e74\u4efd\u8d85\u51fa\u8303\u56f4\uff081000-9999\uff09!");}
meizzSetDay(meizzTheYear,meizzTheMonth);
}
function meizzNextY() //\u5f80\u540e\u7ffb Year
{
if(meizzTheYear > 999 && meizzTheYear <10000){meizzTheYear++;}
else return;//{alert("\u5e74\u4efd\u8d85\u51fa\u8303\u56f4\uff081000-9999\uff09!");}
meizzSetDay(meizzTheYear,meizzTheMonth);
}
function meizzToday() //Today Button
{
var today;
meizzTheYear = new Date().getFullYear();
meizzTheMonth = new Date().getMonth()+1;
today=new Date().getDate();
//meizzSetDay(meizzTheYear,meizzTheMonth);
if(outObject){
outObject.value=meizzTheYear + "-" + meizzTheMonth + "-" + today;
}
closeLayer();
}
function meizzPrevM() //\u5f80\u524d\u7ffb\u6708\u4efd
{
if(meizzTheMonth>1){meizzTheMonth--}else{meizzTheYear--;meizzTheMonth=12;}
meizzSetDay(meizzTheYear,meizzTheMonth);
}
function meizzNextM() //\u5f80\u540e\u7ffb\u6708\u4efd
{
if(meizzTheMonth==12){meizzTheYear++;meizzTheMonth=1}else{meizzTheMonth++}
meizzSetDay(meizzTheYear,meizzTheMonth);
}
function meizzSetDay(yy,mm) //\u4e3b\u8981\u7684\u5199\u7a0b\u5e8f**********
{
meizzWriteHead(yy,mm);
//\u8bbe\u7f6e\u5f53\u524d\u5e74\u6708\u7684\u516c\u5171\u53d8\u91cf\u4e3a\u4f20\u5165\u503c
meizzTheYear=yy;
meizzTheMonth=mm;
for (var i = 0; i < 39; i++){meizzWDay[i]=""}; //\u5c06\u663e\u793a\u6846\u7684\u5185\u5bb9\u5168\u90e8\u6e05\u7a7a
var day1 = 1,day2=1,firstday = new Date(yy,mm-1,1).getDay(); //\u67d0\u6708\u7b2c\u4e00\u5929\u7684\u661f\u671f\u51e0
for (i=0;i<firstday;i++)meizzWDay[i]=GetMonthCount(mm==1?yy-1:yy,mm==1?12:mm-1)-firstday+i+1 //\u4e0a\u4e2a\u6708\u7684\u6700\u540e\u51e0\u5929
for (i = firstday; day1 < GetMonthCount(yy,mm)+1; i++){meizzWDay[i]=day1;day1++;}
for (i=firstday+GetMonthCount(yy,mm);i<39;i++){meizzWDay[i]=day2;day2++}
for (i = 0; i < 39; i++)
{ var da = eval("odatelayer.meizzDay"+i) //\u4e66\u5199\u65b0\u7684\u4e00\u4e2a\u6708\u7684\u65e5\u671f\u661f\u671f\u6392\u5217
if (meizzWDay[i]!="")
{
//\u521d\u59cb\u5316\u8fb9\u6846
da.borderColorLight="#ffffff";
da.borderColorDark="#FFFFFF";
if(i<firstday) //\u4e0a\u4e2a\u6708\u7684\u90e8\u5206
{
da.innerHTML="<b><font color=gray>" + meizzWDay[i] + "</font></b>";
da.title=(mm==1?12:mm-1) +" / " + meizzWDay[i];
da.onclick=Function("meizzDayClick(this.innerText,-1)");
if(!outDate)
da.style.backgroundColor = ((mm==1?yy-1:yy) == new Date().getFullYear() &&
(mm==1?12:mm-1) == new Date().getMonth()+1 && meizzWDay[i] == new Date().getDate()) ?
"#A50031":"#efefef";//\u4e0a\u6708\u90e8\u5206\u7684\u80cc\u666f\u8272
else
{
da.style.backgroundColor =((mm==1?yy-1:yy)==outDate.getFullYear() && (mm==1?12:mm-1)== outDate.getMonth() + 1 &&
meizzWDay[i]==outDate.getDate())? "#ffffff" :
(((mm==1?yy-1:yy) == new Date().getFullYear() && (mm==1?12:mm-1) == new Date().getMonth()+1 &&
meizzWDay[i] == new Date().getDate()) ? "#A50031":"#ffffff");//\u9009\u4e2d\u4e0a\u6708\u672c\u5468\u65e5\u671f\u6846\u548c\u989c\u8272\u80cc\u666f
//\u5c06\u9009\u4e2d\u7684\u65e5\u671f\u663e\u793a\u4e3a\u51f9\u4e0b\u53bb
if((mm==1?yy-1:yy)==outDate.getFullYear() && (mm==1?12:mm-1)== outDate.getMonth() + 1 &&
meizzWDay[i]==outDate.getDate())
{
da.borderColorLight="#FFFFFF";
da.borderColorDark="#FF9900";
}
}
}
else if (i>=firstday+GetMonthCount(yy,mm)) //\u4e0b\u4e2a\u6708\u7684\u90e8\u5206
{
da.innerHTML="<b><font color=gray>" + meizzWDay[i] + "</font></b>";
da.title=(mm==12?1:mm+1) +" / " + meizzWDay[i];
da.onclick=Function("meizzDayClick(this.innerText,1)");
if(!outDate)
da.style.backgroundColor = ((mm==12?yy+1:yy) == new Date().getFullYear() &&
(mm==12?1:mm+1) == new Date().getMonth()+1 && meizzWDay[i] == new Date().getDate()) ?
"#A50031":"#efefef";//\u4e0b\u6708\u90e8\u5206\u7684\u80cc\u666f\u8272
else
{
da.style.backgroundColor =((mm==12?yy+1:yy)==outDate.getFullYear() && (mm==12?1:mm+1)== outDate.getMonth() + 1 &&
meizzWDay[i]==outDate.getDate())? "#ffffff" :
(((mm==12?yy+1:yy) == new Date().getFullYear() && (mm==12?1:mm+1) == new Date().getMonth()+1 &&
meizzWDay[i] == new Date().getDate()) ? "#A50031":"#ffffff");
//\u5c06\u9009\u4e2d\u7684\u65e5\u671f\u663e\u793a\u4e3a\u51f9\u4e0b\u53bb
if((mm==12?yy+1:yy)==outDate.getFullYear() && (mm==12?1:mm+1)== outDate.getMonth() + 1 &&
meizzWDay[i]==outDate.getDate())
{
da.borderColorLight="#FFFFFF";
da.borderColorDark="#A50031";
}
}
}
else //\u672c\u6708\u7684\u90e8\u5206
{
da.innerHTML="<b>" + meizzWDay[i] + "</b>";
da.title=mm + " / " + meizzWDay[i];
da.onclick=Function("meizzDayClick(this.innerText,0)"); //\u7ed9td\u8d4b\u4e88onclick\u4e8b\u4ef6\u7684\u5904\u7406
//\u5982\u679c\u662f\u5f53\u524d\u9009\u62e9\u7684\u65e5\u671f\uff0c\u5219\u663e\u793a\u4eae\u84dd\u8272\u7684\u80cc\u666f\uff1b\u5982\u679c\u662f\u5f53\u524d\u65e5\u671f\uff0c\u5219\u663e\u793a\u6697\u9ec4\u8272\u80cc\u666f
if(!outDate)
{
if (yy == new Date().getFullYear() && mm == new Date().getMonth()+1 && meizzWDay[i] == new Date().getDate())
{
da.style.backgroundColor = "#A10333";
da.style.color = "#ffffff";
}
else
{
da.style.color = "#000000";
da.style.backgroundColor = "#ffffff";
}
}
else
{
if (yy==outDate.getFullYear() && mm== outDate.getMonth() + 1 && meizzWDay[i]==outDate.getDate())
{
da.style.backgroundColor = "#A10333";
da.style.color = "#ffffff";
}
else
{
da.style.color = "#000000";
da.style.backgroundColor = "#ffffff";
}
//\u5c06\u9009\u4e2d\u7684\u65e5\u671f\u663e\u793a\u4e3a\u51f9\u4e0b\u53bb
if(yy==outDate.getFullYear() && mm== outDate.getMonth() + 1 && meizzWDay[i]==outDate.getDate())
{
da.borderColorLight="#ffffff";
da.borderColorDark="#A50031";
}
}
}
da.style.cursor="hand"
}
else{da.innerHTML="";da.style.backgroundColor="";da.style.cursor="default"}
}
}
function meizzDayClick(n,ex) //\u70b9\u51fb\u663e\u793a\u6846\u9009\u53d6\u65e5\u671f\uff0c\u4e3b\u8f93\u5165\u51fd\u6570*************
{
var yy=meizzTheYear;
var mm = parseInt(meizzTheMonth)+ex; //ex\u8868\u793a\u504f\u79fb\u91cf\uff0c\u7528\u4e8e\u9009\u62e9\u4e0a\u4e2a\u6708\u4efd\u548c\u4e0b\u4e2a\u6708\u4efd\u7684\u65e5\u671f
//\u5224\u65ad\u6708\u4efd\uff0c\u5e76\u8fdb\u884c\u5bf9\u5e94\u7684\u5904\u7406
if(mm<1){
yy--;
mm=12+mm;
}
else if(mm>12){
yy++;
mm=mm-12;
}
if (mm < 10){mm = "0" + mm;}
if (outObject)
{
if (!n) {//outObject.value="";
return;}
if ( n < 10){n = "0" + n;}
outObject.value= yy + "/" + mm + "/" + n ; //\u6ce8\uff1a\u5728\u8fd9\u91cc\u4f60\u53ef\u4ee5\u8f93\u51fa\u6539\u6210\u4f60\u60f3\u8981\u7684\u683c\u5f0f
closeLayer();
}
else {closeLayer();}// alert("\u60a8\u6240\u8981\u8f93\u51fa\u7684\u63a7\u4ef6\u5bf9\u8c61\u5e76\u4e0d\u5b58\u5728!");}
}
//**************************************
//*** \u663e\u793a\u65e5\u5386\u7ed3\u675f
//**************************************
| zzhongster-wxtlactivex | chrome/settings/_boc_calendar.js | JavaScript | mpl11 | 20,717 |
(function(node) {
node.createPopup = node.createPopup || function() {
var SetElementStyles = function(element, styleDict) {
var style = element.style;
for (var styleName in styleDict) {
style[styleName] = styleDict[styleName];
}
}
var eDiv = document.createElement('div');
SetElementStyles(eDiv, {
'position': 'absolute',
'top': 0 + 'px',
'left': 0 + 'px',
'width': 0 + 'px',
'height': 0 + 'px',
'zIndex': 1000,
'display': 'none',
'overflow': 'hidden'
});
eDiv.body = eDiv;
eDiv.write = function(string) {
eDiv.innerHTML += string;
}
var opened = false;
var setOpened = function(b) {
opened = b;
}
var getOpened = function() {
return opened;
}
var getCoordinates = function(oElement) {
var coordinates = {
x: 0,
y: 0
};
while (oElement) {
coordinates.x += oElement.offsetLeft;
coordinates.y += oElement.offsetTop;
oElement = oElement.offsetParent;
}
return coordinates;
}
return {
htmlTxt: '',
document: eDiv,
isOpen: getOpened(),
isShow: false,
hide: function() {
SetElementStyles(eDiv, {
'top': 0 + 'px',
'left': 0 + 'px',
'width': 0 + 'px',
'height': 0 + 'px',
'display': 'none'
});
eDiv.innerHTML = '';
this.isShow = false;
},
show: function(iX, iY, iWidth, iHeight, oElement) {
if (!getOpened()) {
document.body.appendChild(eDiv);
setOpened(true);
};
this.htmlTxt = eDiv.innerHTML;
if (this.isShow) {
this.hide();
};
eDiv.innerHTML = this.htmlTxt;
var coordinates = getCoordinates(oElement);
eDiv.style.top = (iX + coordinates.x) + 'px';
eDiv.style.left = (iY + coordinates.y) + 'px';
eDiv.style.width = iWidth + 'px';
eDiv.style.height = iHeight + 'px';
eDiv.style.display = 'block';
this.isShow = true;
}
}
}
})(window.__proto__);
| zzhongster-wxtlactivex | chrome/settings/popup.js | JavaScript | mpl11 | 2,138 |
/**
* \u521b\u5efa\u5b89\u5168\u63a7\u4ef6\u811a\u672c
*/
var rs = "";
function CreateControl(DivID, Form, ObjectID, mode, language) {
var d = document.getElementById(DivID);
var obj = document.createElement('object');
d.appendChild(obj);
obj.width = 162;
obj.height = 20;
obj.classid="clsid:E61E8363-041F-455c-8AD0-8A61F1D8E540";
obj.id=ObjectID;
var version = getVersion(obj);
passInit(obj, mode, language, version);
var rc = null;
if (version >= 66816) { //66560 1.4.0.0 //66306 1.3.0.2 //66305 1.3.0.1 //65539 1.3.0
getRS();
if (rs != "") {
obj.RandomKey_S = rs;
rc = obj.RandomKey_C;
}
}
return rc;
}
/**
* \u53d6\u63a7\u4ef6\u7248\u672c\u53f7
*/
function getVersion(obj) {
try {
var version = obj.Version;
try {
if (version == undefined)
return 0;
} catch(ve) {//IE5.0
return 0;
}
return version;
}
catch(e) {
return 0;
}
}
/**
* \u53d6rs
*/
function getRS() {
if (rs == "") {
url = "refreshrs.do";
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if(xmlhttp) {
xmlhttp.open("POST", url, false);
xmlhttp.send();
rs = xmlhttp.responseText;
if (rs == null) {
alert("Control rs error.");
rs = "";
}
else {
rs = rs.replace(/[ \t\r\n]/g, "");
if (rs.length != 24) {
alert("Control rs error:" + rs.length);
rs = "";
}
}
}
}
}
/**
* \u53d6\u63a7\u4ef6\u7248\u72b6\u6001
*/
function getState(obj) {
try {
var state = obj.State;
try {
if (state == undefined)
return 0;
} catch(ve) {//IE5.0
return 0;
}
return state;
}
catch(e) {
return 0;
}
}
/**
* \u63a7\u4ef6\u68c0\u6d4b
*/
function passControlCheck(obj, mode, language) {
try {
var version = getVersion(obj);
passInit(obj, mode, language, version);
if (version < 65539) {//66560 1.4.0.0 //66306 1.3.0.2 //66305 1.3.0.1 //65539 1.3.0
alert(SAFECONTROL_VERSION);
return false;
}
}
catch(e) {
alert(SAFECONTROL_INSTALL);
return false;
}
return true;
}
/**
* \u8bbe\u7f6e\u63a7\u4ef6
*/
function passInit(obj, mode, language, version) {
obj.SetLanguage(language);
//\u53e3\u4ee4
if (mode == 0) {
obj.PasswordIntensityMinLength = 1;
obj.MaxLength = 20;
obj.OutputValueType = 2;
obj.PasswordIntensityRegularExpression = "^[!-~]*$";
}
//\u65b0\u53e3\u4ee4
else if (mode == 1) {
obj.PasswordIntensityMinLength = 8;
obj.MaxLength = 20;
obj.OutputValueType = 2;
obj.PasswordIntensityRegularExpression = "(^[!-~]*[A-Za-z]+[!-~]*[0-9]+[!-~]*$)|(^[!-~]*[0-9]+[!-~]*[A-Za-z]+[!-~]*$)";
}
//\u52a8\u6001\u53e3\u4ee4
else if (mode == 2) {
obj.PasswordIntensityMinLength = 6;
obj.MaxLength = 6;
obj.OutputValueType = 1;
obj.PasswordIntensityRegularExpression = "^[0-9]{6}$";
}
//\u7535\u8bdd\u94f6\u884c\u5bc6\u7801
else if (mode == 3) {
obj.PasswordIntensityMinLength = 6;
obj.MaxLength = 6;
obj.OutputValueType = 1;
obj.PasswordIntensityRegularExpression = "^[0-9]{6}$";
}
//\u624b\u673a\u94f6\u884c\u5bc6\u7801
else if (mode == 4) {
obj.PasswordIntensityMinLength = 8;
obj.MaxLength = 20;
obj.OutputValueType = 1;
obj.PasswordIntensityRegularExpression = "^[!-~]*$";
}
}
| zzhongster-wxtlactivex | chrome/settings/_boc_createElement.js | JavaScript | mpl11 | 3,150 |
//**************************************
//*** \u4ee5\u4e0b\u51fd\u6570\u662f\u9875\u9762\u9650\u5236\u51fd\u6570
//**************************************
/**
* \u9875\u9762\u9650\u5236\u5f00\u5173
* true -- \u5f00\u53d1\u6a21\u5f0f\uff0c\u9875\u9762\u4e0d\u505a\u9650\u5236
* false -- \u8fd0\u8425\u6a21\u5f0f\uff0c\u9875\u9762\u9650\u5236
*/
var codingMode = false;
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u5c4f\u853d\u53f3\u952e
*/
function click(e)
{
/** \u8868\u793aIE */
if (document.all)
{
if (event.button != 1)
{
oncontextmenu='return false';
}
}
/** \u8868\u793aNC */
if (document.layers)
{
if (e.which == 3)
{
oncontextmenu='return false';
}
}
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u5f53\u952e\u76d8\u952e\u88ab\u6309\u4e0b\u65f6\uff0c\u5c4f\u853d\u67d0\u4e9b\u952e\u548c\u7ec4\u5408\u952e
*/
function limitKey(e)
{
/** \u8868\u793aNC,\u6ce8\u610f\uff1a\u9700\u6d4b\u8bd5 */
if (document.layers)
{
if (e.which == 17)
{
alert("\u64cd\u4f5c\u9519\u8bef.\u6216\u8bb8\u662f\u60a8\u6309\u9519\u4e86\u6309\u952e!");
}
/** \u5c4f\u853d Alt(18)+ \u65b9\u5411\u952e \u2192 Alt+ \u65b9\u5411\u952e \u2190 */
if (e.which == 18 && (e.which==37 || e.which == 39))
{
alert("\u4e0d\u51c6\u4f60\u4f7f\u7528ALT+\u65b9\u5411\u952e\u524d\u8fdb\u6216\u540e\u9000\u7f51\u9875\uff01");
e.returnValue=false;
}
/** \u5c4f\u853d F5(116) \u5237\u65b0\u952eCtrl(17) + R(82) */
if (e.which == 116 || (e.which == 17 && e.which==82))
{
e.which=0;
e.returnValue=false;
}
/** \u5c4f\u853dTab(9) \u5c4f\u853dF11(122) \u5c4f\u853d Ctrl+n(78) \u5c4f\u853d shift(16)+F10(121) */
if (e.which == 9 || e.which == 122 || (e.which == 17 && e.which==78) || (e.which == 16 && e.which==121))
{
e.which=0;
e.returnValue=false;
}
}
/** \u8868\u793aIE */
if (document.all)
{
/** \u5c4f\u853d Alt+ \u65b9\u5411\u952e \u2192 Alt+ \u65b9\u5411\u952e \u2190 */
if (window.event.altKey && (window.event.keyCode==37 || window.event.keyCode == 39))
{
alert("\u4e0d\u51c6\u4f60\u4f7f\u7528ALT+\u65b9\u5411\u952e\u524d\u8fdb\u6216\u540e\u9000\u7f51\u9875\uff01");
event.returnValue=false;
}
/** \u5c4f\u853d F5(116) \u5237\u65b0\u952eCtrl + R(82) */
if (window.event.keyCode == 116 || (window.event.ctrlKey && window.event.keyCode==82))
{
event.keyCode=0;
event.returnValue=false;
}
/** \u5c4f\u853dEnter(13) */
if (window.event.keyCode==13 && typeof(openEnterFlag)=='undefined' )
/** openEnterFlag\u662f\u5728JSP\u4e2d\u6253\u5f00Enter\u7684\u5f00\u5173\u3002\u76ee\u524d\u5e94\u7528\u7684\u5c31\u53ea\u6709\u7559\u8a00\u677f\u9875\u9762 */
/** \u4f7f\u7528\u65b9\u6cd5\uff1a\u5728\u9700\u8981\u6253\u5f00Enter\u7684\u9875\u9762tiles:insert\u524d\u5b9a\u4e49\u53d8\u91cfopenEnterFlag\u5373\u53ef */
{
//alert("pagelimt 13");
event.keyCode=0;
event.returnValue=false;
}
/** \u5c4f\u853dF11(122) \u5c4f\u853d Ctrl+n(78) \u5c4f\u853d shift+F10(121) */
if (window.event.keyCode == 122 || (window.event.ctrlKey && window.event.keyCode==78) || (window.event.shiftKey && window.event.keyCode==121))
{
event.keyCode=0;
event.returnValue=false;
}
/** \u5c4f\u853d Ctrl + A(65) Ctrl + C(67) Ctrl + X(86) Ctrl + V(88) modify by jinj BOCNET-1769,\u653e\u5f00Ctrl + C,Ctrl + V*/
if (window.event.ctrlKey && (window.event.keyCode==65 || window.event.keyCode == 88))
{
event.keyCode=0;
event.returnValue=false;
}
if (window.event.srcElement.tagName == "A" && window.event.shiftKey)
window.event.returnValue = false; //\u5c4f\u853d shift \u52a0\u9f20\u6807\u5de6\u952e\u65b0\u5f00\u4e00\u7f51\u9875
}
}
if (!codingMode)
{
if (document.layers)
{
document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown=click;
document.oncontextmenu = new Function("return false;");
if (document.layers)
document.captureEvents(Event.KEYDOWN);
document.onkeydown=limitKey;
}
//**************************************
//*** \u9875\u9762\u9650\u5236\u51fd\u6570\u7ed3\u675f
//**************************************
| zzhongster-wxtlactivex | chrome/settings/_boc_PageLimit.js | JavaScript | mpl11 | 4,667 |
(function (doc) {
doc.createElement = function(orig) {
return function(name) {
if (name.trim()[0] == '<') {
// We assume the name is correct.
document.head.innerHTML += name;
var obj = document.head.lastChild;
document.head.removeChild(obj);
return obj;
} else {
var val = orig.call(this, name);
if (name == "object") {
val.setAttribute("type", "application/x-itst-activex");
}
return val;
}
}
}(doc.createElement);
})(HTMLDocument.prototype);
| zzhongster-wxtlactivex | chrome/settings/createElement.js | JavaScript | mpl11 | 556 |
(function() {
function reload() {
var maps = document.getElementsByTagName("map");
for (var i = 0; i < maps.length; ++i) {
if (maps[i].name == "") maps[i].name = maps[i].id;
}
}
if (document.readyState == 'complete') {
reload();
} else {
window.addEventListener('load', reload, false);
}
})(); | zzhongster-wxtlactivex | chrome/settings/map_id_name.js | JavaScript | mpl11 | 329 |
//************************************/
//******* \u5b9a\u4e49\u6240\u6709JS\u63d0\u793a\u8bed *******/
//************************************/
/** CurCode\u8d27\u5e01\u5217\u8868 begin */
var CURCODE_CNY = "\u4eba\u6c11\u5e01\u5143";
var CURCODE_GBP = "\u82f1\u9551";
var CURCODE_HKD = "\u6e2f\u5e01";
var CURCODE_USD = "\u7f8e\u5143";
var CURCODE_CHF = "\u745e\u58eb\u6cd5\u90ce";
var CURCODE_DEM = "\u5fb7\u56fd\u9a6c\u514b";
var CURCODE_FRF = "\u6cd5\u56fd\u6cd5\u90ce";
var CURCODE_SGD = "\u65b0\u52a0\u5761\u5143";
var CURCODE_NLG = "\u8377\u5170\u76fe";
var CURCODE_SEK = "\u745e\u5178\u514b\u90ce";
var CURCODE_DKK = "\u4e39\u9ea6\u514b\u90ce";
var CURCODE_NOK = "\u632a\u5a01\u514b\u90ce";
var CURCODE_ATS = "\u5965\u5730\u5229\u5148\u4ee4";
var CURCODE_BEF = "\u6bd4\u5229\u65f6\u6cd5\u90ce";
var CURCODE_ITL = "\u610f\u5927\u5229\u91cc\u62c9";
var CURCODE_JPY = "\u65e5\u5143";
var CURCODE_CAD = "\u52a0\u62ff\u5927\u5143";
var CURCODE_AUD = "\u6fb3\u5927\u5229\u4e9a\u5143";
var CURCODE_EUR = "\u6b27\u5143";
var CURCODE_IDR = "\u5370\u5c3c\u76fe";
var CURCODE_MOP = "\u6fb3\u95e8\u5143";
var CURCODE_PHP = "\u83f2\u5f8b\u5bbe\u6bd4\u7d22";
var CURCODE_THB = "\u6cf0\u56fd\u94e2";
var CURCODE_NZD = "\u65b0\u897f\u5170\u5143";
var CURCODE_KRW = "\u97e9\u5143";
var CURCODE_XSF = "\u8bb0\u8d26\u745e\u58eb\u6cd5\u90ce";
//edit by zhangfeng
var CURCODE_VND = "\u8d8a\u5357\u76fe";
var CURCODE_IDR = "\u5370\u5c3c\u76fe";
//edit by liangd
var CURCODE_AED = "\u963f\u8054\u914b\u8fea\u62c9\u59c6";
var CURCODE_ARP = "\u963f\u6839\u5ef7\u6bd4\u7d22";
var CURCODE_BRL = "\u96f7\u4e9a\u5c14";
var CURCODE_EGP = "\u57c3\u53ca\u78c5";
var CURCODE_INR = "\u5370\u5ea6\u5362\u6bd4";
var CURCODE_JOD = "\u7ea6\u65e6\u7b2c\u7eb3\u5c14";
var CURCODE_MNT = "\u8499\u53e4\u56fe\u683c\u91cc\u514b";
var CURCODE_MYR = "\u9a6c\u6765\u897f\u4e9a\u6797\u5409\u7279";
var CURCODE_NGN = "\u5c3c\u65e5\u5229\u4e9a\u5948\u62c9";
var CURCODE_ROL = "\u7f57\u9a6c\u5c3c\u4e9a\u5217\u4f0a";
var CURCODE_TRL = "\u571f\u8033\u5176\u91cc\u62c9";
var CURCODE_UAH = "\u4e4c\u514b\u5170\u683c\u91cc\u592b\u7eb3";
var CURCODE_ZAR = "\u5357\u975e\u5170\u7279";
//edit by cuiyk
var CURCODE_RUR = "\u5362\u5e03";
var CURCODE_HUF = "\u798f\u6797";
var CURCODE_KZT = "\u54c8\u8428\u514b\u65af\u5766\u575a\u6208";
var CURCODE_ZMK = "\u8d5e\u6bd4\u4e9a\u514b\u74e6\u67e5";
var CURCODE_XPT = "\u767d\u91d1";
var CURCODE_BND = "\u6587\u83b1\u5e01";
var CURCODE_BWP = "\u535a\u8328\u74e6\u7eb3\u666e\u62c9";
//added by hhf.2009.9.10 modify by cuiyk 2009.11.10
var CURCODE_XAU="\u9ec4\u91d1(\u76ce\u53f8)";
var CURCODE_GLD="\u9ec4\u91d1(\u514b)";
/** CurCode\u8d27\u5e01\u5217\u8868 end */
/** FormCheck\u8868\u5355\u68c0\u67e5 begin */
var COMMA_MSG = "\uff0c";
var ENTER_MSG = "\n";
var NOT_NULL = "\u4e0d\u80fd\u4e3a\u7a7a\uff0c\u8bf7\u4fee\u6539\uff01";
var ILLEGAL_REGEX = "\u4e0d\u7b26\u5408\u8f93\u5165\u683c\u5f0f\uff0c\u8bf7\u4fee\u6539\uff01";
var ILLEGAL_CHAR = "\u6570\u636e\u542b\u4e86\u975e\u6cd5\u5b57\u7b26\uff1a[]^$\\~@#%&<>{}:'\"\uff0c\u8bf7\u4fee\u6539\uff01";
var HAVE_CHINESE = "\u6570\u636e\u542b\u4e86\u4e2d\u6587\u6216\u5176\u4ed6\u975e\u6807\u51c6\u5b57\u7b26\uff0c\u8bf7\u4fee\u6539\uff01";
var NOT_ONLY_CHINESE = "\u6570\u636e\u542b\u4e86\u4e2d\u6587\u4ee5\u5916\u7684\u5176\u4ed6\u5b57\u7b26\uff0c\u8bf7\u4fee\u6539\uff01";
var NOT_NUMBER = "\u6570\u636e\u5305\u542b\u4e86\u963f\u62c9\u4f2f\u6570\u5b57\u4ee5\u5916\u7684\u5b57\u7b26\uff0c\u8bf7\u4fee\u6539\uff01";
var NOT_PHONE_NUMBER = "\u6570\u636e\u5305\u542b\u4e86\u7535\u8bdd\u53f7\u7801\u4ee5\u5916\u7684\u5176\u4ed6\u5b57\u7b26\uff0c\u8bf7\u4fee\u6539\uff01";
var LENGTH_MSG = "\u7684\u957f\u5ea6\u5fc5\u987b\u5c0f\u4e8e\u7b49\u4e8e";
var LENGTH_EQUAL_MSG = "\u7684\u957f\u5ea6\u5fc5\u987b\u4e3a";
var LENGTH_MSG1 = "\u4e2a\u82f1\u6587\u5b57\u7b26\uff08\u4e00\u4e2a\u6c49\u5b57\u5360\u75282\u4e2a\u5b57\u7b26\uff09";
var MODIFY_MSG = "\u8bf7\u4fee\u6539\uff01";
var LENGHT_PERIOD_MSG = "\u7684\u957f\u5ea6\u5fc5\u987b\u4e3a\uff1a";
var MINUS_MSG = "-";
var MONEY_MSG1 = "\u6570\u636e\u4e3a\u975e\u6cd5\u91d1\u989d\uff0c\u8bf7\u4fee\u6539\uff01";
var MONEY_MSG2 = "\u6570\u636e\u4e0d\u80fd\u4e3a\u8d1f\uff0c\u8bf7\u4fee\u6539\uff01";
var MONEY_MSG3 = "\u6570\u636e\u6574\u6570\u90e8\u5206\u8d85\u957f\uff0c\u8bf7\u4fee\u6539\uff01";
var MONEY_MSG4 = "\u6570\u636e\u8f85\u5e01\u90e8\u5206\u8d85\u957f\uff0c\u8bf7\u4fee\u6539\uff01";
var MONEY_MSG = "\u5e94\u5927\u4e8e";
var MONEY_MSG0 = "\u5e94\u5c0f\u4e8e\u7b49\u4e8e";
var EXCHANGERATE_MSG1 = "\u6570\u636e\u975e\u6cd5\uff0c\u8bf7\u4fee\u6539\uff01";
var EXCHANGERATE_MSG2 = "\u6570\u636e\u4e0d\u80fd\u4e3a\u8d1f\uff0c\u8bf7\u4fee\u6539\uff01";
var EXCHANGERATE_MSG3 = "\u6570\u636e\u6574\u6570\u90e8\u5206\u8d85\u957f\uff0c\u8bf7\u4fee\u6539\uff01";
var EXCHANGERATE_MSG4 = "\u6570\u636e\u8f85\u5e01\u90e8\u5206\u8d85\u957f\uff0c\u8bf7\u4fee\u6539\uff01";
var ILLEGAL_DATE = "\u6570\u636e\u4e3a\u975e\u6cd5\u65e5\u671f\uff0c\u8bf7\u4fee\u6539\uff01";
var DATE_LATER_MSG = "\u4e0d\u5e94\u65e9\u4e8e";
var DATE_NOTLATER_MSG = "\u4e0d\u80fd\u665a\u4e8e"
var ILLEGAL_DATE_PERIOD = "\u8f93\u5165\u65e5\u671f\u8303\u56f4\u8d85\u8fc7";
var ENTRIES = "\u4e2a";
var MONTH = "\u6708";
var DAY = "\u5929";
/** FormCheck\u8868\u5355\u68c0\u67e5 end */
/** ListCheck\u8868\u5355\u68c0\u67e5 begin */
var ALL_AUTH = "\u6b64\u64cd\u4f5c\u5c06\u6e05\u9664\u60a8\u6240\u505a\u7684\u5176\u4ed6\u9009\u62e9\uff0c\u662f\u5426\u7ee7\u7eed\uff1f";
var CHOICE_MSG = "\u8bf7\u60a8\u81f3\u5c11\u9009\u62e9\u67d0\u4e00";
var ALL_COUNT = "\u672c\u6b21\u5171\u5904\u7406\u4e1a\u52a1\uff1a";
var ALL_MONEY = "\u7b14\uff0c\u603b\u91d1\u989d\uff1a";
var SPACE_MSG = " ";
var DOT_MSG = ".";
var EXCMARK_MSG = "\uff01";
/** ListCheck\u8868\u5355\u68c0\u67e5 end */
/** \u65e5\u5386\u4f7f\u7528 begin */
var calLanguage="zhCN";
var calMonthArr = new Array("1\u6708","2\u6708","3\u6708","4\u6708","5\u6708","6\u6708","7\u6708","8\u6708","9\u6708","10\u6708","11\u6708","12\u6708");
var calDayArr = new Array("\u65e5","\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d");
var calYear = "\u5e74";
var calMonth = "\u6708";
/** \u65e5\u5386\u4f7f\u7528 end */
/** \u6536\u6b3e\u4eba\u5f00\u6237\u884c\u4e0b\u62c9\u83dc\u5355\u4f7f\u7528 begin */
var PLEASE_CHOICE="\u8bf7\u9009\u62e9";
/** \u6536\u6b3e\u4eba\u5f00\u6237\u884c\u4e0b\u62c9\u83dc\u5355\u4f7f\u7528 end */
//author liuy
var START_DATE="\u8d77\u59cb\u65e5\u671f";
var END_DATE="\u7ed3\u675f\u65e5\u671f";
/*******************************/
/*** \u81ea\u52a9\u6ce8\u518c\u4f7f\u7528 ***/
/*******************************/
var USER_NAME_IS_EMPTY = "\u8bf7\u8f93\u5165\u7528\u6237\u540d\uff01";
var USER_NAME_IS_INCORRECT = "\u7528\u6237\u540d\u4e0d\u6b63\u786e\uff0c\u7528\u6237\u540d\u75316-20\u4f4d\u957f\u5ea6\u7684\u6570\u5b57\u548c\u82f1\u6587\u5b57\u6bcd\u7ec4\u6210\uff0c\u4e0d\u533a\u5206\u5927\u5c0f\u5199\uff0c\u4e0d\u5141\u8bb8\u6709\u7a7a\u683c\uff0c\u81f3\u5c11\u5305\u542b1\u4f4d\u82f1\u6587\u5b57\u6bcd\uff01";
var PASSWORD_IS_EMPTY = "\u8bf7\u8f93\u5165\u5bc6\u7801\uff01";
var PASSWORD_IS_INCORRECT = "\u5bc6\u7801\u4e0d\u6b63\u786e\uff0c\u5bc6\u7801\u75318-20\u4f4d\u957f\u5ea6\u7684\u6570\u5b57\u548c\u82f1\u6587\u5b57\u6bcd\u7ec4\u6210\uff0c\u533a\u5206\u5927\u5c0f\u5199\uff0c\u81f3\u5c11\u5305\u542b1\u4f4d\u82f1\u6587\u5b57\u6bcd\u548c1\u4f4d\u6570\u5b57\uff01";
var NEW_PASSWORD_IS_EMPTY = "\u8bf7\u8f93\u5165\u65b0\u5bc6\u7801\uff01";
var NEW_PASSWORD_IS_INCORRECT = "\u65b0\u5bc6\u7801\u4e0d\u6b63\u786e\uff0c\u5bc6\u7801\u75318-20\u4f4d\u957f\u5ea6\u7684\u6570\u5b57\u548c\u82f1\u6587\u5b57\u6bcd\u7ec4\u6210\uff0c\u533a\u5206\u5927\u5c0f\u5199\uff0c\u81f3\u5c11\u5305\u542b1\u4f4d\u82f1\u6587\u5b57\u6bcd\u548c1\u4f4d\u6570\u5b57\uff01";
var CONFIRM_PASSWORD_IS_EMPTY = "\u8bf7\u8f93\u5165\u786e\u8ba4\u5bc6\u7801\uff01";
var CONFIRM_PASSWORD_IS_INCORRECT = "\u786e\u8ba4\u5bc6\u7801\u4e0e\u5bc6\u7801\u4e0d\u5339\u914d\uff01";
var OLD_PASSWORD_IS_EMPTY = "\u8bf7\u8f93\u5165\u539f\u59cb\u5bc6\u7801\uff01";
var BIRTHDAY_IS_INCORRECT = "\u51fa\u751f\u65e5\u671f\u4e0d\u6b63\u786e\uff01\u65e5\u671f\u7684\u6b63\u786e\u683c\u5f0f\u4e3aYYYY/MM/DD\uff0c\u4e14\u5fc5\u987b\u4e3a\u5408\u6cd5\u7684\u65e5\u671f\uff01";
var BIRTHDAY_MORE_THAN_TODAY = "\u51fa\u751f\u65e5\u671f\u4e0d\u80fd\u5927\u4e8e\u4eca\u5929\uff01";
var PHONE_IS_EMPTY = "\u8bf7\u8f93\u5165\u5e38\u7528\u7535\u8bdd\u53f7\u7801\uff01";
var PHONE_IS_INCORRECT = "\u5e38\u7528\u7535\u8bdd\u53f7\u7801\u4e0d\u6b63\u786e\uff0c\u5176\u53ea\u80fd\u5305\u542b\u6570\u5b57\uff0c\u5b57\u6bcd\u4ee5\u53ca-\uff0c\u4e14\u957f\u5ea6\u5fc5\u987b\u5c0f\u4e8e\u7b49\u4e8e15\uff01";
var PHONE2_IS_INCORRECT = "\u5907\u7528\u7535\u8bdd\u53f7\u7801\u4e0d\u6b63\u786e\uff0c\u5176\u53ea\u80fd\u5305\u542b\u6570\u5b57\uff0c\u5b57\u6bcd\u4ee5\u53ca-\uff0c\u4e14\u957f\u5ea6\u5fc5\u987b\u5c0f\u4e8e\u7b49\u4e8e15\uff01";
var MOBILE_IS_INCORRECT = "\u79fb\u52a8\u7535\u8bdd\u53f7\u7801\u4e0d\u6b63\u786e\uff0c\u5176\u5fc5\u987b\u662f11\u4f4d\u6570\u5b57\uff01";
var EMAIL_IS_EMPTY = "\u8bf7\u8f93\u5165\u7535\u5b50\u4fe1\u7bb1\uff01";
var EMAIL_IS_INCORRECT = "\u7535\u5b50\u4fe1\u7bb1\u4e0d\u6b63\u786e\uff01";
var EMAIL1_IS_EMPTY = "\u8bf7\u8f93\u5165\u5e38\u7528\u7684\u7535\u5b50\u4fe1\u7bb1\uff01";
var EMAIL1_IS_INCORRECT = "\u5e38\u7528\u7684\u7535\u5b50\u4fe1\u7bb1\u4e0d\u6b63\u786e\uff01";
var EMAIL2_IS_INCORRECT = "\u5907\u7528\u7684\u7535\u5b50\u4fe1\u7bb1\u4e0d\u6b63\u786e\uff01";
var ZIPCODE_IS_EMPTY = "\u8bf7\u8f93\u5165\u90ae\u653f\u7f16\u7801\uff01";
var ZIPCODE_IS_INCORRECT = "\u90ae\u653f\u7f16\u7801\u5fc5\u987b\u662f6\u4f4d\u6570\u5b57\uff01";
var ADDRESS_IS_EMPTY = "\u8bf7\u8f93\u5165\u90ae\u653f\u5730\u5740\uff01";
var ADDRESS_IS_INCORRECT = "\u90ae\u653f\u5730\u5740\u4e0d\u6b63\u786e\uff0c\u5730\u5740\u957f\u5ea6\u5fc5\u987b\u5c0f\u4e8e\u7b49\u4e8e60\uff01";
var ACCOUNT_EDIT_INPUT_NICKNAME = "\u8bf7\u8f93\u5165\u8d26\u6237\u522b\u540d\uff01";
var WELCOME_IS_EMPTY = "\u8bf7\u8f93\u5165\u6b22\u8fce\u4fe1\u606f\uff01";
var COLOR_IS_EMPTY = "\u8bf7\u8f93\u5165\u60a8\u6700\u559c\u6b22\u7684\u989c\u8272\uff01";
var MOVIE_IS_EMPTY = "\u8bf7\u8f93\u5165\u60a8\u6700\u559c\u6b22\u7684\u7535\u5f71\uff01";
var PET_IS_EMPTY = "\u8bf7\u8f93\u5165\u60a8\u6700\u559c\u6b22\u7684\u5ba0\u7269\uff01";
var GENDER_IS_EMPTY = "\u8bf7\u8f93\u5165\u60a8\u7684\u6027\u522b\uff01";
var QUESTIONONE_IS_EMPTY = "\u8bf7\u8f93\u5165\u60a8\u7684\u9884\u7559\u95ee\u9898\u4e00\uff01";
var QUESTIONTWO_IS_EMPTY = "\u8bf7\u8f93\u5165\u60a8\u7684\u9884\u7559\u95ee\u9898\u4e8c\uff01";
var QUESTIONTHREE_IS_EMPTY = "\u8bf7\u8f93\u5165\u60a8\u7684\u9884\u7559\u95ee\u9898\u4e09\uff01";
var ANSWERONE_IS_EMPTY = "\u8bf7\u8f93\u5165\u60a8\u7684\u95ee\u9898\u4e00\u7b54\u6848\uff01";
var ANSWERTWO_IS_EMPTY = "\u8bf7\u8f93\u5165\u60a8\u7684\u9884\u7559\u95ee\u9898\u4e8c\u7b54\u6848\uff01";
var ANSWERTHREE_IS_EMPTY = "\u8bf7\u8f93\u5165\u60a8\u7684\u9884\u7559\u95ee\u9898\u4e09\u7b54\u6848\uff01";
//***************User identity related constants********************/
var IDENTITY_TYPE_IS_EMPTY = "\u8bf7\u9009\u62e9\u8bc1\u4ef6\u7c7b\u578b";
var IDENTITY_NO_IS_EMPTY = "\u8bf7\u8f93\u5165\u5408\u6cd5\u7684\u8bc1\u4ef6\u53f7\u7801\u3002";
var IDENTITY_NO_IS_INCORRECT = "\u8eab\u4efd\u8bc1\u53f7\u7801\u4e0d\u6b63\u786e\uff0c\u6b63\u786e\u7684\u8eab\u4efd\u8bc1\u53f7\u7801\u5fc5\u987b\u6ee1\u8db3\u4ee5\u4e0b\u89c4\u5219\uff1a" +
"\r\n1\u3001\u957f\u5ea6\u5fc5\u987b\u4e3a15\u621618\u3002" +
"\r\n2\u3001\u8eab\u4efd\u8bc1\u4e2d\u7684\u51fa\u751f\u65e5\u671f\u5fc5\u987b\u662f\u5408\u6cd5\u7684\u65e5\u671f\u3002" +
"\r\n3\u300115\u4f4d\u7684\u8eab\u4efd\u8bc1\u5fc5\u987b\u662f\u6570\u5b57\u3002" +
"\r\n4\u300118\u4f4d\u7684\u8eab\u4efd\u8bc1\u524d17\u4f4d\u5fc5\u987b\u662f\u6570\u5b57\uff0c\u6700\u540e\u4e00\u4f4d\u662f\u6570\u5b57\u6216\u5b57\u6bcd\u2018x\u2019\u3001\u2018X\u2019";
//***************User identity related constants end********************/
/*************** psnApplay \u5728\u7ebf\u9884\u7ea6\u7533\u8bf7\u5f00\u6237 lyj 20110321 begin **************************/
var IDENTITYDATE_IS_EMPTY = "\u8bf7\u8f93\u5165\u8bc1\u4ef6\u5230\u671f\u65e5\u671f\uff01";
var IDENTITYDATE_IS_INCORRECT = "\u8bc1\u4ef6\u5230\u671f\u65e5\u671f\u4e0d\u6b63\u786e\uff01\u65e5\u671f\u7684\u6b63\u786e\u683c\u5f0f\u4e3aYYYY/MM/DD\uff0c\u4e14\u5fc5\u987b\u4e3a\u5408\u6cd5\u7684\u65e5\u671f\uff01";
var IDENTITYDATE_LESS_THAN_TODAY = "\u8bc1\u4ef6\u5230\u671f\u65e5\u671f\u4e0d\u80fd\u5c0f\u4e8e\u4eca\u5929\uff01";
var BIRTHDAY_IS_EMPTY = "\u8bf7\u8f93\u5165\u51fa\u751f\u65e5\u671f";
var A_MOBILE_IS_EMPTY = "\u8bf7\u8f93\u5165\u624b\u673a\u53f7\u7801\uff01";
var A_MOBILE_IS_INCORRECT = "\u79fb\u52a8\u7535\u8bdd\u53f7\u7801\u4e0d\u6b63\u786e\uff0c\u5176\u5fc5\u987b\u662f11\u4f4d\u6570\u5b57\uff01";
var A_COUNTRY_IS_EMPTY = "\u8bf7\u8f93\u5165\u56fd\u5bb6\uff01";
var A_PROVINCE_IS_EMPTY = "\u8bf7\u8f93\u5165\u7701/\u76f4\u8f96\u5e02/\u81ea\u6cbb\u533a\uff01";
var A_PROVINCE_IS_INCORRECT = "\u7701/\u76f4\u8f96\u5e02/\u81ea\u6cbb\u533a\u4e0d\u6b63\u786e\uff0c\u957f\u5ea6\u5fc5\u987b\u5c0f\u4e8e"+"\r\n\u7b49\u4e8e20\u4e2a\u82f1\u6587\u5b57\u7b26\uff08\u4e00\u4e2a\u6c49\u5b57\u53602\u4e2a\u5b57\u7b26\uff09\uff0c\u8bf7\u4fee\u6539\uff01";
var A_CITY_IS_EMPTY = "\u8bf7\u8f93\u5165\u57ce\u5e02\uff01";
var A_CITY_IS_INCORRECT = "\u57ce\u5e02\u4e0d\u6b63\u786e\uff0c\u957f\u5ea6\u5fc5\u987b\u5c0f\u4e8e\u7b49\u4e8e20\u4e2a\u82f1\u6587\u5b57\u7b26\uff08\u4e00\u4e2a\u6c49\u5b57\u53602\u4e2a\u5b57\u7b26\uff09\uff0c\u8bf7\u4fee\u6539\uff01";
var A_ADDRESS_IS_EMPTY = "\u8bf7\u8f93\u5165\u5730\u5740\uff01";
var A_ADDRESS_IS_INCORRECT = "\u5730\u5740\u4e0d\u6b63\u786e\uff0c\u5730\u5740\u957f\u5ea6\u5fc5\u987b\u5c0f\u4e8e\u7b49\u4e8e120\u4e2a\u82f1\u6587\u5b57\u7b26\uff08\u4e00\u4e2a\u6c49\u5b57\u53602\u4e2a\u5b57\u7b26\uff09\uff0c\u8bf7\u4fee\u6539\uff01";
var A_EMAIL1_IS_INCORRECT = "\u7535\u5b50\u4fe1\u7bb1\u4e0d\u6b63\u786e\uff01";
var A_PHONE_IS_INCORRECT = "\u529e\u516c\u7535\u8bdd\u53f7\u7801\u4e0d\u6b63\u786e\uff0c\u5176\u53ea\u80fd\u5305\u542b\u6570\u5b57\uff0c()\u4ee5\u53ca-\uff0c"+"\r\n\u4e14\u957f\u5ea6\u5fc5\u987b\u5c0f\u4e8e\u6216\u7b49\u4e8e14\uff01\u5982\uff1a"+"\r\n\n010-12345678\uff0c(0731)12345678\u3002";
var A_PHONE2_IS_INCORRECT = "\u5bb6\u5ead\u7535\u8bdd\u53f7\u7801\u4e0d\u6b63\u786e\uff0c\u5176\u53ea\u80fd\u5305\u542b\u6570\u5b57\uff0c()\u4ee5\u53ca-\uff0c"+"\r\n\u4e14\u957f\u5ea6\u5fc5\u987b\u5c0f\u4e8e\u6216\u7b49\u4e8e14\uff01\u5982\uff1a"+"\r\n\n010-12345678\uff0c(0731)12345678\u3002";
/*************** psnApplay \u5728\u7ebf\u9884\u7ea6\u7533\u8bf7\u5f00\u6237 lyj 20110321 end **************************/
//***************banking account related constants********************/
var ACCOUNT_IS_EMPTY = "\u8bf7\u8f93\u5165\u94f6\u884c\u8d26\u53f7\u3002";
var ACCOUNT_MUST_BE_NUMBER = "\u94f6\u884c\u8d26\u53f7\u5fc5\u987b\u662f\u6570\u5b57\u3002";
var DEBIT_CARD_IS_INVALID = "\u501f\u8bb0\u5361\u7684\u5361\u53f7\u5fc5\u987b\u662f19\u4f4d\u3002";
var QCC_IS_INVALID = "\u51c6\u8d37\u8bb0\u5361\u7684\u5361\u53f7\u5fc5\u987b\u662f16\u4f4d\u3002";
var BOC_CREDIT_CARD_IS_INVALID = "\u4fe1\u7528\u5361\u7684\u5361\u53f7\u5fc5\u987b\u662f16\u4f4d\u3002";
var ENROLLMENT_ACCOUNT_INVALID = "\u53ea\u6709\u501f\u8bb0\u5361\u624d\u80fd\u4f5c\u4e3a\u6ce8\u518c\u5361";
//***************banking account related constants end********************/
var PASSWORD_NOT_EQUAL_CONFIRM_PASSWORD = "\u5bc6\u7801\u4e0e\u786e\u8ba4\u5bc6\u7801\u4e0d\u4e00\u81f4\u3002";
var EFS_PASSWORD_LEN_INVALID = "\u5bc6\u7801\u7684\u957f\u5ea6\u5fc5\u987b\u5927\u4e8e\u7b49\u4e8e8\u3002";
var USER_NAME_LEN_INVALID = "\u7528\u6237\u540d\u7684\u957f\u5ea6\u5fc5\u987b\u5927\u4e8e\u7b49\u4e8e6\u3002";
var PHONE_PASSWORD_INVALID = "\u7535\u8bdd\u94f6\u884c\u5bc6\u7801\u4e0d\u6b63\u786e\u3002";
var CHECKING_CODE_IS_EMTPY = "\u8bf7\u8f93\u5165\u9a8c\u8bc1\u7801\u3002";
var DATE_INVALID = "\u60a8\u8f93\u5165\u7684\u65e5\u671f\u4e0d\u6b63\u786e\u3002";
var EXPIRING_DATE_INVALID = "\u4f60\u8f93\u5165\u7684\u5931\u6548\u65e5\u671f\u4e0d\u6b63\u786e\u3002";
var E_TOKEN_INVALID = "\u52a8\u6001\u53e3\u4ee4\u4e0d\u6b63\u786e\uff0c\u8bf7\u8f93\u51656\u4f4d\u6570\u5b57\u7684\u52a8\u6001\u53e3\u4ee4\u3002";
/*******************************/
/*** \u81ea\u52a9\u6ce8\u518c\u4f7f\u7528 end */
/*******************************/
/*******************************/
/*** \u5b9a\u671f\u5b58\u6b3e **/
/********************************/
var SELECT_CURRENCY = "\u8bf7\u9009\u62e9";
var TRANSFER_ACCOUNT_INVALID = "\u8d26\u6237\u4fe1\u606f\u4e0d\u53ef\u7528\uff0c\u8bf7\u9009\u62e9\u53e6\u4e00\u4e2a\u8d26\u6237\u6216\u8005\u5237\u65b0\u8d26\u6237\u4fe1\u606f";
var TRANSFER_FROM_ACCOUNT = "\u8bf7\u9009\u62e9\u8f6c\u51fa\u8d26\u6237\uff01";
var TRANSFER_TO_ACCOUNT = "\u8bf7\u9009\u62e9\u8f6c\u5165\u8d26\u6237\uff01";
var TRANSFER_AMOUNT = "\u8bf7\u586b\u5199\u8f6c\u8d26\u91d1\u989d\uff01";
var TRANSFER_CURRENCY = "\u8bf7\u8f93\u5165\u5e01\u79cd\u6027\u8d28!";
var TRANSFER_CASHREMIT = "\u8bf7\u9009\u62e9\u949e\u6c47\u6807\u5fd7!";
var TRANSFER_CDTERM = "\u8bf7\u9009\u62e9\u5b58\u671f!";
var TRANSFER_FREQUENCY = "\u8bf7\u9009\u62e9\u5468\u671f!";
var TRANSFER_ENDDATE = "\u8bf7\u9009\u62e9\u7ed3\u675f\u65e5\u671f!";
var SYSDATE = "\u7cfb\u7edf\u5f53\u524d\u65e5\u671f";
var SCHEDULEDATE = "\u9884\u7ea6\u6267\u884c\u65e5\u671f";
var STARTDATE_INVALID = "\u8d77\u59cb\u65e5\u671f\u5fc5\u987b\u662f\u7cfb\u7edf\u5f53\u524d\u65e5\u671f\u672a\u6765\u4e00\u4e2a\u6708\u7684\u4efb\u610f\u4e00\u5929!";
var ENDDATE_INVALID = "\u7ed3\u675f\u65e5\u671f\u5fc5\u987b\u662f\u7cfb\u7edf\u5f53\u524d\u65e5\u671f\u672a\u6765\u516d\u4e2a\u6708\u7684\u4efb\u610f\u4e00\u5929!";
var SCHEDULEDATE_INVALID = "\u9884\u7ea6\u6267\u884c\u65e5\u671f\u5fc5\u987b\u662f\u7cfb\u7edf\u5f53\u524d\u65e5\u671f\u672a\u6765\u4e09\u4e2a\u6708\u5185\u7684\u4efb\u610f\u4e00\u5929!";
var ENDDATE_BEFORE_STARTDATE = "\u7ed3\u675f\u65e5\u671f\u4e0d\u80fd\u5c0f\u4e8e\u8d77\u59cb\u65e5\u671f!";
var FORMAT_ERROR="{0}\u683c\u5f0f\u4e0d\u6b63\u786e\uff0c";
/*******************************/
/*** \u5b89\u5168\u63a7\u4ef6 **/
/********************************/
var SAFECONTROL_INSTALL = "\u8bf7\u9996\u5148\u4e0b\u8f7d\u5e76\u5b89\u88c5\u5b89\u5168\u63a7\u4ef6\u540e\u518d\u767b\u5f55\u7f51\u4e0a\u94f6\u884c\uff0c\u5b89\u88c5\u63a7\u4ef6\u65f6\u8bf7\u5173\u95ed\u6240\u6709\u7684\u6d4f\u89c8\u5668\u7a97\u53e3\u3002";
var SAFECONTROL_VERSION = "\u5b89\u5168\u63a7\u4ef6\u5df2\u7ecf\u5347\u7ea7\uff0c\u8bf7\u9996\u5148\u4e0b\u8f7d\u5e76\u5b89\u88c5\u65b0\u7248\u672c\u5b89\u5168\u63a7\u4ef6\u540e\u518d\u767b\u5f55\u7f51\u4e0a\u94f6\u884c\u3002\u5b89\u88c5\u65b0\u5b89\u5168\u63a7\u4ef6\u524d\u8bf7\u5148\u5230\u63a7\u5236\u9762\u677f\u4e2d\u5378\u8f7d\u65e7\u5b89\u5168\u63a7\u4ef6\uff0c\u5b89\u88c5\u65f6\u5173\u95ed\u6240\u6709\u7684\u6d4f\u89c8\u5668\u7a97\u53e3\u3002";
//edit by yangda
var CURCODE_KHR = "\u67ec\u57d4\u5be8\u745e\u5c14";
/*
* \u5404\u5e01\u79cd\u91d1\u989d\u683c\u5f0f\u6570\u7ec4
*
* curCodeArr[0] -- \u8868\u793a\u8d27\u5e01\u4ee3\u7801
* curCodeArr[1] -- \u8868\u793a\u5e01\u79cd\u540d\u79f0
* curCodeArr[2] -- \u8868\u793a\u6574\u6570\u4f4d\u6570
* curCodeArr[3] -- \u8868\u793a\u8f85\u5e01\u4f4d\u6570
*
*/
var curCodeArr = new Array(
new Array("001",CURCODE_CNY,13,2),
new Array("012",CURCODE_GBP,13,2),
new Array("013",CURCODE_HKD,13,2),
new Array("014",CURCODE_USD,13,2),
new Array("015",CURCODE_CHF,13,2),
new Array("016",CURCODE_DEM,13,2),
new Array("017",CURCODE_FRF,13,2),
new Array("018",CURCODE_SGD,13,2),
new Array("020",CURCODE_NLG,13,2),
new Array("021",CURCODE_SEK,13,2),
new Array("022",CURCODE_DKK,13,2),
new Array("023",CURCODE_NOK,13,2),
new Array("024",CURCODE_ATS,13,2),
new Array("025",CURCODE_BEF,13,0),
new Array("026",CURCODE_ITL,13,0),
new Array("027",CURCODE_JPY,13,0),
new Array("028",CURCODE_CAD,13,2),
new Array("029",CURCODE_AUD,13,2),
new Array("038",CURCODE_EUR,13,2),
new Array("056",CURCODE_IDR,13,2),
new Array("064",CURCODE_VND,13,0),
new Array("081",CURCODE_MOP,13,2),
new Array("082",CURCODE_PHP,13,2),
new Array("084",CURCODE_THB,13,2),
new Array("087",CURCODE_NZD,13,2),
new Array("088",CURCODE_KRW,13,0),
new Array("095",CURCODE_XSF,13,2),
new Array("072",CURCODE_RUR,13,2),
new Array("070",CURCODE_ZAR,13,2),
new Array("065",CURCODE_HUF,13,2),
new Array("101",CURCODE_KZT,13,2),
new Array("080",CURCODE_ZMK,13,2),
new Array("032",CURCODE_MYR,13,2),
//add by cuiyk \u767d\u91d1 \u6587\u83b1\u5e01 \u91cc\u4e9a\u5c14 \u535a\u8328\u74e6\u7eb3\u666e\u62c9
new Array("843",CURCODE_XPT,13,2),
new Array("131",CURCODE_BND,13,2),
new Array("134",CURCODE_BRL,13,2),
new Array("039",CURCODE_BWP,13,2),
//added by hhf.\u4e3a\u9ec4\u91d1\u724c\u4ef7\u5c40\u90e8\u5237\u65b0
new Array("034",CURCODE_XAU,13,2),
new Array("035",CURCODE_GLD,13,0),
//add by zph Riel
new Array("166",CURCODE_KHR,13,2)
);
| zzhongster-wxtlactivex | chrome/settings/_boc_resources_zh_CN_CurCode.js | JavaScript | mpl11 | 20,873 |
navigator.cpuClass='x86';
| zzhongster-wxtlactivex | chrome/settings/cpuclass.js | JavaScript | mpl11 | 26 |
window.addEventListener('load', function() {
delete FrmUserInfo.elements;
FrmUserInfo.elements = function(x){return this[x]};
console.log('cloudzz patch');
onAuthenticated();
}, false);
HTMLElement.prototype.insertAdjacentHTML = function(orig) {
return function() {
this.style.display = "block";
this.style.overflow = "hidden";
orig.apply(this, arguments);
}
}(HTMLElement.prototype.insertAdjacentHTML); | zzhongster-wxtlactivex | chrome/settings/_cloudzz.js | JavaScript | mpl11 | 403 |
(function() {
function declareEventAsIE(node) {
if (!node.attachEvent) {
node.attachEvent = function(event, operation) {
if (event.substr(0, 2) == "on") this.addEventListener(event.substr(2), operation, false)
}
}
if (!node.detachEvent) {
node.detachEvent = function(event, operation) {
if (event.substr(0, 2) == "on") this.removeEventListener(event.substr(2), operation, false)
}
}
}
declareEventAsIE(window.Node.prototype);
declareEventAsIE(window.__proto__);
})();
| zzhongster-wxtlactivex | chrome/settings/IEEvent.js | JavaScript | mpl11 | 532 |
//********************************************
//*** \u4ee5\u4e0b\u51fd\u6570\u7528\u6765\u5904\u7406\u91d1\u989d\u5343\u5206\u4f4d\u663e\u793a\u53ca\u4eba\u6c11\u5e01\u5927\u5199
//********************************************
var pubarray1 = new Array("\u96f6","\u58f9","\u8d30","\u53c1","\u8086","\u4f0d","\u9646","\u67d2","\u634c","\u7396","");
var pubarray2 = new Array("","\u62fe","\u4f70","\u4edf");
var pubarray3 = new Array("\u5143","\u4e07","\u4ebf","\u5146","","");
var pubarray4 = new Array("\u89d2","\u5206");
var char_len = pubarray1[0].length;
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u6839\u636e\u8d27\u5e01\u7801\u683c\u5f0f\u5316\u8f85\u5e01\u4f4d\u6570\uff0c\u4e0d\u8db3\u4f4d\u7684\u88650
*
* Parameter str -- \u9700\u5904\u7406\u7684\u5e26\u6709\u6570\u5b57\u7684\u5b57\u7b26\u4e32;
* curCode -- \u8d27\u5e01\u7801;
*
* Return \u5b57\u7b26\u4e32 -- \u683c\u5f0f\u5316\u540e\u7684\u5b57\u7b26\u4e32
*
* \u4f8b\u5b50\uff1aformatDecimalPart("12345678","001");
* \u8fd4\u56de\u5b57\u7b26\u4e32\uff1a12345678.00
*
*/
function formatDecimalPart(str,curCode)
{
var curDec;
for(var j = 0; j < curCodeArr.length; j++)
{
if (curCodeArr[j][0] == curCode)
{
curDec = curCodeArr[j][3];
break;
}
}
if (str.indexOf(".") == -1)
{
var tmp = "";
if (curDec == 0)
return str;
for(var i = 0; i < curDec; i++)
{
tmp += "0";
}
return str + "." + tmp;
}
else
{
var strArr = str.split(".");
var decimalPart = strArr[1];
while(decimalPart.length < curDec)
{
decimalPart += "0";
}
return strArr[0] + "." + decimalPart;
}
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u5c06\u5e26\u6709\u6570\u5b57\u7684\u5b57\u7b26\u4e32\u7528","\u8fdb\u884c\u5206\u9694,\u5e76\u4e14\u52a0\u4e0a\u5c0f\u6570\u4f4d(\u5904\u7406\u5343\u5206\u4f4d,\u5206\u5e01\u79cd)
*
* Parameter str -- \u9700\u5904\u7406\u7684\u5e26\u6709\u6570\u5b57\u7684\u5b57\u7b26\u4e32;
* curCode -- \u8d27\u5e01\u7801;
*
* Return \u5b57\u7b26\u4e32 -- \u683c\u5f0f\u5316\u540e\u7684\u5b57\u7b26\u4e32
*
* \u4f8b\u5b50\uff1achangePartition("12345678");
* \u8fd4\u56de\u5b57\u7b26\u4e32\uff1a12,345,678.00
*
*/
function changePartition(str,curCode)
{
var minus = "";
if(str.substring(0,1) == "-")
{
str = str.substring(1);
minus = "-";
}
str = formatDecimalPart(str,curCode);
var twopart = str.split(".");
var decimal_part = twopart[1];
//format integer part
var integer_part="0";
var intlen=twopart[0].length;
if(intlen>0)
{
var i=0;
integer_part="";
while(intlen>3)
{
integer_part=","+twopart[0].substring(intlen-3,intlen)+integer_part;
i=i+1;
intlen=intlen-3;
}
integer_part=twopart[0].substring(0,intlen)+integer_part;
}
if (!decimal_part)
return minus + integer_part;
else
return minus + integer_part + "." + decimal_part
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u5c06\u5e26\u6709\u6570\u5b57\u7684\u5b57\u7b26\u4e32\u5904\u7406\u6210\u5927\u5199\u7684\u4eba\u6c11\u5e01
*
* Parameter str -- \u9700\u5904\u7406\u7684\u5e26\u6709\u6570\u5b57\u7684\u5b57\u7b26\u4e32;
*
* Return \u5b57\u7b26\u4e32 -- \u683c\u5f0f\u5316\u540e\u7684\u5b57\u7b26\u4e32
*
* \u4f8b\u5b50\uff1achangeUppercase("12345678.90")
* \u8fd4\u56de\u5b57\u7b26\u4e32\uff1a\u58f9\u4edf\u8d30\u4f70\u53c1\u62fe\u8086\u4e07\u4f0d\u4edf\u9646\u4f70\u67d2\u62fe\u634c\u5143\u7396\u89d2
*
*/
function changeUppercase(str)
{
if(str=="" || eval(str)==0)
return "\u96f6";
if(str.substring(0,1) == "-")
{
if(eval(str.substring(1)) < 0.01)
return "\u91d1\u989d\u6709\u8bef!!";
else
str = str.substring(1);
}
var integer_part="";
var decimal_part="\u6574";
var tmpstr="";
var twopart=str.split(".");
//\u5904\u7406\u6574\u578b\u90e8\u5206\uff08\u5c0f\u6570\u70b9\u524d\u7684\u6574\u6570\u4f4d\uff09
var intlen=twopart[0].length;
if (intlen > 0 && eval(twopart[0]) != 0)
{
var gp=0;
var intarray=new Array();
while(intlen > 4)
{
intarray[gp]=twopart[0].substring(intlen-4,intlen);
gp=gp+1;
intlen=intlen-4;
}
intarray[gp]=twopart[0].substring(0,intlen);
for(var i=gp;i>=0;i--)
{
integer_part=integer_part+every4(intarray[i])+pubarray3[i];
}
integer_part=replace(integer_part,"\u4ebf\u4e07","\u4ebf\u96f6");
integer_part=replace(integer_part,"\u5146\u4ebf","\u5146\u96f6");
while(true)
{
if (integer_part.indexOf("\u96f6\u96f6")==-1)
break;
integer_part=replace(integer_part,"\u96f6\u96f6","\u96f6");
}
integer_part=replace(integer_part,"\u96f6\u5143","\u5143");
/*\u6b64\u5904\u6ce8\u91ca\u662f\u4e3a\u4e86\u89e3\u51b3100000\uff0c\u663e\u793a\u4e3a\u62fe\u4e07\u800c\u4e0d\u662f\u58f9\u62fe\u4e07\u7684\u95ee\u9898\uff0c\u6b64\u6bb5\u7a0b\u5e8f\u628a\u58f9\u62fe\u4e07\u622a\u6210\u4e86\u62fe\u4e07
tmpstr=intarray[gp];
if (tmpstr.length==2 && tmpstr.charAt(0)=="1")
{
intlen=integer_part.length;
integer_part=integer_part.substring(char_len,intlen);
}
*/
}
//\u5904\u7406\u5c0f\u6570\u90e8\u5206\uff08\u5c0f\u6570\u70b9\u540e\u7684\u6570\u503c\uff09
tmpstr="";
if(twopart.length==2 && twopart[1]!="")
{
if(eval(twopart[1])!=0)
{
decimal_part="";
intlen= (twopart[1].length>2) ? 2 : twopart[1].length;
for(var i=0;i<intlen;i++)
{
tmpstr=twopart[1].charAt(i);
decimal_part=decimal_part+pubarray1[eval(tmpstr)]+pubarray4[i];
}
decimal_part=replace(decimal_part,"\u96f6\u89d2","\u96f6");
decimal_part=replace(decimal_part,"\u96f6\u5206","");
if(integer_part=="" && twopart[1].charAt(0)==0)
{
intlen=decimal_part.length;
decimal_part=decimal_part.substring(char_len,intlen);
}
}
}
tmpstr=integer_part+decimal_part;
return tmpstr;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u5bf9\u4f4d\u6570\u5c0f\u4e8e\u7b49\u4e8e4\u7684\u6574\u6570\u503c\u5b57\u7b26\u4e32\u8fdb\u884c\u4e2d\u6587\u8d27\u5e01\u7b26\u53f7\u5904\u7406
*
* Parameter str -- \u9700\u5904\u7406\u7684\u5e26\u6709\u6570\u5b57\u7684\u5b57\u7b26\u4e32;
*
* Return \u5b57\u7b26\u4e32 -- \u683c\u5f0f\u5316\u540e\u7684\u5b57\u7b26\u4e32
*
* \u4f8b\u5b50\uff1aevery4("1234")
* \u8fd4\u56de\u5b57\u7b26\u4e32\uff1a\u58f9\u4edf\u8d30\u4f70\u53c1\u62fe\u8086
*
*/
function every4(str)
{
var weishu=str.length-1;
var retstr="";
var shuzi;
for (var i=0;i<str.length;i++)
{
shuzi=str.charAt(i);
if(shuzi=="0")
retstr=retstr+pubarray1[eval(shuzi)];
else
retstr=retstr+pubarray1[eval(shuzi)]+pubarray2[weishu];
weishu=weishu-1;
}
while(true)
{
if (retstr.indexOf("\u96f6\u96f6")==-1)
break;
retstr=replace(retstr,"\u96f6\u96f6","\u96f6");
}
if(shuzi=="0")
{
weishu=retstr.length-char_len;
retstr=retstr.substring(0,weishu);
}
return retstr;
}
| zzhongster-wxtlactivex | chrome/settings/_boc_FormatMoneyBase.js | JavaScript | mpl11 | 7,803 |
(function() {
Document.prototype.getElementById = function(orig) {
return function(id) {
var a = this.getElementsByName(id);
if (a.length > 0) {
return a[0];
}
return orig.call(this, id);
}
} (Document.prototype.getElementById);
})();
| zzhongster-wxtlactivex | chrome/settings/ieidname.js | JavaScript | mpl11 | 290 |
document.addEventListener('DOMContentLoaded', function() {
if (window.doLogin && window.statcus && window.psw) {
function makeHidden(obj) {
obj.style.display = 'block';
obj.style.height = '0px';
obj.style.width = '0px';
}
window.doLogin = function(orig) {
return function() {
if (statcus.style.display == 'none') {
makeHidden(statcus);
}
if (psw.style.display == 'none') {
makeHidden(psw);
}
orig();
};
}(doLogin);
}
}, false);
| zzhongster-wxtlactivex | chrome/settings/cebpay.js | JavaScript | mpl11 | 558 |
(function () {
function patch() {
if (window.ShowPayPage && window.InitControls) {
InitControls = function(orig) {
return function() {
if (CreditCardYear.object === undefined) {
CreditCardYear.object = {};
}
if (CreditCardMonth.object === undefined) {
CreditCardMonth.object = {};
}
if (CreditCardCVV2.object === undefined) {
CreditCardCVV2.object = {};
}
orig();
}
} (InitControls);
ShowPayPage = function(orig) {
return function(par) {
orig(par);
InitControls();
}
} (ShowPayPage);
DoSubmit = function(orig) {
return function(par) {
if (!CardPayNo.Option) {
CardPayNo.Option = function() {};
}
orig(par);
}
} (DoSubmit);
}
if (window.OpenWnd) {
var inputs = document.querySelectorAll('div > input[type=hidden]');
for (var i = 0; i < inputs.length; ++i) {
window[inputs[i].name] = inputs[i];
}
}
function patchLoginSwitch(fncName) {
if (!(window[fncName])) {
return;
}
window[fncName] = function(orig) {
return function(par) {
orig(par);
MobileNo_Ctrl.PasswdCtrl = false;
EMail_Ctrl.PasswdCtrl = false;
NetBankUser_Ctrl.PasswdCtrl = false;
DebitCardNo_Ctrl.PasswdCtrl = false;
CreditCardNo_Ctrl.PasswdCtrl = false;
IdNo_Ctrl.PasswdCtrl = false;
BookNo_Ctrl.PasswdCtrl = false;
}
} (window[fncName]);
}
patchLoginSwitch('changeCreditCardLoginType');
patchLoginSwitch('changeEALoginType');
patchLoginSwitch('showLoginEntry');
CallbackCheckClient = function() {};
}
if (document.readyState == 'complete') {
patch();
} else {
window.addEventListener('load', patch, false);
}
})();
| zzhongster-wxtlactivex | chrome/settings/cmb_pay.js | JavaScript | mpl11 | 1,943 |
window.addEventListener('DOMContentLoaded', function() {
if (window.logonSubmit) {
logonSubmit = function(orig) {
return function() {
try {
orig();
} catch (e) {
if (e.message == 'Error calling method on NPObject.') {
// We assume it has passed the checking.
frmLogon.submit();
clickBoolean = false;
}
}
}
}(logonSubmit);
}
}, false);
| zzhongster-wxtlactivex | chrome/settings/95559_submit.js | JavaScript | mpl11 | 449 |
//**************************************
//*** \u4ee5\u4e0b\u51fd\u6570\u662fJS\u516c\u7528\u51fd\u6570
//**************************************
var CONST_STRDOC="document.";
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u5220\u9664\u5de6\u53f3\u4e24\u7aef\u7684\u7a7a\u683c
*
*/
String.prototype.trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, "");
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u8df3\u8f6c\u81f3\u5176\u4ed6\u9875\u9762
*
*/
function gotoPage(url)
{
location.href = url;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u8df3\u8f6c\u81f3\u5176\u4ed6\u9875\u9762,\u5e76\u4f20\u9875\u9762\u53c2\u6570
*
* Parameter url -- \u8df3\u8f6c\u7684\u94fe\u63a5;
* paraName -- \u8981\u4f20\u7684\u53c2\u6570\u7684\u53c2\u6570\u540d\u79f0;
* paraValue -- \u8981\u4f20\u7684\u53c2\u6570\u7684\u53c2\u6570\u503c;
*
* \u4f8b\uff1agotoPage('XXX.do','orderName','ActNo');
* gotoPage('XXX.do','orderName|orderName1|PageNum','ActNo|ibknum|3');
*
*/
function gotoPageByPara(url,paraName,paraValue)
{
var urlHavePara = false;
if (url.indexOf("?") != -1)
urlHavePara = true;
if(paraName.indexOf("|") == -1)
if (urlHavePara)
location.href = url + "&" + paraName + "=" + paraValue ;
else
location.href = url + "?" + paraName + "=" + paraValue ;
else
{
nameArr = paraName.split("|");
paraArr = paraValue.split("|");
var paraStr = "";
for(var i = 0; i < nameArr.length; i++)
{
if (i == 0 && !urlHavePara)
paraStr = "?" + nameArr[i] + "=" + paraArr[i];
else
paraStr += "&" + nameArr[i] + "=" + paraArr[i];
}
location.href = url + paraStr;
}
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u6570\u636e\u4e0b\u8f7d\u4f7f\u7528\uff0c\u4f7f\u7528topFrame\u4e0b\u8f7d
*
*/
function dataDownload(url)
{
parent.topFrame.location.href = url;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u6570\u636e\u4e0b\u8f7d\u4f7f\u7528\uff0c\u4f7f\u7528topFrame\u4e0b\u8f7d,\u5e76\u4f20\u9875\u9762\u53c2\u6570
*
* Parameter url -- \u8df3\u8f6c\u7684\u94fe\u63a5;
* paraName -- \u8981\u4f20\u7684\u53c2\u6570\u7684\u53c2\u6570\u540d\u79f0;
* paraValue -- \u8981\u4f20\u7684\u53c2\u6570\u7684\u53c2\u6570\u503c;
*
* \u4f8b\uff1adataDownloadByPara('XXX.do','orderName','ActNo');
* dataDownloadByPara('XXX.do','orderName|orderName1|PageNum','ActNo|ibknum|3');
*
*/
function dataDownloadByPara(url,paraName,paraValue)
{
var urlHavePara = false;
if (url.indexOf("?") != -1)
urlHavePara = true;
if(paraName.indexOf("|") == -1)
if (urlHavePara)
parent.topFrame.location.href = url + "&" + paraName + "=" + paraValue ;
else
parent.topFrame.location.href = url + "?" + paraName + "=" + paraValue ;
else
{
nameArr = paraName.split("|");
paraArr = paraValue.split("|");
var paraStr = "";
for(var i = 0; i < nameArr.length; i++)
{
if (i == 0 && !urlHavePara)
paraStr = "?" + nameArr[i] + "=" + paraArr[i];
else
paraStr += "&" + nameArr[i] + "=" + paraArr[i];
}
parent.topFrame.location.href = url + paraStr;
}
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u6253\u5370\u5f53\u524d\u9875\u9762,\u5e76\u5c4f\u853d\u6253\u5370\u6309\u94ae(\u5982\u679c\u5b58\u5728ID\u4e3aprintDiv\u7684DIV\u5219\u5c4f\u853d)
*
*/
function printPage()
{
var obj = eval(CONST_STRDOC + "all.printDiv")
if (obj && obj.style)
{
obj.style.display = "none";
window.print();
obj.style.display = "";
}
else
window.print();
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u7528\u67d0\u5b57\u7b26\u4e32\u66ff\u6362\u6307\u5b9a\u5b57\u7b26\u4e32\u4e2d\u7684\u67d0\u5b57\u7b26\u4e32
*
* Parameter str -- \u9700\u5904\u7406\u7684\u5e26\u6709\u5f85\u66ff\u6362\u5b57\u4e32\u7684\u5b57\u7b26\u4e32;
* str_s -- \u9700\u67e5\u627e\u7684\u5f85\u66ff\u6362\u7684\u5b57\u7b26\u4e32;
* str_d -- \u8fdb\u884c\u66ff\u6362\u7684\u5b57\u7b26\u4e32;
*
* Return \u5b57\u7b26\u4e32 -- \u66ff\u6362\u540e\u7684\u5b57\u7b26\u4e32
*
* \u4f8b\u5b50\uff1areplace("\u58f9\u4edf\u96f6\u96f6\u53c1","\u96f6\u96f6","\u96f6")
* \u8fd4\u56de\u5b57\u7b26\u4e32\uff1a\u58f9\u4edf\u96f6\u53c1
*/
function replace(str,str_s,str_d)
{
var pos=str.indexOf(str_s);
if (pos==-1)
return str;
var twopart=str.split(str_s);
var ret=twopart[0];
for(pos=1;pos<twopart.length;pos++)
ret=ret+str_d+twopart[pos];
return ret;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u53d6\u5f97\u8868\u5355\u4e2dradio\u7684\u503c
*
* Parameter str -- \u8868\u5355\u4e2dradio\u7684\u540d\u5b57;
*
* Return \u5b57\u7b26\u4e32 -- radio\u7684\u503c
*
* \u4f8b\u5b50\uff1agetRadioValue('form1.radio')
*
*/
function getRadioValue(str)
{
var obj = eval(CONST_STRDOC + str);
if (!obj)
return;
if (!obj.length)
return obj.value;
else
{
for(var i = 0; i < obj.length; i++)
{
if (obj[i].checked)
{
return obj[i].value;
}
}
}
}
//**************************************
//*** JS\u516c\u7528\u51fd\u6570\u7ed3\u675f
//**************************************
//**************************************/
//******* \u8fdb\u5ea6\u6761\u5904\u7406\u51fd\u6570 begin *******/
//**************************************/
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u663e\u793a\u9875\u9762\u5904\u7406\u65f6\u7684\u8fdb\u5ea6\u6761\uff0c\u5e76\u63a7\u5236\u5f53\u524d\u9875\u9762\u7684\u4e8c\u6b21\u63d0\u4ea4\uff0c\u5728checkForm\u4e2d\u8c03\u7528\u3002
*/
function pageProcessing()
{
// try {
// processForm();
// } catch (e) {
// //alert("error: " + e.description);
// }
var processObj = document.all.processDiv;
var processBlockObj = document.all.processBlockDiv;
processObj.style.width = document.documentElement.scrollWidth;
processObj.style.height = document.documentElement.scrollHeight;
processObj.style.display = "";
processBlockObj.style.left = (document.documentElement.clientWidth - parseInt(processBlockObj.style.width)) / 2 + document.documentElement.scrollLeft;
processBlockObj.style.top = (document.documentElement.clientHeight - parseInt(processBlockObj.style.height)) / 2 + document.documentElement.scrollTop;
disableAllSelect();
/** 10\u5206\u949f\u540e\uff0c\u8fdb\u5ea6\u6761\u5931\u6548 */
window.setTimeout("pageProcessingDone();",600000);
}
/** \u4e3a\u6bcf\u4e2a\u9875\u9762\u589e\u52a0\u9632\u7be1\u6539\u529f\u80fd added by fangxi */
var processForm = (function () {
if (typeof BocNet == undefined) {
//alert("BocNet not found........");
return function() {};
} else {
//alert("BocNet defined...");
var VAR1 = "_viewstate1", VAR2 = "_viewstate2";
var f0 = function(m, key, value) { if (!m[key]) m[key] = []; m[key].push(value == null ? '' : String(value)); };
var f1 = function(m, key, item) { f0(m, key, item.value); };
var f2 = function(m, key, item) { if (item.checked) f0(m, key, item.value); };
var f3 = function(m, key, item) { if (item.selectedIndex >= 0) $A(item.options).each(function(e) { if (e.selected) f0(m, key, e.value); }); };
var ByType = { "text": f1, "password": f1, "hidden": f1, "radio": f2, "checkbox":f2, "select-one": f3, "select-multiple": f3 };
var injector = function(m,item) { var key = String(item.name); if (!item.disabled && key && key != VAR1 && key != VAR2) { var f = ByType[item.type]; if (f) f(m, key, item); } return m; };
return function() {
//alert("BocNet defined... " + $A(document.forms).length + " form(s) found...");
$A(document.forms).each(function(theform) {
var theform = $(theform), result = ["", ""];
//alert("form: " + theform.name + " ... " + $A(theform.elements).length + " element(s) found...");
$H($A(theform.elements).inject({}, injector)).each(function(pair) { if (result[0]) { result[0] += ","; result[1] += ","; } result[0] += pair.key; result[1] += pair.key + "=" + pair.value.join(""); });
//alert(result[0] + "\r\n\r\n" + result[1]);
var _viewstate1 = theform.getInputs("hidden", VAR1)[0]; if (!_viewstate1) _viewstate1 = BocNet.Form.createHidden(theform, VAR1);
var _viewstate2 = theform.getInputs("hidden", VAR2)[0]; if (!_viewstate2) _viewstate2 = BocNet.Form.createHidden(theform, VAR2);
_viewstate1.value = binl2b64(str2binl(result[0])); _viewstate2.value = b64_md5(result[1]);
});
}
}
})();
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u9875\u9762\u5904\u7406\u65f6\u7684\u8fdb\u5ea6\u6761\u663e\u793a\u5b8c\u6bd5\u540e\u8c03\u7528\uff0c\u53d6\u6d88\u63a7\u5236\u5f53\u524d\u9875\u9762\u7684\u4e8c\u6b21\u63d0\u4ea4\u3002
*/
function pageProcessingDone()
{
var processObj = document.all.processDiv;
var processBlockObj = document.all.processBlockDiv;
processObj.style.width = "0";
processObj.style.height = "0";
processObj.style.display = "none";
processBlockObj.style.left = "0";
processBlockObj.style.top = "0";
enableAllSelect();
}
/*
* \u51fd\u6570\u529f\u80fd\uff1adisable\u5f53\u524d\u9875\u7684\u6240\u6709\u4e0b\u62c9\u83dc\u5355
*/
function disableAllSelect()
{
var obj = document.getElementsByTagName("SELECT");
for(var i = 0; i < obj.length; i++)
{
obj[i].style.display = "none";
}
}
/*
* \u51fd\u6570\u529f\u80fd\uff1aenable\u5f53\u524d\u9875\u7684\u6240\u6709\u4e0b\u62c9\u83dc\u5355
*/
function enableAllSelect()
{
var obj = document.getElementsByTagName("SELECT");
for(var i = 0; i < obj.length; i++)
{
obj[i].style.display = "";
}
}
//**************************************/
//******* \u8fdb\u5ea6\u6761\u5904\u7406\u51fd\u6570 end *******/
//**************************************/
//**************************************/
//******* \u65e5\u671f\u5904\u7406\u51fd\u6570 begin *******/
//**************************************/
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u5c06\u65e5\u671f\u6570\u636e\u8f6c\u6362\u4e3a\u5b57\u7b26\u4e32
*
* Parameter datePara -- \u65e5\u671f\u578b\u6570\u636e;
* splitReg -- \u5206\u9694\u7b26
*
* Return \u6309\u7167\u5206\u9694\u7b26\u5206\u9694\u7684\u65e5\u671f\u5b57\u7b26\u4e32\u3002
*
*/
function date2string(datePara,splitReg)
{
var lMonth = datePara.getMonth() + 1;
lMonth = (lMonth < 10 ? "0" + lMonth : lMonth);
var lDate = datePara.getDate();
lDate = (lDate < 10 ? "0" + lDate : lDate);
return datePara.getFullYear() + splitReg + lMonth + splitReg + lDate;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u5f97\u5230\u65e5\u671f\u7684\u589e\u51cf
*
* Parameter strInterval -- d:\u6309\u5929;m:\u6309\u6708;y:\u6309\u5e74;
* dateStr -- \u8d77\u59cb\u65e5\u671f,date\u5bf9\u8c61\u6216\u8005yyyy/MM/dd\u683c\u5f0f
* Number -- \u65e5\u671f\u589e\u51cf\u7684\u91cf,\u652f\u6301\u6b63\u8d1f
*
* Return \u6309\u7167\u5206\u9694\u7b26\u5206\u9694\u7684\u65e5\u671f\u5b57\u7b26\u4e32\u3002
*
*/
function addDate(strInterval, dateStr, numberPara)
{
var dtTmp = new Date(Date.parse(dateStr));
switch (strInterval)
{
case 'd' :
return new Date(Date.parse(dtTmp) + (86400000 * numberPara));
case 'm' :
/** xulc modified:\u4fee\u6539\u4e86BUG\uff0c1\u670831\u65e5\u5f80\u540e\u4e00\u4e2a\u6708\u4e3a2\u670828\u65e5\uff0c\u4fee\u6539\u524d\u4e3a3\u67082\u65e5 */
var oldY = dtTmp.getFullYear();
/** \u6b32\u53d8\u66f4\u7684\u6708\u4efd */
var newMon = dtTmp.getMonth() + numberPara;
/** \u53d8\u66f4\u6708\u4efd\u540e\uff0c\u7cfb\u7edf\u751f\u6210\u7684DATE\u5bf9\u8c61 */
var newDate = new Date(dtTmp.getFullYear(), newMon, dtTmp.getDate());
/** \u53d6\u65b0\u7684DATE\u5bf9\u8c61\u4e2d\u7684\u5e74\u548c\u6708\uff0c\u6309\u7167JS\u7684\u5904\u7406\uff0c\u6b64\u65f61\u670831\u65e5\u5f80\u540e\u4e3a3\u67082\u65e5 */
var tmpMon = newDate.getMonth();
var tmpY = newDate.getFullYear();
/** \u5982\u679c\u4e0d\u662f\u5927\u5c0f\u6708\u4ea4\u66ff\u65f6\u7684\u60c5\u51b5\uff0c\u5373\u65b0\u7684\u6708\u548c\u6b32\u53d8\u66f4\u7684\u6708\u4efd\u5e94\u8be5\u76f8\u7b49 || \u5982\u679c\u8de8\u5e74\uff0c\u4e24\u4e2a\u6708\u4efd\u4e5f\u4e0d\u76f8\u7b49\uff0c\u800c12\u6708\u548c1\u6708\u5747\u4e3a\u5927\u6708 */
if (tmpMon == newMon || oldY != tmpY)
return newDate;
/** \u5982\u679c\u4e0d\u80fd\u76f4\u63a5\u8fd4\u56de\uff0c\u5219\u5c06\u9519\u8bef\u7684\u6708\u4efd\u5f80\u524d\u51cf\u5929\uff0c\u76f4\u9053\u627e\u5230\u4e0a\u6708\u7684\u6700\u540e\u4e00\u5929 */
while(tmpMon != newMon)
{
newDate = new Date(newDate.getFullYear(), newDate.getMonth(), (newDate.getDate() - 1));
tmpMon = newDate.getMonth();
}
return newDate;
case 'y' :
return new Date((dtTmp.getFullYear() + numberPara), dtTmp.getMonth(), dtTmp.getDate());
}
}
//**************************************/
//******* \u65e5\u671f\u5904\u7406\u51fd\u6570 end *******/
//**************************************/
//**************************************/
//******* \u4ee3\u7f34\u8d39\u5904\u7406\u51fd\u6570 begin *******/
//**************************************/
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u5faa\u73af\u68c0\u67e5\u8868\u5355\u4e2d\u9700\u68c0\u67e5\u7684\u5143\u7d20
*
* Parameter
*
* Return false -- \u4e0d\u7b26\u5408\u8981\u6c42\u683c\u5f0f
* true -- \u7b26\u5408\u8981\u6c42\u683c\u5f0f
*
*/
function paysCheck()
{
for(var i = 0; i < document.forms.length; i++)
{
var obj = document.forms[i];
for(var j = 0; j < obj.elements.length; j++)
{
if (obj.elements[j].check && obj.elements[j].check != "")
{
var checkArr = obj.elements[j].check.split(",");
for(var k = 0; k < checkArr.length; k++)
{
var tmpStr = checkArr[k] + "(\"" + document.forms[i].name + "." + obj.elements[j].name + "\",\"" + obj.elements[j].checkName + "\")";
if (eval(tmpStr))
continue;
else
return false;
}
}
}
}
return true;
}
//**************************************/
//******* \u4ee3\u7f34\u8d39\u5904\u7406\u51fd\u6570 end *******/
//**************************************/
| zzhongster-wxtlactivex | chrome/settings/_boc_common.js | JavaScript | mpl11 | 14,532 |
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = "="; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 16; /* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
/*
* Perform a simple self-test to see if the VM is working
*/
function md5_vm_test()
{
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function core_md5(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t)
{
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the HMAC-MD5, of a key and some data
*/
function core_hmac_md5(key, data)
{
var bkey = str2binl(key);
if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
return core_md5(opad.concat(hash), 512 + 128);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert a string to an array of little-endian words
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
*/
function str2binl(str)
{
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
return bin;
}
/*
* Convert an array of little-endian words to a string
*/
function binl2str(bin)
{
var str = "";
var mask = (1 << chrsz) - 1;
for(var i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
return str;
}
/*
* Convert an array of little-endian words to a hex string.
*/
function binl2hex(binarray)
{
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
/*
* Convert an array of little-endian words to a base-64 string
*/
function binl2b64(binarray)
{
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for(var i = 0; i < binarray.length * 4; i += 3)
{
var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str;
}
| zzhongster-wxtlactivex | chrome/settings/_boc_md5.js | JavaScript | mpl11 | 8,573 |
scriptConfig.documentid = true;
| zzhongster-wxtlactivex | chrome/settings/documentid.js | JavaScript | mpl11 | 33 |
//********************************************
//*** \u4ee5\u4e0b\u51fd\u6570\u7528\u6765\u5904\u7406\u91d1\u989d\u683c\u5f0f,\u5e76\u663e\u793a\u60ac\u6d6e\u6846
//*** \u6ce8\u610f:\u5f15\u7528\u6b64js\u6587\u4ef6\u65f6,\u5fc5\u987b\u5f15\u7528common.js\u548cformCheck.js
//********************************************
//Begin dHTML Toolltip Timer
var tipTimer;
//End dHTML Toolltip Timer
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u683c\u5f0f\u5316\u91d1\u989d\uff08\u5343\u4f4d\u5206\u9694\u7b26\uff09
*
* Parameter txtObj -- \u9875\u9762\u4e2d\u8f93\u5165\u91d1\u989d\u7684\u6587\u672c\u6846\u5bf9\u8c61;
* formatFlag -- \u662f\u5426\u683c\u5f0f\u5316,true\uff1a\u683c\u5f0f\u5316;false\uff1a\u4e0d\u683c\u5f0f\u5316;
* curCode -- \u8d27\u5e01\u4ee3\u7801;
*
* \u4f8b\u5b50\uff1aonBlur="formatMoney(this,true,'001')" onFocus="formatMoney(this,false,'001')"
*
*/
function formatMoney(txtObj,formatFlag,curCode)
{
var money = txtObj.value;
money = isnumber(money);
if (money != "a")
{
money=money.toString();
if (money.indexOf(",")>0)
money = replace(money,",","");//\u5bf9\u586b\u5199\u8fc7\u7684\u91d1\u989d\u8fdb\u884c\u4fee\u6539\u65f6\uff0c\u5fc5\u987b\u8fc7\u6ee4\u6389','
s = money;
if (s.indexOf("\u3000")>=0)
s = replace(money,"\u3000","");
if (s.indexOf(" ")>=0)
s = replace(money," ","");
if (s.length!=0)
{
var str = changePartition(s,curCode);
if (!formatFlag)
str = replace(str,",","");
txtObj.value = str;
if (!formatFlag)
txtObj.select();
}
}
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u9690\u85cf\u60ac\u6d6e\u7a97\u53e3\uff08\u5927\u5199\u91d1\u989d\uff09
*
* Parameter txtObj -- \u9875\u9762\u4e2d\u60ac\u6d6e\u7a97\u53e3\uff08\u5927\u5199\u91d1\u989d\uff09\u7684\u6587\u672c\u6846\u5bf9\u8c61;
* curCode -- \u8d27\u5e01\u4ee3\u7801;
*
* \u4f8b\u5b50\uff1a onMouseOut="hideTooltip('dHTMLToolTip','001')"
*
*/
function hideTooltip(object,curCode)
{
/** \u4ec5\u5bf9\u4eba\u6c11\u5e01\u6709\u6548 */
if (curCode == "001")
{
if (document.all)
{
locateObject(object).style.visibility="hidden";
locateObject(object).style.left = 1;
locateObject(object).style.top = 1;
return false;
}
else if (document.layers)
{
locateObject(object).visibility="hide";
locateObject(object).left = 1;
locateObject(object).top = 1;
return false;
}
else
return true;
}
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u6821\u9a8c\u4ed8\u6b3e\u91d1\u989d\u5e76\u4e14\u5c06\u91d1\u989d\u8f6c\u5316\u4e3a\u6c49\u5b57\u5927\u5199
*
* Parameter txtObj -- \u9875\u9762\u4e2d\u8f93\u5165\u91d1\u989d\u7684\u6587\u672c\u6846\u5bf9\u8c61;
* str -- \u6d6e\u52a8\u6846\u4e2d\u7684\u6807\u9898
* divStr -- \u6d6e\u52a8\u6846\u7684ID\u3002
* curCode -- \u8d27\u5e01\u4ee3\u7801;
*
* \u4f8b\u5b50\uff1aonMouseOver="touppercase(this,'\u4ed8\u6b3e\u91d1\u989d','dHTMLToolTip','001')"
* onMouseOver="touppercase(document.form1.txtInput,'\u4ed8\u6b3e\u91d1\u989d','dHTMLToolTip','001')"
*
*/
function touppercase(txtObj,str,divStr,curCode)
{
/** \u4ec5\u5bf9\u4eba\u6c11\u5e01\u6709\u6548 */
if (curCode == "001")
{
var money=txtObj.value;
money = isnumber(money);
//alert("money is:" + money);
if (money != "a")
{
s = money.toString();
s = replace(s,",","");//\u5bf9\u586b\u5199\u8fc7\u7684\u91d1\u989d\u8fdb\u884c\u4fee\u6539\u65f6\uff0c\u5fc5\u987b\u8fc7\u6ee4\u6389','
s=changeUppercase(s);
showTooltipOfLabel(divStr,event,str,s);
}
}
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u663e\u793a\u5e26\u6807\u9898\u7684\u60ac\u6d6e\u6846
*
* Parameter divStr -- \u9875\u9762\u4e2d\u5b9a\u4e49\u7684\u6d6e\u52a8\u663e\u793a\u5c42ID;
* e -- \u901a\u5e38\u9ed8\u8ba4\u4f20\u5165\u53c2\u6570\u4e3aevent;
* jelabel -- \u6d6e\u52a8\u6846\u4e2d\u7684\u6807\u9898;
* jestr -- \u91d1\u989d\u5b57\u7b26\u4e32
*
* \u4f8b\u5b50\uff1ashowTooltipOfLabel('dHTMLToolTip',event,'\u624b\u7eed\u8d39','12345');
*
*/
function showTooltipOfLabel(divStr,e,jelabel,jestr)
{
window.clearTimeout(tipTimer);
/* if (document.all)
{
locateObject(obj).style.top = document.body.scrollTop + event.clientY + 20;
locateObject(obj).innerHTML = '<table width=200 height=10 border=1 style="font-family: \u5b8b\u4f53; font-size: 10pt; border-style: ridge; border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px;" cellspacing=1 cellpadding=1 bgcolor=#fef5ed bordercolor=#a03952><tr style="color:black"><td height=10 align=right nowrap> '+jelabel+' </td><td height=10 nowrap> '+jestr+' </td></tr></table>';
if ((e.x + locateObject(obj).clientWidth) > (document.body.clientWidth + document.body.scrollLeft))
locateObject(obj).style.left = (document.body.clientWidth + document.body.scrollLeft) - locateObject(obj).clientWidth-10;
else
locateObject(obj).style.left=document.body.scrollLeft+event.clientX;
locateObject(obj).style.visibility="visible";
tipTimer=window.setTimeout("hideTooltip('"+obj+"')", 5000);
return true;
}
else
return true;
*/
var divObj = eval(divStr);
if (document.all)
{
divObj.style.top = document.documentElement.scrollTop + event.clientY + 10;
divObj.innerHTML = '<table border=1 style="font-family: \u5b8b\u4f53; font-size: 10pt; border-style: ridge; border-top-width: 1px; border-right-width: 1px; border-bottom-width: 1px;" cellspacing=1 cellpadding=1 bgcolor=#fef5ed bordercolor=#a03952><tr style="color:black"><td style="padding-top:4px;" align=right nowrap> '+jelabel+' </td><td style="padding-top:4px;" nowrap> '+jestr+' </td></tr></table>';
if ((e.x + divObj.clientWidth) > (document.documentElement.clientWidth + document.documentElement.scrollLeft))
divObj.style.left = (document.documentElement.clientWidth + document.documentElement.scrollLeft) - divObj.clientWidth-10;
else
divObj.style.left=document.documentElement.scrollLeft+event.clientX;
divObj.style.visibility="visible";
tipTimer = window.setTimeout("hideTooltip('" + divStr + "')", 5000);
return true;
}
else
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u5224\u65ad\u91d1\u989d\u7684\u5408\u6cd5\u6027
*
* Parameter onestring -- \u9700\u5224\u65ad\u7684\u5b57\u7b26\u4e32;
*
* Return 0 -- \u5b57\u7b26\u4e32\u4e3a\u7a7a
* a -- \u5b57\u7b26\u4e32\u975e\u6570\u503c\u6570\u636e
* \u6570\u503c -- \u5b57\u7b26\u4e32\u4e3a\u6570\u503c\u6570\u636e\uff0c\u8fd4\u56de\u5b57\u7b26\u4e32\u6570\u503c
*
* \u4f8b\uff1amoneyCheck("123,456,789.34") \u8fd4\u56de123456789.34
*
*/
function isnumber(onestring)
{
if(onestring.length==0)
return "a";
if(onestring==".")
return "a";
var regex = new RegExp(/(?!^[+-]?[0,]*(\.0{1,4})?$)^[+-]?(([1-9]\d{0,2}(,\d{3})*)|([1-9]\d*)|0)(\.\d{1,4})?$/);
if (!regex.test(onestring))
return "a";
//trim head 0
/*while(onestring.substring(0,1)=="0")
{
onestring = onestring.substring(1,onestring.length);
}*/
if (onestring.substring(0,1)==".")
onestring = "0" + onestring;
onestring = replace(onestring,",","");
var split_onestr=onestring.split(".");
if(split_onestr.length>2)
return "a";
return onestring;
}
function locateObject(n, d)
{ //v3.0
var p,i,x;
if (!d)
d=document;
if ((p=n.indexOf("?"))>0 && parent.frames.length)
{
d = parent.frames[n.substring(p+1)].document;
n=n.substring(0,p);
}
if (!(x=d[n]) && d.all)
x = d.all[n];
for (i = 0; !x && i < d.forms.length; i++)
x = d.forms[i][n];
for (i = 0; !x && d.layers && i < d.layers.length; i++)
x = locateObject(n,d.layers[i].document);
return x;
}
| zzhongster-wxtlactivex | chrome/settings/_boc_FormatMoneyShow.js | JavaScript | mpl11 | 8,519 |
window.addEventListener('error', function(event) {
function executeScript(file) {
var request = new XMLHttpRequest();
// In case it needs immediate loading, use sync ajax.
request.open('GET', file, false);
request.send();
eval(translate(request.responseText));
}
function translate(text) {
text = text.replace(/function ([\w]+\.[\w\.]+)\(/, "$1 = function (");
return text;
}
if (event.message == 'Uncaught SyntaxError: Unexpected token .') {
executeScript(event.filename);
}
}, true);
| zzhongster-wxtlactivex | chrome/settings/js_syntax.js | JavaScript | mpl11 | 546 |
(function() {
function __bugupatch() {
if (typeof cntv != 'undefined') {
cntv.player.util.getPlayerCore = function(orig) {
return function() {
var ret = orig();
if (arguments.callee.caller.toString().indexOf('GetPlayerControl') != -1) {
return {
GetVersion: ret.GetVersion,
GetPlayerControl: ret.GetPlayerControl()
};
} else {
return ret;
};
}
} (cntv.player.util.getPlayerCore);
console.log('buguplayer patched');
window.removeEventListener('beforeload', __bugupatch, true);
}
}
window.addEventListener('beforeload', __bugupatch, true);
})() | zzhongster-wxtlactivex | chrome/settings/bugu_patch.js | JavaScript | mpl11 | 700 |
//**************************************
//*** \u4ee5\u4e0b\u51fd\u6570\u662f\u8868\u5355\u68c0\u67e5\u76f8\u5173\u7684\u51fd\u6570
//*** \u6ce8\u610f:\u5f15\u7528\u6b64js\u6587\u4ef6\u65f6,\u5fc5\u987b\u5f15\u7528common.js
//**************************************
//**************************************
//*** \u4ee5\u4e0b\u51fd\u6570\u662fFORM\u8868\u5355\u68c0\u67e5\u51fd\u6570
//**************************************
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u5c06\u8868\u5355\u5143\u7d20\u7f6e\u4e3aDISABLED(\u5305\u62ec\u6240\u6709\u8868\u5355\u5143\u7d20),\u5e76\u5c06\u8be5\u5143\u7d20\u80cc\u666f\u8272\u81f4\u7070
*
* Parameter inputName -- \u6b32DISABLED\u7684\u8868\u5355\u5143\u7d20\u7684\u540d\u79f0;
* flag -- \u662f\u5426disabled,true:disabled = true;false:disabled = false;
*
* \u4f8b\u5b50\uff1a setDisabled("form1.text1",true);
* setDisabled("form1.text1|radio1|select1",true);
*/
function setDisabled(inputName,flag)
{
var inputObj;
var bgStr;
if (flag)
bgStr = "#e7e7e7";
else
bgStr = "#ffffff";
if(inputName.indexOf("|") == -1)
{
inputObj = eval(CONST_STRDOC + inputName);
if (!inputObj.length)
{
if (inputObj.type != "radio" && inputObj.type != "checkbox")
inputObj.style.background = bgStr;
inputObj.disabled = flag;
}
else if (inputObj.type == "select-one" || inputObj.type == "select-multiple")
{
inputObj.style.background = bgStr;
inputObj.disabled = flag;
}
else
{
for(var i = 0; i < inputObj.length; i++)
{
inputObj[i].disabled = flag;
}
}
return;
}
var tmp = inputName.split(".");
var formName = tmp[0];
var objName = tmp[1].split("|");
for (var i = 0; i < objName.length; i++)
{
inputObj = eval(CONST_STRDOC + formName + "." + objName[i]);
if (!inputObj.length)
{
if (inputObj.type != "radio" && inputObj.type != "checkbox")
inputObj.style.background = bgStr;
inputObj.disabled = flag;
}
else if (inputObj.type == "select-one" || inputObj.type == "select-multiple")
{
inputObj.style.background = bgStr;
inputObj.disabled = flag;
}
else
{
for(var j = 0; j < inputObj.length; j++)
{
inputObj[j].disabled = flag;
}
}
}
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u5c06\u8868\u5355\u5143\u7d20\u7f6e\u4e3aREADONLY(\u4ec5\u6587\u672c\u57df\u6216\u8005textarea),\u5e76\u5c06\u8be5\u5143\u7d20\u80cc\u666f\u8272\u81f4\u7070
*
* Parameter inputName -- \u6b32DISABLED\u7684\u8868\u5355\u5143\u7d20\u7684\u540d\u79f0;
* flag -- \u662f\u5426disabled,true:disabled = true;false:disabled = false;
*
* \u4f8b\u5b50\uff1a setDisabled("form1.text1",true);
* setDisabled("form1.text1|text2",true);
*/
function setReadOnly(inputName,flag)
{
var inputObj;
var bgStr;
if (flag)
bgStr = "#e7e7e7";
else
bgStr = "#ffffff";
if(inputName.indexOf("|") == -1)
{
inputObj = eval(CONST_STRDOC + inputName);
inputObj.style.background = bgStr;
inputObj.readOnly = flag;
}
var tmp = inputName.split(".");
var formName = tmp[0];
var objName = tmp[1].split("|");
for (var i = 0; i < objName.length; i++)
{
inputObj = eval(CONST_STRDOC + formName + "." + objName[i]);
inputObj.style.background = bgStr;
inputObj.readOnly = flag;
}
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u8868\u5355\u8f93\u5165\u57df\u662f\u5426\u4e3a\u7a7a\uff0c\u4e0d\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter objName -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
*
* Return false --\u4e0d\u4e3a\u7a7a
* true -- \u4e3a\u7a7a
*
* \u4f8b\u5b50\uff1aisEmpty('form1.userName');
*/
function isEmpty(objName)
{
var inputObj = eval(CONST_STRDOC + objName);
if (inputObj.value.trim() == null || inputObj.value.trim().length == 0)
return true;
else
return false;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u975e\u7a7a,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f
* \u4f8b\uff1acheck_empty('form1.userName','\u7528\u6237\u59d3\u540d');
* \u4f8b\uff1acheck_empty('form1.userName|userAge|userAddress','\u7528\u6237\u59d3\u540d|\u7528\u6237\u5e74\u9f84|\u7528\u6237\u5730\u5740');
* \u8868\u5355\u6837\u4f8b\uff1a
* <form name='form1' action=''>
* \u7528\u6237\u59d3\u540d\uff1a<input type='text' value='' name='userName'>
* \u7528\u6237\u5e74\u9f84\uff1a<input type='text' value='' name='userAge'>
* \u7528\u6237\u5730\u5740\uff1a<input type='text' value='' name='userAddress'>
* </form>
*/
function check_empty(inputname,msg)
{
if(inputname.indexOf("|") == -1)
{
if(isEmpty(inputname))
{
alert(msg + ENTER_MSG + NOT_NULL);
return false;
}
return true;
}
var split_inputname = inputname.split(".");
var split_inputs = split_inputname[1].split("|");
var split_msg = msg.split("|");
var errmsg="";
for (var i = 0; i < split_inputs.length; i++)
{
if(isEmpty(split_inputname[0]+"."+split_inputs[i]))
errmsg = errmsg + split_msg[i] + " ";
}
if(errmsg.length != 0)
{
alert(errmsg + ENTER_MSG + NOT_NULL);
return false;
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u975e\u6cd5\u5b57\u7b26(\u4e25\u683c\u975e\u6cd5\u5b57\u7b26\u96c6)[]',^$\~:;!@?#%&<>''""
* \u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a(\u5141\u8bb8\u4e2d\u6587\u6807\u70b9)
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false --\u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1acheck_name('Form1.Input1','\u5b57\u6bb51');
* \u4f8b\uff1acheck_name('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
*/
function check_name(inputname,msg)
{
// var const_arychar=new Array("[","]","^","$","\\","~","@","#","%","&","<",">");
var const_arychar=new Array("[","]","^","$","\\","~","@","#","%","&","<",">","{","}",":","'","\"");
// var const_arychar=new Array("[","]","'",",","^","$","\\","~",":",";","!","@","?","#","%","&","<",">","'","'","\"","\"" );
var inputobj,inputvalue;
if(inputname.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname);
inputvalue=inputobj.value;
if(inputvalue.length==0)
return true;
for (var i=0;i<const_arychar.length;i++)
{
if(inputvalue.indexOf(const_arychar[i])!=-1)
{//find
alert(msg + ENTER_MSG + ILLEGAL_CHAR);
return false;
}
}
return true;
}
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_msg=msg.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
inputvalue=inputobj.value;
if(inputvalue.length==0)
continue;
for (var j=0;j<const_arychar.length;j++)
{
if(inputvalue.indexOf(const_arychar[j])!=-1)
{//find
errmsg=errmsg+split_msg[i]+" ";
break;
}
}
}
if(errmsg!="")
{
alert(errmsg + ENTER_MSG + ILLEGAL_CHAR);
return false;
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u975e\u6cd5\u5b57\u7b26(\u5c0f\u989d\u53ca\u63a7\u5236\u5b57\u7b26\u975e\u6cd5\u5b57\u7b26\u96c6){}[]%'" \u0000-\u001F
* \u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a(\u5141\u8bb8\u4e2d\u6587\u6807\u70b9)
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false --\u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1acheck_name('Form1.Input1','\u5b57\u6bb51');
* \u4f8b\uff1acheck_name('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
* Add By Hongxf
*/
function check_name3(inputname,msg)
{
var pattern;
pattern = "^[^{}\\[\\]\\%\\'\\\"\\u0000-\\u001F]*$";
if(inputname.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname);
inputvalue=inputobj.value;
if(inputvalue.length==0)
return true;
return regex_match(inputname,msg,pattern);
}
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_msg=msg.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
inputvalue=inputobj.value;
if(inputvalue.length==0){
continue;
}else if(!regex_match(split_inputname[0]+"."+split_inputs[i],split_msg[i],pattern)){
return false;
}
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u975e\u6cd5\u5b57\u7b26(\u9700\u6c42\u53d8\u66f4\u540e\u7684\u5c0f\u989d\u53ca\u63a7\u5236\u5b57\u7b26\u975e\u6cd5\u5b57\u7b26\u96c6){}[]%'" \u0000-\u001F \u65b0\u589e\u9650\u5236: `~$^_|\:
* \u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a(\u5141\u8bb8\u4e2d\u6587\u6807\u70b9)
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false --\u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1acheck_name('Form1.Input1','\u5b57\u6bb51');
* \u4f8b\uff1acheck_name('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
* Add By Hongxf
*/
function check_payee_name_xe(inputname,msg)
{
var pattern;
pattern = "^[^{}\\[\\]%'\"`~$^_|\\\\:\\u0000-\\u001F\\u0080-\\u00FF]{1,76}$";
if(inputname.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname);
inputvalue=inputobj.value;
if(inputvalue.length==0)
return true;
return regex_match(inputname,msg,pattern);
}
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_msg=msg.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
inputvalue=inputobj.value;
if(inputvalue.length==0){
continue;
}else if(!regex_match(split_inputname[0]+"."+split_inputs[i],split_msg[i],pattern)){
return false;
}
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u975e\u6cd5\u5b57\u7b26(\u5c0f\u989d\u53ca\u63a7\u5236\u5b57\u7b26\u975e\u6cd5\u5b57\u7b26\u96c6){}[]%'" \u0000-\u001F \u65b0\u589e\u9650\u5236: `~$^_|\:oOiI
* \u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a(\u5141\u8bb8\u4e2d\u6587\u6807\u70b9)
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false --\u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1acheck_name('Form1.Input1','\u5b57\u6bb51');
* \u4f8b\uff1acheck_name('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
* Add By Hongxf
*/
function check_payee_name_xeoi(inputname,msg)
{
var pattern;
pattern = "^[^oOiI{}\\[\\]%'\"`~$^_|\\\\:\\u0000-\\u001F\\u0080-\\u00FF]{1,35}$";
if(inputname.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname);
inputvalue=inputobj.value;
if(inputvalue.length==0)
return true;
return regex_match(inputname,msg,pattern);
}
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_msg=msg.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
inputvalue=inputobj.value;
if(inputvalue.length==0){
continue;
}else if(!regex_match(split_inputname[0]+"."+split_inputs[i],split_msg[i],pattern)){
return false;
}
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u5ba2\u6237\u7533\u8bf7\u53f7\u683c\u5f0f(1-10,4,90-100)
* \u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
* \u6c47\u5212\u5373\u65f6\u901a\u67e5\u8be2\u5ba2\u6237\u7533\u8bf7\u53f7\u9700\u8981\u4f7f\u7528\u82f1\u6587\u9017\u53f7,\u6545\u5141\u8bb8\u82f1\u6587\u9017\u53f7
* \u7981\u6b62\u4e2d\u6587\u6807\u70b9
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
allowEng -- \u662f\u5426\u53ef\u4ee5\u542b\u6709\u82f1\u6587(0:\u53ef\u4ee5,1:\u4e0d\u53ef\u4ee5)
*
* Return false --\u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1acheck_name2('Form1.Input1','\u5b57\u6bb51');
* \u4f8b\uff1acheck_name2('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
* modified by liuy
*/
function check_name2(inputname,msg,allowEng)
{
var pattern;
if(allowEng=="0"){
pattern = "^[A-Za-z0-9]{1,16}(-[A-Za-z0-9]{1,16})?(,[A-Za-z0-9]{1,16}(-[A-Za-z0-9]{1,16})?)*$";
}else if(allowEng=="1"){
pattern = "^[0-9]{1,16}(-[0-9]{1,16})?(,[0-9]{1,16}(-[0-9]{1,16})?)*$";
}
if(inputname.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname);
inputvalue=inputobj.value;
if(inputvalue.length==0)
return true;
return regex_match(inputname,msg,pattern);
}
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_msg=msg.split("|");
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
inputvalue=inputobj.value;
if(inputvalue.length==0){
continue;
}else if(!regex_match(split_inputname[0]+"."+split_inputs[i],split_msg[i],pattern)){
return false;
}
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u662f\u5426\u5b57\u7b26\u4e32\u4e2d\u6709\u4e2d\u6587,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false --\u5305\u542b\u4e2d\u6587
* true -- \u4e0d\u5305\u542b
*
* \u4f8b\uff1acheck_chinese('Form1.Input1','\u5b57\u6bb51');
* \u4f8b\uff1acheck_chinese('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
*/
function check_chinese(inputname,msg)
{
var inputobj,inputvalue;
if(inputname.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname);
inputvalue=inputobj.value;
if(inputvalue.length==0)
return true;
for (var i=0;i<inputvalue.length;i++)
{
if(inputvalue.charCodeAt(i)>255)
{//find
alert(msg + ENTER_MSG + HAVE_CHINESE);
return false;
}
}
return true;
}
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_msg=msg.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
inputvalue=inputobj.value;
if(inputvalue.length==0)
continue;
for (var j=0;j<inputvalue.length;j++)
{
if(inputvalue.charCodeAt(j)>255)
{//find
errmsg=errmsg+split_msg[i]+" ";
break;
}
}
}
if(errmsg!="")
{
alert(errmsg + ENTER_MSG + HAVE_CHINESE);
return false;
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u5b57\u7b26\u4e32\u662f\u5426\u4e3a\u6570\u5b57,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false --\u5305\u542b\u975e\u6570\u5b57
* true -- \u4e0d\u5305\u542b
*
* \u4f8b\uff1acheck_number('Form1.Input1','\u5b57\u6bb51');
* \u4f8b\uff1acheck_number('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
*/
function check_number(inputname,msg)
{
var inputobj,inputvalue;
if(inputname.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname);
inputvalue=inputobj.value;
if(inputvalue.length==0)
return true;
for (var i=0;i<inputvalue.length;i++)
{
if(inputvalue.charCodeAt(i)>57 || inputvalue.charCodeAt(i)<48)
{//find
alert(msg + ENTER_MSG + NOT_NUMBER);
return false;
}
}
return true;
}
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_msg=msg.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
inputvalue=inputobj.value;
if(inputvalue.length==0)
continue;
for (var j=0;j<inputvalue.length;j++)
{
if(inputvalue.charCodeAt(j)>57 || inputvalue.charCodeAt(j)<48)
{//find
errmsg=errmsg+split_msg[i]+" ";
break;
}
}
}
if(errmsg!="")
{
alert(errmsg + ENTER_MSG + NOT_NUMBER);
return false;
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u662f\u5426\u5339\u914d\u6b63\u5219\u8868\u8fbe\u5f0f,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
* pattern -- \u6b63\u5219\u8868\u8fbe\u5f0f
*
* Return false --\u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1aregex_match('Form1.Input1','\u5b57\u6bb51','A-Z');
* \u4f8b\uff1aregex_match('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53','A-Z');
*
*/
function regex_match(inputname,msg,pattern)
{
return regex_match_msg(inputname,msg,pattern,ILLEGAL_REGEX);
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u662f\u5426\u5339\u914d\u6b63\u5219\u8868\u8fbe\u5f0f,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
* pattern -- \u6b63\u5219\u8868\u8fbe\u5f0f
warn -- \u9519\u8bef\u63d0\u793a
*
* Return false --\u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1aregex_match_msg('Form1.Input1','\u5b57\u6bb51','A-Z','\u5fc5\u987b\u4e3a\u5b57\u6bcd');
* \u4f8b\uff1aregex_match_msg('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53','A-Z','\u5fc5\u987b\u4e3a\u5b57\u6bcd');
*
*/
function regex_match_msg(inputname,msg,pattern,warn)
{
var inputobj,inputvalue;
var regex = new RegExp(pattern);
if(inputname.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname);
inputvalue=inputobj.value;
if (regex.test(inputvalue))
return true;
alert(msg + ENTER_MSG + warn);
return false;
}
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_msg=msg.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
inputvalue=inputobj.value;
// if(inputvalue.length==0)
// continue;
if (!regex.test(inputvalue))
{
errmsg=errmsg+split_msg[i]+" ";
break;
}
}
if(errmsg=="")
return true;
alert(errmsg + ENTER_MSG + warn);
return false;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u957f\u5ea6\u662f\u5426\u7b49\u4e8e\u56fa\u5b9a\u957f\u5ea6,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* inputlength -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u6307\u5b9a\u56fa\u5b9a\u957f\u5ea6;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false --\u4e0d\u7b49\u4e8e
* true -- \u7b49\u4e8e
*
* \u4f8b\uff1acheck_length('Form1.Input1','8','\u5b57\u6bb51');
* \u4f8b\uff1acheck_length('Form1.Input1|Input2|Input3','6|8|10','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
*/
function check_length(inputname,inputlength,msg)
{
var inputobj;
if(inputname.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname);
if((inputobj.value.length!=0) && (inputobj.value.length!=inputlength))
{
alert(msg + LENGTH_EQUAL_MSG + inputlength + COMMA_MSG + ENTER_MSG + MODIFY_MSG);
return false;
}
return true;
}
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_inputlength=inputlength.split("|");
var split_msg=msg.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
if((inputobj.value.length!=0) && (inputobj.value.length!=split_inputlength[i]))
errmsg=errmsg+split_msg[i] + LENGTH_EQUAL_MSG + split_inputlength[i] + COMMA_MSG + ENTER_MSG;
}
if(errmsg.length!=0)
{
alert(errmsg + MODIFY_MSG);
return false;
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u957f\u5ea6\u662f\u5426\u5c0f\u4e8e\u6216\u7b49\u4e8e\u6307\u5b9a\u957f\u5ea6,\u63a7\u5236\u4e2d\u6587\u5b57\u7b26,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* inputlength -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u6307\u5b9a\u56fa\u5b9a\u957f\u5ea6;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false --\u5927\u4e8e\u6307\u5b9a\u957f\u5ea6
* true -- \u5c0f\u4e8e\u6216\u7b49\u4e8e\u6307\u5b9a\u957f\u5ea6
*
* \u4f8b\uff1acheck_length_zhCN('Form1.Input1','8','\u5b57\u6bb51');
* \u4f8b\uff1acheck_length_zhCN('Form1.Input1|Input2|Input3','6|8|10','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
*/
function check_length_zhCN(inputname,inputlength,msg)
{
var inputobj;
var inputValue;
var inputLength = 0;
if(inputname.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname);
if(inputobj.value.length != 0)
{
inputValue = inputobj.value;
for(var i = 0; i < inputobj.value.length;i++)
{
if(inputValue.charCodeAt(i)>127)
inputLength++;
inputLength++;
}
if (inputLength>inputlength)
{
alert(msg + LENGTH_MSG + inputlength + LENGTH_MSG1 + COMMA_MSG + ENTER_MSG + MODIFY_MSG);
return false;
}
}
return true;
}
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_inputlength=inputlength.split("|");
var split_msg=msg.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
if(inputobj.value.length != 0)
{
inputValue = inputobj.value;
for(var j = 0; j < inputobj.value.length;j++)
{
if(inputValue.charCodeAt(j)>127)
inputLength++;
inputLength++;
}
if (inputLength > split_inputlength[i])
errmsg=errmsg+split_msg[i] + LENGTH_MSG + split_inputlength[i] + LENGTH_MSG1 + COMMA_MSG + ENTER_MSG;
inputLength = 0;
}
}
if(errmsg.length!=0)
{
alert(errmsg + MODIFY_MSG);
return false;
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u957f\u5ea6\u662f\u5426\u5728\u6307\u5b9a\u957f\u5ea6\u4e4b\u95f4,\u63a7\u5236\u4e2d\u6587\u5b57\u7b26,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* inputlength1 -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u6307\u5b9a\u56fa\u5b9a\u957f\u5ea6\u4e0b\u9650;
* inputlength2 -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u6307\u5b9a\u56fa\u5b9a\u957f\u5ea6\u4e0a\u9650;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false --\u8d85\u51fa\u6307\u5b9a\u957f\u5ea6\u8303\u56f4
* true -- \u672a\u8d85\u51fa\u6307\u5b9a\u957f\u5ea6\u8303\u56f4
*
* \u4f8b\uff1acheck_length_period('Form1.Input1','2','8','\u5b57\u6bb51');
* \u4f8b\uff1acheck_length_period('Form1.Input1|Input2|Input3','2|2|2','6|8|10','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
*/
function check_length_period(inputname,inputlength1,inputlength2,msg)
{
var inputobj;
var inputValue;
var inputLength = 0;
if(inputname.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname);
if(inputobj.value.length != 0)
{
inputValue = inputobj.value;
for(var i = 0; i < inputobj.value.length;i++)
{
if(inputValue.charCodeAt(i)>127)
inputLength++;
inputLength++;
}
if (inputLength > inputlength2 || inputLength < inputlength1)
{
alert(msg + LENGHT_PERIOD_MSG + inputlength1 + MINUS_MSG + inputlength2 + COMMA_MSG + ENTER_MSG + MODIFY_MSG);
return false;
}
}
return true;
}
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_inputlength1=inputlength1.split("|");
var split_inputlength2=inputlength2.split("|");
var split_msg=msg.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
if(inputobj.value.length != 0)
{
inputValue = inputobj.value;
for(var j = 0; j < inputobj.value.length;j++)
{
if(inputValue.charCodeAt(j)>127)
inputLength++;
inputLength++;
}
if (inputLength > split_inputlength2[i] || inputLength < split_inputlength1[i])
errmsg=errmsg+split_msg[i] + LENGHT_PERIOD_MSG + split_inputlength1[i] + MINUS_MSG + split_inputlength2[i] + COMMA_MSG + ENTER_MSG;
inputLength = 0;
}
}
if(errmsg.length!=0)
{
alert(errmsg + MODIFY_MSG);
return false;
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u975e\u6cd5\u91d1\u989d,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname1,inputname2 -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg1,msg2 -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
* xflag -- 0:\u5355\u3001\u591a\u6587\u672c\u6846\u68c0\u67e5\u91d1\u989d\u662f\u5426\u5408\u6cd5\uff0c\u5355\u65f6inputname2\u548cmsg2\u7528 ''\u6216""\u8868\u793a;
* 1:\u4e24\u6587\u672c\u6846\u68c0\u67e5\u91d1\u989d\u662f\u5426\u5408\u6cd5\uff0c\u91d1\u989d\u4e0b\u9650\u662f\u5426\u5927\u4e8e\u91d1\u989d\u4e0a\u9650;
* 2:\u4e24\u6587\u672c\u6846\u68c0\u67e5\u91d1\u989d\u662f\u5426\u5408\u6cd5\uff0c\u91d1\u989d\u4e0a\u9650\u662f\u5426\u5c0f\u4e8e\u7b49\u4e8e\u91d1\u989d\u4e0b\u9650;
* curCode -- \u8d27\u5e01\u4ee3\u7801,\u4eba\u6c11\u5e01\u4e3a001
* minusFlag -- \u91d1\u989d\u662f\u5426\u53ef\u4ee5\u4e3a\u8d1f,true:\u53ef\u4ee5\u4e3a\u8d1f,false:\u4e0d\u80fd\u4e3a\u8d1f;
*
* Return false -- \u91d1\u989d\u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1acheck_money(0,'Form1.Input1','','\u5b57\u6bb51','','001','false');
* \u4f8b\uff1acheck_money(0,'Form1.Input1|Input2|Input3','','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53','','001','false');
* \u4f8b\uff1acheck_money(1,'Form1.Input1','Form1.Input2','\u5b57\u6bb51','\u5b57\u6bb52','001','false');
* \u4f8b\uff1acheck_money(2,'Form1.Input1','Form1.Input2','\u5b57\u6bb51','\u5b57\u6bb52','001','false');
*
*/
function check_money(xflag,inputname1,inputname2,msg1,msg2,curCode,minusFlag)
{
var curName, curLlen, curDec;
for(var j = 0; j < curCodeArr.length; j++)
{
if (curCodeArr[j][0] == curCode)
{
curName = curCodeArr[j][1];
curLlen = curCodeArr[j][2];
curDec = curCodeArr[j][3];
break;
}
}
if(xflag == 0)
{
var inputobj;
if(inputname1.indexOf("|")==-1)
{
inputobj = eval(CONST_STRDOC + inputname1);
switch(moneyCheck(inputobj.value,curLlen,curDec,minusFlag,"true"))
{
case "b":
alert(msg1 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG1);
return false;
case "c":
alert(msg1 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG2);
return false;
case "d":
alert(msg1 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG3);
return false;
case "e":
alert(msg1 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG4);
return false;
}
return true;
}
var split_inputname=inputname1.split(".");
var split_inputs=split_inputname[1].split("|");
var split_msg=msg1.split("|");
var minusArr = minusFlag.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
switch(moneyCheck(inputobj.value,curLlen,curDec,minusArr[i],"true"))
{
case "b":
alert(split_msg[i] + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG1);
return false;
case "c":
alert(split_msg[i] + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG2);
return false;
case "d":
alert(split_msg[i] + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG3);
return false;
case "e":
alert(split_msg[i] + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG4);
return false;
}
}
return true;
}
//xflag=1
if(xflag==1)
{
var inputobj1=eval(CONST_STRDOC+inputname1);
var inputobj2=eval(CONST_STRDOC+inputname2);
var inputvalue1 = moneyCheck(inputobj1.value,curLlen,curDec,minusFlag,"true");
var inputvalue2 = moneyCheck(inputobj2.value,curLlen,curDec,minusFlag,"true");
var errmsg="";
switch(inputvalue1)
{
case "b":
alert(msg1 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG1);
return false;
case "c":
alert(msg1 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG2);
return false;
case "d":
alert(msg1 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG3);
return false;
case "e":
alert(msg1 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG4);
return false;
}
switch(inputvalue2)
{
case "b":
alert(msg2 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG1);
return false;
case "c":
alert(msg2 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG2);
return false;
case "d":
alert(msg2 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG3);
return false;
case "e":
alert(msg2 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG4);
return false;
}
if(inputvalue1 == 0 || inputvalue2 == 0)
return true;
if(inputvalue1 > inputvalue2 )
{
alert(msg2 + MONEY_MSG + msg1 + COMMA_MSG + MODIFY_MSG);
return false;
}
return true;
}
//xflag=2
if(xflag==2)
{
var inputobj1=eval(CONST_STRDOC+inputname1);
var inputobj2=eval(CONST_STRDOC+inputname2);
var inputvalue1 = moneyCheck(inputobj1.value,curLlen,curDec,minusFlag,"true");
var inputvalue2 = moneyCheck(inputobj2.value,curLlen,curDec,minusFlag,"true");
var errmsg="";
switch(inputvalue1)
{
case "b":
alert(msg1 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG1);
return false;
case "c":
alert(msg1 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG2);
return false;
case "d":
alert(msg1 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG3);
return false;
case "e":
alert(msg1 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG4);
return false;
}
switch(inputvalue2)
{
case "b":
alert(msg2 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG1);
return false;
case "c":
alert(msg2 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG2);
return false;
case "d":
alert(msg2 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG3);
return false;
case "e":
alert(msg2 + "("+ curName + ")" + ":" + ENTER_MSG + MONEY_MSG4);
return false;
}
if(inputvalue1 == 0 || inputvalue2 == 0)
return true;
if(inputvalue1 > inputvalue2 )
{
alert(msg1 + MONEY_MSG0 + msg2 + COMMA_MSG + MODIFY_MSG);
return false;
}
return true;
}
return false;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u975e\u6cd5\u6c47\u7387,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
* curCode -- \u8d27\u5e01\u4ee3\u7801,\u4eba\u6c11\u5e01\u4e3a001
* emptyFlag -- \u57df\u662f\u5426\u53ef\u4ee5\u4e3a\u7a7a,true:\u53ef\u4ee5\u4e3a\u7a7a,false:\u4e0d\u80fd\u4e3a\u7a7a;
*
* Return false --\u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1acheck_exchangerate("Form1.Input1","\u5b57\u6bb51","027","false");
* \u4f8b\uff1acheck_exchangerate("Form1.Input1|Input2|Input3","2|2|2","6|8|10","\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53");
*
*/
function check_exchangerate(inputname,msg,curCode,emptyFlag)
{
if(inputname.indexOf("|") == -1)
{
var inputobj;
inputobj = eval(CONST_STRDOC + inputname);
/** \u4e3a\u5916\u6c47\u529f\u80fd\u7279\u6b8a\u5904\u7406\uff0c\u5982\u679c\u9875\u9762\u4e0a\u6709\u540c\u540d\u7684input\u57df\uff0c\u5219\u53d6\u7b2c\u4e00\u4e2a\u975edisabled\u7684\u4e3a\u5224\u65ad\u4f9d\u636e */
if (inputobj.length != null)
{
for(var i = 0; i < inputobj.length; i++)
{
if (!inputobj[i].disabled)
{
inputobj = inputobj[i];
break;
}
}
}
var curLen = 3;
var curDec = 4;
if (curCode == "027")
{
curLen = 3;
curDec = 2;
}
switch(moneyCheck(inputobj.value,curLen,curDec,"false","false"))
{
case "a":
if (emptyFlag == "false")
alert(msg + ENTER_MSG + NOT_NULL);
return false;
case "b":
alert(msg + ":" + ENTER_MSG + EXCHANGERATE_MSG1);
return false;
case "c":
alert(msg + ":" + ENTER_MSG + EXCHANGERATE_MSG2);
return false;
case "d":
alert(msg + ":" + ENTER_MSG + EXCHANGERATE_MSG3);
return false;
case "e":
alert(msg + ":" + ENTER_MSG + EXCHANGERATE_MSG4);
return false;
}
return true;
}
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_msg=msg.split("|");
var curCodeArr=curCode.split("|");
var emptyFlagArr = emptyFlag.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
var curLen = 3;
var curDec = 4;
if (curCodeArr[i] == "027")
{
curLen = 3;
curDec = 2;
}
switch(moneyCheck(inputobj.value,curLen,curDec,"false","false"))
{
case "a":
if (emptyFlagArr[i] == "false")
alert(split_msg[i] + ENTER_MSG + NOT_NULL);
return false;
case "b":
alert(split_msg[i] + ":" + ENTER_MSG + EXCHANGERATE_MSG1);
return false;
case "c":
alert(split_msg[i] + ":" + ENTER_MSG + EXCHANGERATE_MSG2);
return false;
case "d":
alert(split_msg[i] + ":" + ENTER_MSG + EXCHANGERATE_MSG3);
return false;
case "e":
alert(split_msg[i] + ":" + ENTER_MSG + EXCHANGERATE_MSG4);
return false;
}
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u624b\u673a\u53f7,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false -- \u4e0d\u7b26\u5408\u8981\u6c42\u683c\u5f0f
* true -- \u7b26\u5408\u8981\u6c42\u683c\u5f0f
*
* \u4f8b\uff1acheck_mobile("Form1.Input1","\u5b57\u6bb51");
* \u4f8b\uff1acheck_mobile("Form1.Input1|Input2|Input3","\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53");
*
*/
function check_mobile(inputname,msg)
{
return regex_match(inputname,msg,"^([0-9]{11})?$");
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u8eab\u4efd\u8bc1\u53f7,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false -- \u4e0d\u7b26\u5408\u8981\u6c42\u683c\u5f0f
* true -- \u7b26\u5408\u8981\u6c42\u683c\u5f0f
*
* \u4f8b\uff1acheck_identify("Form1.Input1","\u5b57\u6bb51");
* \u4f8b\uff1acheck_identify("Form1.Input1|Input2|Input3","\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53");
*
*/
function check_identify(inputname,msg)
{
return regex_match(inputname,msg,"^(\\d{15}|\\d{17}[0-9Xx])?$");
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5EMAIL,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false -- \u4e0d\u7b26\u5408\u8981\u6c42\u683c\u5f0f
* true -- \u7b26\u5408\u8981\u6c42\u683c\u5f0f
*
* \u4f8b\uff1acheck_email("Form1.Input1","\u5b57\u6bb51");
* \u4f8b\uff1acheck_email("Form1.Input1|Input2|Input3","\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53");
*
*/
function check_email(inputname,msg)
{
return regex_match(inputname,msg,"^(\\S+@\\S+)?$");
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5E-token,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false -- \u4e0d\u7b26\u5408\u8981\u6c42\u683c\u5f0f
* true -- \u7b26\u5408\u8981\u6c42\u683c\u5f0f
*
* \u4f8b\uff1acheck_etoken("Form1.Input1","\u5b57\u6bb51");
* \u4f8b\uff1acheck_etoken("Form1.Input1|Input2|Input3","\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53");
*
*/
function check_etoken(inputname,msg)
{
return regex_match(inputname,msg,"^[0-9A-Za-z+=/]{6,12}$");
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u6d77\u5916\u4e2a\u4eba\u8f6c\u8d26\u6458\u8981,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false -- \u4e0d\u7b26\u5408\u8981\u6c42\u683c\u5f0f
* true -- \u7b26\u5408\u8981\u6c42\u683c\u5f0f
*
* \u4f8b\uff1acheck_englishForBoc2000("Form1.Input1","\u5b57\u6bb51");
* \u4f8b\uff1acheck_englishForBoc2000("Form1.Input1|Input2|Input3","\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53");
*
*/
function check_englishForBoc2000(inputname,msg)
{
return regex_match(inputname,msg,"^[ A-Za-z0-9-().,'//s/?/+//]*$");
}
/**
* \u51fd\u6570\u529f\u80fd\uff1a\u5b9e\u73b0check_date\u51fd\u6570\u7684\u91cd\u8f7d,\u672c\u51fd\u6570\u6839\u636echeck_date(arg1,arg2.....)\u4e2d\u53c2\u6570\u7684\u4e2a\u6570,\u5206\u522b\u8c03\u7528\u4e0d\u540c\u7684\u51fd\u6570,\u5206\u522b\u5b9e\u73b0\u4ee5\u4e0b\u529f\u80fd:
*
* 1. \u4ec5\u68c0\u67e5\u4e00\u4e2a\u65e5\u671f\u8f93\u5165\u57df\u662f\u5426\u5408\u6cd5:function checkDateSingle(inputname1,msg1)
* 2. \u68c0\u67e5\u4e24\u4e2a\u65e5\u671f\u8f93\u5165\u57df(\u8d77\u59cb/\u622a\u6b62\u65e5\u671f)\u662f\u5426\u5408\u6cd5,\u4e14\u622a\u6b62\u665a\u4e8e\u8d77\u59cb:function checkDateTwo(inputname1,inputname2,msg1,msg2)
* 3. \u68c0\u67e5\u4e24\u4e2a\u65e5\u671f\u8f93\u5165\u57df\u662f\u5426\u5408\u6cd5\u3001\u622a\u6b62\u662f\u5426\u665a\u4e8e\u8d77\u59cb\u3001\u65e5\u671f\u8de8\u5ea6\u4e3a\u82e5\u5e72\u6708\uff1a
* 4. \u68c0\u67e5\u4e24\u4e2a\u65e5\u671f\u662f\u5426\u5408\u6cd5\u3001\u622a\u6b62\u662f\u5426\u665a\u4e8e\u8d77\u59cb\u3001\u540c\u65f6\u9650\u5236\u622a\u6b62\u65e5\u671f\u548c\u8d77\u59cb\u65e5\u671f\u7684\u8303\u56f4\u662f\u5426\u5728\u67d0\u4e2a\u65e5\u671f\uff08limitDate\uff09\u4e4b\u5185\uff0c\u8de8\u5ea6\u4e3aperiod:
* function checkDateTwoLimit(inputname1,inputname2,msg1,msg2,limitDate,period)
* 5. \u68c0\u67e5\u4e24\u4e2a\u65e5\u671f\u662f\u5426\u5408\u6cd5\u3001\u622a\u6b62\u662f\u5426\u665a\u4e8e\u8d77\u59cb\u3001\u65e5\u671f\u8de8\u5ea6\u4e3a\u82e5\u5e72\u6708\u3001\u4e14\u53ef\u67e5\u8be2\u8303\u56f4\u662f\u5426\u5728\u67d0\u4e2a\u65e5\u671f\uff08limitDate\uff09\u4e4b\u5185\uff0c\u8de8\u5ea6\u4e3aperiod,\u67e5\u8be2\u8303\u56f4\u4e3ayPeriod
* function checkDatePeriodLimit(inputname1,inputname2,msg1,msg2,limitDate,period,yPeriod)
*
*
* Parameter \u53c2\u6570\u542b\u4e49\u89c1\u5404\u51fd\u6570\u6ce8\u91ca
*
* Return false -- \u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1a1. check_date('Form1.Input1','\u5b57\u6bb51');
* check_date('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
* 2. check_date('Form1.Input1','Form1.Input2','\u5b57\u6bb51','\u5b57\u6bb52');
*
* 3. check_date('Form1.Input1','Form1.Input2','\u5b57\u6bb51','\u5b57\u6bb52',3);
*
* 4. check_date('Form1.Input1','Form1.Input2','\u5b57\u6bb51','\u5b57\u6bb52','2007/07/27',6);
*
* 5. check_date('Form1.Input1','Form1.Input2','\u5b57\u6bb51','\u5b57\u6bb52','2007/07/27',6,-12);
*/
function check_date()
{
switch (arguments.length)
{
/** \u5982\u679c\u53c2\u6570\u4e2a\u6570\u4e3a2,\u8c03\u7528\u76f8\u5e94\u51fd\u6570\u5904\u7406 */
case 2:
return checkDateSingle(arguments[0],arguments[1]);
break;
/** \u5982\u679c\u53c2\u6570\u4e2a\u6570\u4e3a4,\u8c03\u7528\u76f8\u5e94\u51fd\u6570\u5904\u7406 */
case 4:
return checkDateTwo(arguments[0],arguments[1],arguments[2],arguments[3]);
break;
/** \u5982\u679c\u53c2\u6570\u4e2a\u6570\u4e3a5,\u8c03\u7528\u76f8\u5e94\u51fd\u6570\u5904\u7406 */
case 5:
return checkDateTwoPeriod(arguments[0],arguments[1],arguments[2],arguments[3],arguments[4]);
break;
/** \u5982\u679c\u53c2\u6570\u4e2a\u6570\u4e3a6,\u8c03\u7528\u76f8\u5e94\u51fd\u6570\u5904\u7406 */
case 6:
return checkDateTwoLimit(arguments[0],arguments[1],arguments[2],arguments[3],arguments[4],arguments[5]);
break;
/** \u5982\u679c\u53c2\u6570\u4e2a\u6570\u4e3a7,\u8c03\u7528\u76f8\u5e94\u51fd\u6570\u5904\u7406 */
case 7:
return checkDatePeriodLimit(arguments[0],arguments[1],arguments[2],arguments[3],arguments[4],arguments[5],arguments[6]);
break;
default:
return false;
}
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5date,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname1 -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg1 -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false -- \u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1acheckDateSingle('Form1.Input1','\u5b57\u6bb51');
* \u4f8b\uff1acheckDateSingle('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
*/
function checkDateSingle(inputname1,msg1)
{
var inputobj;
var inputvalue;
if(inputname1.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname1);
inputvalue = isdate(inputobj.value);
if(typeof(inputvalue) == "number" && inputvalue < 0)
{
alert(msg1 + ENTER_MSG + ILLEGAL_DATE);
return false;
}
return true;
}
var split_inputname=inputname1.split(".");
var split_inputs=split_inputname[1].split("|");
var split_msg=msg1.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
inputvalue = isdate(inputobj.value);
if(typeof(inputvalue) == "number" && inputvalue < 0)
errmsg=errmsg+split_msg[i]+" ";
}
if(errmsg!="")
{
alert(errmsg + ENTER_MSG + ILLEGAL_DATE);
return false;
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5date,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a,\u4e3b\u8981\u68c0\u67e5\u4e24\u4e2a\u65e5\u671f\u662f\u5426\u5408\u6cd5\uff0c\u5224\u65ad\u622a\u6b62\u65e5\u671f>\u5f00\u59cb\u65e5\u671f
*
* Parameter inputname1,inputname2 -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg1,msg2 -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false -- \u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1acheckDateTwo('Form1.Input1','Form1.Input2','\u5b57\u6bb51','\u5b57\u6bb52');
*
*/
function checkDateTwo(inputname1,inputname2,msg1,msg2)
{
var inputobj1=eval(CONST_STRDOC+inputname1);
var inputobj2=eval(CONST_STRDOC+inputname2);
var inputvalue1=isdate(inputobj1.value);
var inputvalue2=isdate(inputobj2.value);
var errmsg="";
if(typeof(inputvalue1) == "number" && inputvalue1 < 0)
errmsg=errmsg+msg1+" ";
if(typeof(inputvalue2) == "number" && inputvalue2 < 0)
errmsg=errmsg+msg2+" ";
if(errmsg!="")
{
alert(errmsg + ENTER_MSG + ILLEGAL_DATE);
return false;
}
if(typeof(inputvalue1) == "number" && inputvalue1 == 0 && typeof(inputvalue2) == "number" && inputvalue2 == 0)
return true;
if(inputvalue2 < inputvalue1)
{
alert(msg2 + DATE_LATER_MSG + msg1 + COMMA_MSG + MODIFY_MSG);
return false;
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5date,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a,\u4e3b\u8981\u68c0\u67e5\u4e24\u4e2a\u65e5\u671f\u662f\u5426\u5408\u6cd5,\u540c\u65f6\u9650\u5236\u622a\u6b62\u65e5\u671f\u548c\u8d77\u59cb\u65e5\u671f\u7684\u8303\u56f4
*
* Parameter inputname1,inputname2 -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg1,msg2 -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
* period -- \u8d77\u59cb\u65e5\u671f/\u622a\u6b62\u65e5\u671f\u7684\u8de8\u5ea6,\u4ee5\u6708\u4e3a\u5355\u4f4d,\u5982:period=3,\u8868\u793a3\u4e2a\u6708
*
* Return false -- \u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1acheckDateTwoPeriod('Form1.Input1','Form1.Input2','\u5b57\u6bb51','\u5b57\u6bb52',3);
*
*/
function checkDateTwoPeriod(inputname1,inputname2,msg1,msg2,period)
{
var inputobj1=eval(CONST_STRDOC+inputname1);
var inputobj2=eval(CONST_STRDOC+inputname2);
var inputvalue1=isdate(inputobj1.value);
var inputvalue2=isdate(inputobj2.value);
var errmsg="";
if(typeof(inputvalue1) == "number" && inputvalue1 < 0)
errmsg=errmsg+msg1+" ";
if(typeof(inputvalue2) == "number" && inputvalue2 < 0)
errmsg=errmsg+msg2+" ";
if(errmsg!="")
{
alert(errmsg + ENTER_MSG + ILLEGAL_DATE);
return false;
}
if(typeof(inputvalue1) == "number" && inputvalue1 == 0 && typeof(inputvalue2) == "number" && inputvalue2 == 0)
return true;
if(inputvalue2 < inputvalue1)
{
alert(msg2 + DATE_LATER_MSG + msg1 + COMMA_MSG + MODIFY_MSG);
return false;
}
if (addDate("m",inputvalue1,period) < inputvalue2)
{
alert(ILLEGAL_DATE_PERIOD + period + ENTRIES + MONTH + COMMA_MSG + MODIFY_MSG);
return false;
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5date,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a,\u4e3b\u8981\u68c0\u67e5\u4e24\u4e2a\u65e5\u671f\u662f\u5426\u5408\u6cd5,\u540c\u65f6\u9650\u5236\u622a\u6b62\u65e5\u671f\u548c\u8d77\u59cb\u65e5\u671f\u7684\u8303\u56f4
*
* Parameter inputname1,inputname2 -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg1,msg2 -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
* limitDate -- \u622a\u6b62\u65e5\u671f\u7684\u6700\u5927\u503c;
* period -- \u8d77\u59cb\u65e5\u671f/\u622a\u6b62\u65e5\u671f\u7684\u8de8\u5ea6,\u4ee5\u6708\u4e3a\u5355\u4f4d,\u5982:period=3,\u8868\u793a3\u4e2a\u6708
*
* Return false -- \u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1acheckDateTwoLimit('Form1.Input1','Form1.Input2','\u5b57\u6bb51','\u5b57\u6bb52','2007/07/27',6);
*
*/
function checkDateTwoLimit(inputname1,inputname2,msg1,msg2,limitDate,period)
{
var inputobj1=eval(CONST_STRDOC+inputname1);
var inputobj2=eval(CONST_STRDOC+inputname2);
var inputvalue1=isdate(inputobj1.value);
var inputvalue2=isdate(inputobj2.value);
var errmsg="";
if(typeof(inputvalue1) == "number" && inputvalue1 < 0)
errmsg=errmsg+msg1+" ";
if(typeof(inputvalue2) == "number" && inputvalue2 < 0)
errmsg=errmsg+msg2+" ";
if(errmsg!="")
{
alert(errmsg + ENTER_MSG + ILLEGAL_DATE);
return false;
}
if(typeof(inputvalue1) == "number" && inputvalue1 == 0 && typeof(inputvalue2) == "number" && inputvalue2 == 0)
return true;
var limitEndDateValue = isdate(limitDate);
var limitStartDateValue = addDate("m",isdate(limitDate),0-period);
var limitStartDate = date2string(limitStartDateValue,"/");
if(inputvalue2 < inputvalue1)
{
alert(msg2 + DATE_LATER_MSG + msg1 + COMMA_MSG + MODIFY_MSG);
return false;
}
if (limitEndDateValue < inputvalue2)
{
alert(msg2 + DATE_NOTLATER_MSG + limitDate + COMMA_MSG + MODIFY_MSG);
return false;
}
if (inputvalue1 < limitStartDateValue)
{
alert(msg1 + DATE_LATER_MSG + limitStartDate + COMMA_MSG + MODIFY_MSG);
return false;
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5date,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a,\u4e3b\u8981\u68c0\u67e5\u4e24\u4e2a\u65e5\u671f\u662f\u5426\u5408\u6cd5,\u540c\u65f6\u9650\u5236\u622a\u6b62\u65e5\u671f\u548c\u8d77\u59cb\u65e5\u671f\u7684\u8303\u56f4
*
* Parameter inputname1,inputname2 -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg1,msg2 -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
* limitDate -- \u67e5\u8be2\u8303\u56f4\u7684\u8d77\u59cb\u65e5\u671f;
* period -- \u8d77\u59cb\u65e5\u671f/\u622a\u6b62\u65e5\u671f\u7684\u8de8\u5ea6,\u4ee5\u6708\u4e3a\u5355\u4f4d,\u5982:period=3,\u8868\u793a3\u4e2a\u6708
* yPeriod -- \u67e5\u8be2\u8303\u56f4,\u6708\u4e3a\u5355\u4f4d,-12\u8868\u793a\u4ecelimitDate\u5f80\u524d\u4e00\u5e74,12\u8868\u793a\u4ecelimitDate\u5f80\u540e\u4e00\u5e74
*
* Return false -- \u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1acheckDateTwoLimit('Form1.Input1','Form1.Input2','\u5b57\u6bb51','\u5b57\u6bb52','2007/07/27',3,-12);
*
*/
function checkDatePeriodLimit(inputname1,inputname2,msg1,msg2,limitDate,period,yPeriod)
{
var inputobj1=eval(CONST_STRDOC+inputname1);
var inputobj2=eval(CONST_STRDOC+inputname2);
var inputvalue1=isdate(inputobj1.value);
var inputvalue2=isdate(inputobj2.value);
var errmsg="";
if(typeof(inputvalue1) == "number" && inputvalue1 < 0)
errmsg=errmsg+msg1+" ";
if(typeof(inputvalue2) == "number" && inputvalue2 < 0)
errmsg=errmsg+msg2+" ";
if(errmsg!="")
{
alert(errmsg + ENTER_MSG + ILLEGAL_DATE);
return false;
}
if(typeof(inputvalue1) == "number" && inputvalue1 == 0 && typeof(inputvalue2) == "number" && inputvalue2 == 0)
return true;
var limitEndDateValue = null;
var limitStartDateValue = null;
if (yPeriod >= 0)
{
limitStartDateValue = isdate(limitDate);
limitEndDateValue = addDate("m",isdate(limitDate),yPeriod);
}
else
{
limitEndDateValue = isdate(limitDate);
limitStartDateValue = addDate("m",isdate(limitDate),yPeriod);
}
var limitStartDate = date2string(limitStartDateValue,"/");
var limitEndDate = date2string(limitEndDateValue,"/");
if(inputvalue2 < inputvalue1)
{
alert(msg2 + DATE_LATER_MSG + msg1 + COMMA_MSG + MODIFY_MSG);
return false;
}
if (addDate("m",inputvalue1,period) < inputvalue2)
{
alert(ILLEGAL_DATE_PERIOD + period + ENTRIES + MONTH + COMMA_MSG + MODIFY_MSG);
return false;
}
if (limitEndDateValue < inputvalue2)
{
alert(msg2 + DATE_NOTLATER_MSG + limitEndDate + COMMA_MSG + MODIFY_MSG);
return false;
}
if (inputvalue1 < limitStartDateValue)
{
alert(msg1 + DATE_LATER_MSG + limitStartDate + COMMA_MSG + MODIFY_MSG);
return false;
}
return true;
}
/**
* \u51fd\u6570\u529f\u80fd\uff1a\u4fee\u6539checkDatePeriodLimit\u51fd\u6570\u529f\u80fd,\u8de8\u5ea6\u65e5\u671f\u5355\u4f4d\u7531\u6708\u6539\u4e3a\u65e5,\u53ef\u4ee5\u5b9e\u73b0"\u8d77\u59cb\u622a\u81f3\u65e5\u671f\u95f4\u9694\u4e0d\u80fd\u8d85\u8fc7XX\u5929"\u7c7b\u7684\u9700\u6c42
*
* \u529f\u80fd: \u68c0\u67e5\u4e24\u4e2a\u65e5\u671f\u662f\u5426\u5408\u6cd5\u3001\u622a\u6b62\u662f\u5426\u665a\u4e8e\u8d77\u59cb\u3001\u65e5\u671f\u8de8\u5ea6\u4e3a\u82e5\u5e72\u5929\u3001\u4e14\u53ef\u67e5\u8be2\u8303\u56f4\u662f\u5426\u5728\u4ee5\u67d0\u4e2a\u65e5\u671f\uff08limitDate\uff09\u4e3a\u57fa\u51c6,\u8303\u56f4\u5728(yPeriod)\u4e4b\u5185,\u8d77\u59cb\u622a\u81f3\u65e5\u671f\u8de8\u5ea6\u4e3aperiod
* function checkDatePeriodLimitByDay(inputname1,inputname2,msg1,msg2,limitDate,period,yPeriod)
*
*
* Parameter:
* 1.inputname1: \u8d77\u59cb\u65e5\u671f\u8f93\u5165\u57df\u540d\u79f0
* 2.inputname2: \u622a\u81f3\u65e5\u671f\u8f93\u5165\u57df\u540d\u79f0
* 3.msg1: \u63d0\u793a\u4fe1\u606f\u4e2d,\u5bf9\u4e8e\u8d77\u59cb\u65e5\u671f\u7684\u7ffb\u8bd1
* 4.msg2: \u63d0\u793a\u4fe1\u606f\u4e2d,\u5bf9\u4e8e\u622a\u81f3\u65e5\u671f\u7684\u7ffb\u8bd1
* 5.limitDate: \u5982\u679c\u67e5\u8be2\u8303\u56f4(yPeriod)>=0,\u5219\u4e3a\u67e5\u8be2\u8303\u56f4\u7684\u8d77\u59cb\u65e5\u671f,\u6839\u636eyPeriod\u987a\u5ef6\u4e4b\u540e\u7684\u65e5\u671f\u4e3a\u67e5\u8be2\u8303\u56f4\u7684\u622a\u81f3\u65e5\u671f;
* \u5982\u679c\u67e5\u8be2\u8303\u56f4(yPeriod)<0,\u5219\u4e3a\u67e5\u8be2\u8303\u56f4\u7684\u622a\u81f3\u65e5\u671f,\u6839\u636eyPeriod\u63d0\u524d\u7684\u65e5\u671f\u4e3a\u67e5\u8be2\u8303\u56f4\u7684\u8d77\u59cb\u65e5\u671f
* 6.period: \u7528\u6237\u8f93\u5165\u7684\u8d77\u59cb\u622a\u81f3\u65e5\u671f\u4e4b\u95f4\u7684\u8de8\u5ea6,\u5355\u4f4d\u4e3a"\u5929"
* 7.yPeriod: \u67e5\u8be2\u8303\u56f4,\u5173\u8054limitDate\u5224\u65ad,\u5355\u4f4d\u4e3a"\u6708"
*
* Return false -- \u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1acheckDatePeriodLimitByDay('Form1.Input1','Form1.Input2','\u5b57\u6bb51','\u5b57\u6bb52','2007/07/27',15,-12);
*/
function checkDatePeriodLimitByDay (inputname1,inputname2,msg1,msg2,limitDate,period,yPeriod) {
var inputobj1=eval(CONST_STRDOC+inputname1);
var inputobj2=eval(CONST_STRDOC+inputname2);
var inputvalue1=isdate(inputobj1.value);
var inputvalue2=isdate(inputobj2.value);
var errmsg="";
if(typeof(inputvalue1) == "number" && inputvalue1 < 0)
errmsg=errmsg+msg1+" ";
if(typeof(inputvalue2) == "number" && inputvalue2 < 0)
errmsg=errmsg+msg2+" ";
if(errmsg!="")
{
alert(errmsg + ENTER_MSG + ILLEGAL_DATE);
return false;
}
if(typeof(inputvalue1) == "number" && inputvalue1 == 0 && typeof(inputvalue2) == "number" && inputvalue2 == 0)
return true;
var limitEndDateValue = null;
var limitStartDateValue = null;
if (yPeriod >= 0)
{
limitStartDateValue = isdate(limitDate);
limitEndDateValue = addDate("m",isdate(limitDate),yPeriod);
}
else
{
limitEndDateValue = isdate(limitDate);
limitStartDateValue = addDate("m",isdate(limitDate),yPeriod);
}
var limitStartDate = date2string(limitStartDateValue,"/");
var limitEndDate = date2string(limitEndDateValue,"/");
if(inputvalue2 < inputvalue1)
{
alert(msg2 + DATE_LATER_MSG + msg1 + COMMA_MSG + MODIFY_MSG);
return false;
}
if (addDate("d",inputvalue1,period) < inputvalue2)
{
alert(ILLEGAL_DATE_PERIOD + period + DAY + COMMA_MSG + MODIFY_MSG);
return false;
}
if (limitEndDateValue < inputvalue2)
{
alert(msg2 + DATE_NOTLATER_MSG + limitEndDate + COMMA_MSG + MODIFY_MSG);
return false;
}
if (inputvalue1 < limitStartDateValue)
{
alert(msg1 + DATE_LATER_MSG + limitStartDate + COMMA_MSG + MODIFY_MSG);
return false;
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u5224\u65ad\u5b57\u7b26\u4e32\u662f\u5426\u4e3a\u65e5\u671f\u6570\u636e,\u83b7\u5f97\u8fd4\u56de\u503c
*
* Parameter onestring -- \u9700\u5224\u65ad\u7684\u5b57\u7b26\u4e32;
*
* Return 0 -- \u5b57\u7b26\u4e32\u4e3a\u7a7a
* -1 -- \u5b57\u7b26\u4e32\u975e\u65e5\u671f\u6570\u636e
* \u65e5\u671f\u503c -- \u5b57\u7b26\u4e32\u4e3a\u65e5\u671f\u6570\u636e\uff0c\u5e76\u83b7\u5f97\u65e5\u671f\u503c
*
* \u4f8b\uff1aisdate("2000/01/01") \u8fd4\u56de20000101
* \u4f8b\uff1aisdate("") \u8fd4\u56de0
* \u4f8b\uff1aisdate("abc") \u8fd4\u56de-1
*
*/
function isdate(onestring)
{
if(onestring.length == 0)
return 0;
if(onestring.length != 10)
return -1;
var pattern = /\d{4}\/\d{2}\/\d{2}/;
if(!pattern.test(onestring))
return -1;
var arrDate = onestring.split("/");
if(parseInt(arrDate[0],10) < 100)
arrDate[0] = 2000 + parseInt(arrDate[0],10) + "";
var newdate = new Date(arrDate[0],(parseInt(arrDate[1],10) -1)+"",arrDate[2]);
if(newdate.getFullYear() == arrDate[0] && newdate.getMonth() == (parseInt(arrDate[1],10) -1)+"" && newdate.getDate() == arrDate[2])
return newdate;
else
return -1;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u662f\u5426\u5b57\u7b26\u4e32\u5168\u4e3a\u4e2d\u6587,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false --\u5305\u542b\u975e\u4e2d\u6587
* true -- \u5168\u4e3a\u4e2d\u6587
*
* \u4f8b\uff1acheck_chinese_only('Form1.Input1','\u5b57\u6bb51');
* \u4f8b\uff1acheck_chinese_only('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
*/
function check_chinese_only(inputname,msg)
{
var inputobj,inputvalue;
if(inputname.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname);
inputvalue=inputobj.value;
if(inputvalue.length==0)
return true;
for (var i=0;i<inputvalue.length;i++)
{
if(inputvalue.charCodeAt(i)<=255)
{//find
alert(msg + ENTER_MSG + NOT_ONLY_CHINESE);
return false;
}
}
return true;
}
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_msg=msg.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
inputvalue=inputobj.value;
if(inputvalue.length==0)
continue;
for (var j=0;j<inputvalue.length;j++)
{
if(inputvalue.charCodeAt(j)>255)
{//find
errmsg=errmsg+split_msg[i]+" ";
break;
}
}
}
if(errmsg!="")
{
alert(errmsg + ENTER_MSG + NOT_ONLY_CHINESE);
return false;
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u5b57\u7b26\u4e32\u662f\u5426\u4e3a\u6570\u5b57\u3001\u52a0\u53f7\u3001\u7a7a\u683c\u3001\u6a2a\u7ebf,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false --\u5305\u542b\u6570\u5b57\u3001\u52a0\u53f7\u3001\u7a7a\u683c\u3001\u6a2a\u7ebf\u4ee5\u5916\u7684\u5b57\u7b26
* true -- \u4e0d\u5305\u542b
*
* \u4f8b\uff1acheck_phone('Form1.Input1','\u5b57\u6bb51');
* \u4f8b\uff1acheck_phone('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
*/
function check_phone(inputname,msg)
{
return regex_match(inputname,msg,"[ 0-9-///+]*$");
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u5224\u65ad\u91d1\u989d\u7684\u5408\u6cd5\u6027,\u540c\u65f6\u6269\u5c55\u4e3a\u666e\u901a\u6d6e\u70b9\u6570\u7684\u68c0\u67e5(\u79c1\u6709\u51fd\u6570\uff0c\u8bf7\u52ff\u8c03\u7528)
*
* Parameter str -- \u9700\u5224\u65ad\u7684\u5b57\u7b26\u4e32;
* llen -- \u91d1\u989d\u6574\u6570\u90e8\u5206\u7684\u957f\u5ea6;
* dec -- \u8f85\u5e01\u4f4d\u6570;
* minusFlag -- \u91d1\u989d\u662f\u5426\u53ef\u4ee5\u4e3a\u8d1f,true:\u53ef\u4ee5\u4e3a\u8d1f,false:\u4e0d\u80fd\u4e3a\u8d1f;
* isFormatMoney -- \u662f\u5426\u662f\u683c\u5f0f\u5316\u91d1\u989d,true:\u662f,false:\u5426;\u5982\u679c\u4e3a\u5426\uff0c\u53ef\u7528\u505a\u666e\u901a\u6d6e\u70b9\u6570\u7684\u5224\u65ad
*
* Return a -- \u5b57\u7b26\u4e32\u4e3a\u7a7a
* b -- \u5b57\u7b26\u4e32\u975e\u6570\u503c\u6570\u636e
* c -- \u91d1\u989d\u4e3a\u8d1f
* d -- \u6574\u6570\u90e8\u5206\u8d85\u957f
* e -- \u5c0f\u6570\u90e8\u5206\u8d85\u957f
* \u6570\u503c -- \u5b57\u7b26\u4e32\u4e3a\u6570\u503c\u6570\u636e\uff0c\u5e76\u83b7\u5f97\u8f6c\u6362\u540e\u7684\u6570\u503c
*
* \u4f8b\uff1amoneyCheck("123,456,789.34",13,2) \u8fd4\u56de123456789.34
*
*/
function moneyCheck(str,llen,dec,minusFlag,isFormatMoney)
{
if(str == null || str == "")
return "a";
if(str.length!=0&&str.trim().length == 0)
return "b";
var regex;
if (isFormatMoney == "true")
regex = new RegExp(/(?!^[-]?[0,]*(\.0{1,4})?$)^[-]?(([1-9]\d{0,2}(,\d{3})*)|([1-9]\d*)|0)(\.\d{1,4})?$/);
else
regex = new RegExp(/(?!^[-]?[0]*(\.0{1,4})?$)^[-]?(([1-9]\d*)|0)(\.\d{1,4})?$/);
if (!regex.test(str))
return "b";
var minus = "";
if (minusFlag == "true")
{
if(str.substring(0,1) == "-")
{
minus = "-";
str = str.substring(1);
}
}
else
{
if(str.substring(0,1) == "-")
return "c";
}
if (str.substring(0,1)==".")
str = "0" + str;
str = replace(str,",","");
if (str.indexOf(".") == -1)
{
if (str.length > llen)
return "d";
return parseFloat(minus + str);
}
else
{
var tmp = str.split(".");
if(tmp.length > 2)
return "b";
if (tmp[0].length > llen)
return "d";
if (tmp[1].length > dec)
return "e";
return parseFloat(minus + tmp[0] + "." + tmp[1]);
}
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u534a\u89d2\u5b57\u7b26\u4e32\u8f6c\u6362\u4e3a\u5168\u89d2\u5b57\u7b26\u4e32(\u516c\u6709\u51fd\u6570\uff0c\u8bf7\u8c03\u7528)
*
* Parameter str -- \u9700\u8981\u8f6c\u6362\u7684\u5b57\u7b26\u4e32\uff0c\u652f\u6301\u534a\u89d2\u5168\u89d2\u6df7\u5408\u5b57\u7b26\u4e32
* flag -- \u8f6c\u6362\u6807\u8bc6\uff0c0\u4e3a\u8f6c\u6362
*
* Return \u5168\u89d2\u5b57\u7b26
*
* \u4f8b\uff1aDBC2SBC("abcdefg",0) \u8fd4\u56de\uff41\uff42\uff43\uff44\uff45\uff46\uff47
*
*/
function DBC2SBC(str,flag) {
var i;
var result='';
if(str.length<=0) {
return result;
}
for(i=0;i<str.length;i++){
str1=str.charCodeAt(i);
if(str1<125&&!flag){
if(str1==32){//\u5982\u679c\u662f\u534a\u89d2\u7a7a\u683c\uff0c\u7279\u6b8a\u5904\u7406
result+=String.fromCharCode(12288);
}else{
result+=String.fromCharCode(str.charCodeAt(i)+65248);
}
}else{
result+=String.fromCharCode(str.charCodeAt(i));
}
}
return result;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u957f\u5ea6\u662f\u5426\u7b49\u4e8e\u679a\u4e3e\u56fa\u5b9a\u957f\u5ea6,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* inputlength -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u6307\u5b9a\u679a\u4e3e\u56fa\u5b9a\u957f\u5ea6;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false --\u4e0d\u7b49\u4e8e
* true -- \u7b49\u4e8e
*
* \u4f8b\uff1acheck_length('Form1.Input1','6|8|10','\u5b57\u6bb51');
*
*/
function check_lengthEnum(inputname,inputlength,msg)
{
var inputobj;
/*
if(inputname.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname);
if((inputobj.value.length!=0) && (inputobj.value.length!=inputlength))
{
alert(msg + LENGTH_EQUAL_MSG + inputlength + COMMA_MSG + ENTER_MSG + MODIFY_MSG);
return false;
}
return true;
}*/
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_inputlength=inputlength.split("|");
var split_msg=msg.split("|");
var errmsg=FORMAT_ERROR.replace("{0}",msg);
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[0]);
for (var i=0;i<split_inputlength.length;i++)
{
if(inputobj.value.length==split_inputlength[i])
{
errmsg="";
break
}
//errmsg=errmsg+split_msg[i] + LENGTH_EQUAL_MSG + split_inputlength[i] + COMMA_MSG + ENTER_MSG;
}
if(errmsg.length!=0)
{
alert(errmsg + MODIFY_MSG);
return false;
}
return true;
}
/*
*\u51fd\u6570\u529f\u80fd\uff1a\u53bb\u9664\u5b57\u7b26\u4e32\u4e2d\u7684\u6240\u6709\u7a7a\u767d\u7b26(\u5b57\u7b26\u4e32\u524d\u3001\u4e2d\u95f4\u3001\u540e)
*
*Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
*
*
*\u4f8b\u5b50\uff1a onblur="trimAllBlank(document.form1.ToAccountNo)"
*/
function trimAllBlank(inputname)
{
var result=inputname.value.replace(/(\s)/g,"");
inputname.value=result;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5swift\u975e\u6cd5\u5b57\u7b26 ` ~ ! @ # $ % ^ & * _ = [ ] { } ; " < > | \ : -
* \u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false --\u4e0d\u5408\u6cd5
* true -- \u5408\u6cd5
*
* \u4f8b\uff1acheck_swift('Form1.Input1','\u5b57\u6bb51');
* \u4f8b\uff1acheck_swift('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
*/
function check_swift(inputname,msg)
{
var pattern;
pattern = "^[^`~!@#\\$%\\^&\\*_=\\[\\]{};\\\"<>\\|\\\\:-]*$";
if(inputname.indexOf("|")==-1)
{
inputobj=eval(CONST_STRDOC+inputname);
inputvalue=inputobj.value;
if(inputvalue.length==0)
return true;
return regex_match(inputname,msg,pattern);
}
var split_inputname=inputname.split(".");
var split_inputs=split_inputname[1].split("|");
var split_msg=msg.split("|");
var errmsg="";
for (var i=0;i<split_inputs.length;i++)
{
inputobj=eval(CONST_STRDOC+split_inputname[0]+"."+split_inputs[i]);
inputvalue=inputobj.value;
if(inputvalue.length==0){
continue;
}else if(!regex_match(split_inputname[0]+"."+split_inputs[i],split_msg[i],pattern)){
return false;
}
}
return true;
}
/*
* \u51fd\u6570\u529f\u80fd\uff1a\u68c0\u67e5\u5b57\u7b26\u4e32\u662f\u5426\u4e3a\u5b57\u6bcd\u3001\u6570\u5b57,\u5411\u7528\u6237\u53d1\u51fa\u63d0\u793a
*
* Parameter inputname -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u82f1\u6587\u540d;
* msg -- \u8868\u5355\u57df\u6587\u672c\u6846\u7684\u4e2d\u6587\u6807\u8bc6\u4e3a\u7528\u6237\u63d0\u4f9b\u63d0\u793a\u4fe1\u606f;
*
* Return false --\u5305\u542b\u5b57\u6bcd\u3001\u6570\u5b57\u4ee5\u5916\u7684\u5b57\u7b26
* true -- \u4e0d\u5305\u542b
*
* \u4f8b\uff1acheck_letter_num('Form1.Input1','\u5b57\u6bb51');
* \u4f8b\uff1acheck_letter_num('Form1.Input1|Input2|Input3','\u5b57\u6bb51|\u5b57\u6bb52|\u5b57\u6bb53');
*
*/
function check_letter_num(inputname,msg) {
return regex_match(inputname,msg,"^[ A-Za-z0-9]*$");
}
//**************************************
//*** FORM\u8868\u5355\u68c0\u67e5\u51fd\u6570\u7ed3\u675f
//**************************************
| zzhongster-wxtlactivex | chrome/settings/_boc_FormCheck.js | JavaScript | mpl11 | 73,404 |
function initShare() {
var link = 'https://chrome.google.com/webstore/detail/' +
'lgllffgicojgllpmdbemgglaponefajn';
var text2 = ['Chrome也能用网银啦!',
'每次付款还要换浏览器?你out啦!',
'现在可以彻底抛弃IE了!',
'让IE去死吧!',
'Chrome用网银:'
];
text2 = text2[Math.floor(Math.random() * 1000121) % text2.length];
text2 = '只要安装了ActiveX for Chrome,就可以直接在Chrome里' +
'使用各种网银、播放器等ActiveX控件了。而且不用切换内核,非常方便。';
var pic = 'http://ww3.sinaimg.cn/bmiddle/8c75b426jw1dqz2l1qfubj.jpg';
var text = text2 + '下载地址:';
// facebook
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = 'https://connect.facebook.net/en_US/all.js#xfbml=1';
js.async = true;
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
window.___gcfg = {lang: navigator.language};
// Google plus
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
// Sina weibo
(function() {
var _w = 75 , _h = 24;
var param = {
url: link,
type: '2',
count: '1', /**是否显示分享数,1显示(可选)*/
appkey: '798098327', /**您申请的应用appkey,显示分享来源(可选)*/
title: text,
pic: pic, /**分享图片的路径(可选)*/
ralateUid: '2356524070', /**关联用户的UID,分享微博会@该用户(可选)*/
language: 'zh_cn', /**设置语言,zh_cn|zh_tw(可选)*/
rnd: new Date().valueOf()
};
var temp = [];
for (var p in param) {
temp.push(p + '=' + encodeURIComponent(param[p] || ''));
}
weiboshare.innerHTML = '<iframe allowTransparency="true"' +
' frameborder="0" scrolling="no" ' +
'src="http://hits.sinajs.cn/A1/weiboshare.html?' +
temp.join('&') + '" width="' + _w + '" height="' + _h + '"></iframe>';
})();
//renren
function shareClick() {
var rrShareParam = {
resourceUrl: link,
pic: pic,
title: 'Chrome用网银:ActiveX for Chrome',
description: text2
};
rrShareOnclick(rrShareParam);
}
Renren.share();
xn_share.addEventListener('click', shareClick, false);
// Tencent weibo
function postToWb() {
var _url = encodeURIComponent(link);
var _assname = encodeURI('');
var _appkey = encodeURI('801125118');//你从腾讯获得的appkey
var _pic = encodeURI(pic);
var _t = '';
var metainfo = document.getElementsByTagName('meta');
for (var metai = 0; metai < metainfo.length; metai++) {
if ((new RegExp('description', 'gi')).test(
metainfo[metai].getAttribute('name'))) {
_t = metainfo[metai].attributes['content'].value;
}
}
_t = text;
if (_t.length > 120) {
_t = _t.substr(0, 117) + '...';
}
_t = encodeURI(_t);
var _u = 'http://share.v.t.qq.com/index.php?c=share&a=index&url=' + _url +
'&appkey=' + _appkey + '&pic=' + _pic + '&assname=' + _assname +
'&title=' + _t;
window.open(_u, '', 'width=700, height=680, top=0, left=0, toolbar=no,' +
' menubar=no, scrollbars=no, location=yes, resizable=no, status=no');
}
qqweibo.addEventListener('click', postToWb, false);
// Douban
function doubanShare() {
var d = document,
e = encodeURIComponent,
s1 = window.getSelection,
s2 = d.getSelection,
s3 = d.selection,
s = s1 ? s1() : s2 ? s2() : s3 ? s3.createRange().text : '',
r = 'http://www.douban.com/recommend/?url=' + e(link) +
'&title=' + e('ActiveX for Chrome') + '&sel=' + e(s) + '&v=1';
window.open(
r, 'douban',
'toolbar=0,resizable=1,scrollbars=yes,status=1,width=450,height=330');
}
doubanshare.addEventListener('click', doubanShare, false);
}
$(document).ready(function() {
div = $('#share');
div.load('share.html', function() {
setTimeout(initShare, 200);
});
});
document.write('<script type="text/javascript" src="rrshare.js"></script>');
document.write('<div id="share">');
document.write('</div>');
| zzhongster-wxtlactivex | chrome/share.js | JavaScript | mpl11 | 4,556 |
// Copyright (c) 2012 eagleonhill(qiuc12@gmail.com). All rights reserved.
// Use of this source code is governed by a Mozilla-1.1 license that can be
// found in the LICENSE file.
/*
prop = {
header, // String
property, // String
events, //
type, // checkbox, select, input.type, button
extra // depend on type
}
*/
function List(config) {
this.config = config;
this.props = config.props;
this.main = config.main;
this.selectedLine = -2;
this.lines = [];
if (!config.getItems) {
config.getItems = function() {
return config.items;
}
}
if (!config.getItemProp) {
config.getItemProp = function(id, prop) {
return config.getItem(id)[prop];
}
}
if (!config.setItemProp) {
config.setItemProp = function(id, prop, value) {
config.getItem(id)[prop] = value;
}
}
if (!config.getItem) {
config.getItem = function(id) {
return config.getItems()[id];
}
}
if (!config.move) {
config.move = function(a, b) {
if (a != b && a >= 0 && b >= 0 && a < this.count() && b < this.count()) {
var list = config.getItems();
var tmp = list[a];
// remove a
list.splice(a, 1);
// insert b
list.splice(b, 0, tmp);
}
}
}
if (!config.insert) {
config.insert = function(id, newItem) {
config.getItems().splice(id, 0, newItem);
}
}
if (!config.remove) {
config.remove = function(a) {
config.move(a, config.count() - 1);
config.getItems().pop();
}
}
if (!config.validate) {
config.validate = function() {return true;};
}
if (!config.count) {
config.count = function() {
return config.getItems().length;
}
}
if (!config.patch) {
config.patch = function(id, newVal) {
for (var name in newVal) {
config.setItemProp(id, name, newVal[name]);
}
}
}
if (!config.defaultValue) {
config.defaultValue = {};
}
config.main.addClass('list');
}
List.ids = {
noline: -1
};
List.types = {};
List.prototype = {
init: function() {
with (this) {
if (this.inited) {
return;
}
this.inited = true;
this.headergroup = $('<div class="headers"></div>');
for (var i = 0; i < props.length; ++i) {
var header = $('<div class="header"></div>').
attr('property', props[i].property).html(props[i].header);
headergroup.append(header);
}
this.scrolls = $('<div>').addClass('listscroll');
this.contents = $('<div class="listitems"></div>').appendTo(scrolls);
scrolls.scroll(function() {
headergroup.css('left', -(scrolls.scrollLeft()) + 'px');
});
contents.click(function(e) {
if (e.target == contents[0]) {
selectLine(List.ids.noline);
}
});
$(main).append(headergroup).append(scrolls);
var height = this.main.height() - this.headergroup.outerHeight();
this.scrolls.height(height);
load();
selectLine(List.ids.noline);
}
},
editNewLine: function() {
this.startEdit(this.lines[this.lines.length - 1]);
},
updatePropDisplay: function(line, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var id = Number(line.attr('row'));
if (id == this.config.count()) {
var value = this.config.defaultValue[name];
if (value) {
ctrl.value = value;
}
obj.trigger('createNew');
} else {
ctrl.value = this.config.getItemProp(id, name);
obj.trigger('update');
}
},
updateLine: function(line) {
for (var i = 0; i < this.props.length; ++i) {
this.updatePropDisplay(line, this.props[i]);
}
if (Number(line.attr('row')) < this.config.count()) {
line.trigger('update');
} else {
line.addClass('newline');
}
},
createLine: function() {
with (this) {
var line = $('<div></div>').addClass('itemline');
var inner = $('<div>');
line.append(inner);
// create input boxes
for (var i = 0; i < props.length; ++i) {
var prop = props[i];
var ctrl = $('<div></div>').attr('property', prop.property)
.addClass('listvalue').attr('tabindex', -1);
var valueobj = new List.types[prop.type](ctrl, prop);
var data = {list: this, line: line, prop: prop};
for (var e in prop.events) {
ctrl.bind(e, data, prop.events[e]);
}
ctrl.bind('change', function(e) {
validate(line);
return true;
});
ctrl.bind('keyup', function(e) {
if (e.keyCode == 27) {
cancelEdit(line);
}
});
ctrl.trigger('create');
inner.append(ctrl);
}
// Event listeners
line.click(function(e) {
startEdit(line);
});
line.focusin(function(e) {
startEdit(line);
});
line.focusout(function(e) {
finishEdit(line);
});
for (var e in this.config.lineEvents) {
line.bind(e, {list: this, line: line}, this.config.lineEvents[e]);
}
var list = this;
line.bind('updating', function() {
$(list).trigger('updating');
});
line.bind('updated', function() {
$(list).trigger('updated');
});
this.bindId(line, this.lines.length);
this.lines.push(line);
line.appendTo(this.contents);
return line;
}
},
refresh: function(lines) {
var all = false;
if (lines === undefined) {
all = true;
lines = [];
}
for (var i = this.lines.length; i <= this.config.count(); ++i) {
var line = this.createLine();
lines.push(i);
}
while (this.lines.length > this.config.count() + 1) {
this.lines.pop().remove();
}
$('.newline', this.contents).removeClass('newline');
this.lines[this.lines.length - 1].addClass('newline');
if (all) {
for (var i = 0; i < this.lines.length; ++i) {
this.updateLine(this.lines[i]);
}
} else {
for (var i = 0; i < lines.length; ++i) {
this.updateLine(this.lines[lines[i]]);
}
}
},
load: function() {
this.contents.empty();
this.lines = [];
this.refresh();
},
bindId: function(line, id) {
line.attr('row', id);
},
getLineNewValue: function(line) {
var ret = {};
for (var i = 0; i < this.props.length; ++i) {
this.getPropValue(line, ret, this.props[i]);
}
return ret;
},
getPropValue: function(line, item, prop) {
var name = prop.property;
obj = $('[property=' + name + ']', line);
var ctrl = obj[0].listdata;
var value = ctrl.value;
if (value !== undefined) {
item[name] = value;
}
return value;
},
startEdit: function(line) {
if (line.hasClass('editing')) {
return;
}
line.addClass('editing');
this.showLine(line);
this.selectLine(line);
var list = this;
setTimeout(function() {
if (!line[0].contains(document.activeElement)) {
$('.valinput', line).first().focus();
}
list.validate(line);
}, 50);
},
finishEdit: function(line) {
var list = this;
function doFinishEdit() {
with (list) {
if (line[0].contains(document.activeElement)) {
return;
}
var valid = isValid(line);
if (valid) {
var id = Number(line.attr('row'));
var newval = getLineNewValue(line);
if (line.hasClass('newline')) {
$(list).trigger('updating');
if (!config.insert(id, newval)) {
line.removeClass('newline');
list.selectLine(line);
$(list).trigger('add', id);
addNewLine();
}
} else {
line.trigger('updating');
config.patch(id, newval);
}
line.trigger('updated');
}
cancelEdit(line);
}
};
setTimeout(doFinishEdit, 50);
},
cancelEdit: function(line) {
line.removeClass('editing');
line.removeClass('error');
var id = Number(line.attr('row'));
if (id == this.config.count() && this.selectedLine == id) {
this.selectedLine = List.ids.noline;
}
this.updateLine(line);
},
addNewLine: function() {
with (this) {
var line = $('.newline', contents);
if (!line.length) {
line = createLine().addClass('newline');
}
return line;
}
},
isValid: function(line) {
var id = Number(line.attr('row'));
var obj = this.getLineNewValue(line);
return valid = this.config.validate(id, obj);
},
validate: function(line) {
if (this.isValid(line)) {
line.removeClass('error');
} else {
line.addClass('error');
}
},
move: function(a, b, keepSelect) {
var len = this.config.count();
if (a == b || a < 0 || b < 0 || a >= len || b >= len) {
return;
}
this.config.move(a, b);
for (var i = Math.min(a, b); i <= Math.max(a, b); ++i) {
this.updateLine(this.getLine(i));
}
if (keepSelect) {
if (this.selectedLine == a) {
this.selectLine(b);
} else if (this.selectedLine == b) {
this.selectLine(a);
}
}
},
getLine: function(id) {
if (id < 0 || id >= this.lines.length) {
return null;
}
return this.lines[id];
},
remove: function(id) {
id = Number(id);
if (id < 0 || id >= this.config.count()) {
return;
}
$(this).trigger('updating');
var len = this.lines.length;
this.getLine(id).trigger('removing');
if (this.config.remove(id)) {
return;
}
this.getLine(len - 1).remove();
this.lines.pop();
for (var i = id; i < len - 1; ++i) {
this.updateLine(this.getLine(i));
}
if (id >= len - 2) {
this.selectLine(id);
} else {
this.selectLine(List.ids.noline);
}
$(this).trigger('updated');
},
selectLine: function(id) {
var line = id;
if (typeof id == 'number') {
line = this.getLine(id);
} else {
id = Number(line.attr('row'));
}
// Can't select the new line.
if (line && line.hasClass('newline')) {
line = null;
id = List.ids.noline;
}
if (this.selectedLine == id) {
return;
}
var oldline = this.getLine(this.selectedLine);
if (oldline) {
this.cancelEdit(oldline);
oldline.removeClass('selected');
oldline.trigger('deselect');
this.selectedLine = List.ids.noline;
}
this.selectedLine = id;
if (line != null) {
line.addClass('selected');
line.trigger('select');
this.showLine(line);
}
$(this).trigger('select');
},
showLine: function(line) {
var showtop = this.scrolls.scrollTop();
var showbottom = showtop + this.scrolls.height();
var top = line.offset().top - this.contents.offset().top;
// Include the scroll bar
var bottom = top + line.height() + 20;
if (top < showtop) {
// show at top
this.scrolls.scrollTop(top);
} else if (bottom > showbottom) {
// show at bottom
this.scrolls.scrollTop(Math.max(0, bottom - this.scrolls.height()));
}
}
};
| zzhongster-wxtlactivex | chrome/list.js | JavaScript | mpl11 | 11,702 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "HTMLDocumentContainer.h"
#include "npactivex.h"
#include <MsHTML.h>
const GUID HTMLDocumentContainer::IID_TopLevelBrowser = {0x4C96BE40, 0x915C, 0x11CF, {0x99, 0xD3, 0x00, 0xAA, 0x00, 0x4A, 0xE8, 0x37}};
HTMLDocumentContainer::HTMLDocumentContainer() : dispatcher(NULL)
{
}
void HTMLDocumentContainer::Init(NPP instance, ITypeLib *htmlLib) {
NPObjectProxy npWindow;
NPNFuncs.getvalue(instance, NPNVWindowNPObject, &npWindow);
NPVariantProxy documentVariant;
if (NPNFuncs.getproperty(instance, npWindow, NPNFuncs.getstringidentifier("document"), &documentVariant)
&& NPVARIANT_IS_OBJECT(documentVariant)) {
NPObject *npDocument = NPVARIANT_TO_OBJECT(documentVariant);
dispatcher = new FakeDispatcher(instance, htmlLib, npDocument);
}
npp = instance;
}
HRESULT HTMLDocumentContainer::get_LocationURL(BSTR *str) {
NPObjectProxy npWindow;
NPNFuncs.getvalue(npp, NPNVWindowNPObject, &npWindow);
NPVariantProxy LocationVariant;
if (!NPNFuncs.getproperty(npp, npWindow, NPNFuncs.getstringidentifier("location"), &LocationVariant)
|| !NPVARIANT_IS_OBJECT(LocationVariant)) {
return E_FAIL;
}
NPObject *npLocation = NPVARIANT_TO_OBJECT(LocationVariant);
NPVariantProxy npStr;
if (!NPNFuncs.getproperty(npp, npLocation, NPNFuncs.getstringidentifier("href"), &npStr))
return E_FAIL;
CComBSTR bstr(npStr.value.stringValue.UTF8Length, npStr.value.stringValue.UTF8Characters);
*str = bstr.Detach();
return S_OK;
}
HRESULT STDMETHODCALLTYPE HTMLDocumentContainer::get_Document(
__RPC__deref_out_opt IDispatch **ppDisp) {
if (dispatcher)
return dispatcher->QueryInterface(DIID_DispHTMLDocument, (LPVOID*)ppDisp);
return E_FAIL;
}
HTMLDocumentContainer::~HTMLDocumentContainer(void)
{
}
| zzhongster-wxtlactivex | ffactivex/HTMLDocumentContainer.cpp | C++ | mpl11 | 3,293 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <algorithm>
#include <string>
#include "GenericNPObject.h"
static NPObject*
AllocateGenericNPObject(NPP npp, NPClass *aClass)
{
return new GenericNPObject(npp, false);
}
static NPObject*
AllocateMethodNPObject(NPP npp, NPClass *aClass)
{
return new GenericNPObject(npp, true);
}
static void
DeallocateGenericNPObject(NPObject *obj)
{
if (!obj) {
return;
}
GenericNPObject *m = (GenericNPObject *)obj;
delete m;
}
static void
InvalidateGenericNPObject(NPObject *obj)
{
if (!obj) {
return;
}
((GenericNPObject *)obj)->Invalidate();
}
NPClass GenericNPObjectClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ AllocateGenericNPObject,
/* deallocate */ DeallocateGenericNPObject,
/* invalidate */ InvalidateGenericNPObject,
/* hasMethod */ GenericNPObject::_HasMethod,
/* invoke */ GenericNPObject::_Invoke,
/* invokeDefault */ GenericNPObject::_InvokeDefault,
/* hasProperty */ GenericNPObject::_HasProperty,
/* getProperty */ GenericNPObject::_GetProperty,
/* setProperty */ GenericNPObject::_SetProperty,
/* removeProperty */ GenericNPObject::_RemoveProperty,
/* enumerate */ GenericNPObject::_Enumerate,
/* construct */ NULL
};
NPClass MethodNPObjectClass = {
/* version */ NP_CLASS_STRUCT_VERSION,
/* allocate */ AllocateMethodNPObject,
/* deallocate */ DeallocateGenericNPObject,
/* invalidate */ InvalidateGenericNPObject,
/* hasMethod */ GenericNPObject::_HasMethod,
/* invoke */ GenericNPObject::_Invoke,
/* invokeDefault */ GenericNPObject::_InvokeDefault,
/* hasProperty */ GenericNPObject::_HasProperty,
/* getProperty */ GenericNPObject::_GetProperty,
/* setProperty */ GenericNPObject::_SetProperty,
/* removeProperty */ GenericNPObject::_RemoveProperty,
/* enumerate */ GenericNPObject::_Enumerate,
/* construct */ NULL
};
// Some standard JavaScript methods
bool toString(void *object, const NPVariant *args, uint32_t argCount, NPVariant *result) {
GenericNPObject *map = (GenericNPObject *)object;
if (!map || map->invalid) return false;
// no args expected or cared for...
std::string out;
std::vector<NPVariant>::iterator it;
for (it = map->numeric_mapper.begin(); it < map->numeric_mapper.end(); ++it) {
if (NPVARIANT_IS_VOID(*it)) {
out += ",";
}
else if (NPVARIANT_IS_NULL(*it)) {
out += ",";
}
else if (NPVARIANT_IS_BOOLEAN(*it)) {
if ((*it).value.boolValue) {
out += "true,";
}
else {
out += "false,";
}
}
else if (NPVARIANT_IS_INT32(*it)) {
char tmp[50];
memset(tmp, 0, sizeof(tmp));
_snprintf(tmp, 49, "%d,", (*it).value.intValue);
out += tmp;
}
else if (NPVARIANT_IS_DOUBLE(*it)) {
char tmp[50];
memset(tmp, 0, sizeof(tmp));
_snprintf(tmp, 49, "%f,", (*it).value.doubleValue);
out += tmp;
}
else if (NPVARIANT_IS_STRING(*it)) {
out += std::string((*it).value.stringValue.UTF8Characters,
(*it).value.stringValue.UTF8Characters + (*it).value.stringValue.UTF8Length);
out += ",";
}
else if (NPVARIANT_IS_OBJECT(*it)) {
out += "[object],";
}
}
// calculate how much space we need
std::string::size_type size = out.length();
char *s = (char *)NPNFuncs.memalloc(size * sizeof(char));
if (NULL == s) {
return false;
}
memcpy(s, out.c_str(), size);
s[size - 1] = 0; // overwrite the last ","
STRINGZ_TO_NPVARIANT(s, (*result));
return true;
}
// Some helpers
static void free_numeric_element(NPVariant elem) {
NPNFuncs.releasevariantvalue(&elem);
}
static void free_alpha_element(std::pair<const char *, NPVariant> elem) {
NPNFuncs.releasevariantvalue(&(elem.second));
}
// And now the GenericNPObject implementation
GenericNPObject::GenericNPObject(NPP instance, bool isMethodObj):
invalid(false), defInvoker(NULL), defInvokerObject(NULL) {
NPVariant val;
INT32_TO_NPVARIANT(0, val);
immutables["length"] = val;
if (!isMethodObj) {
NPObject *obj = NULL;
obj = NPNFuncs.createobject(instance, &MethodNPObjectClass);
if (NULL == obj) {
throw NULL;
}
((GenericNPObject *)obj)->SetDefaultInvoker(&toString, this);
OBJECT_TO_NPVARIANT(obj, val);
immutables["toString"] = val;
}
}
GenericNPObject::~GenericNPObject() {
for_each(immutables.begin(), immutables.end(), free_alpha_element);
for_each(alpha_mapper.begin(), alpha_mapper.end(), free_alpha_element);
for_each(numeric_mapper.begin(), numeric_mapper.end(), free_numeric_element);
}
bool GenericNPObject::HasMethod(NPIdentifier name) {
if (invalid) return false;
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(immutables[key])) {
return (NULL != immutables[key].value.objectValue->_class->invokeDefault);
}
}
else if (alpha_mapper.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) {
return (NULL != alpha_mapper[key].value.objectValue->_class->invokeDefault);
}
}
}
return false;
}
bool GenericNPObject::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (invalid) return false;
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if ( NPVARIANT_IS_OBJECT(immutables[key])
&& immutables[key].value.objectValue->_class->invokeDefault) {
return immutables[key].value.objectValue->_class->invokeDefault(immutables[key].value.objectValue, args, argCount, result);
}
}
else if (alpha_mapper.count(key) > 0) {
if ( NPVARIANT_IS_OBJECT(alpha_mapper[key])
&& alpha_mapper[key].value.objectValue->_class->invokeDefault) {
return alpha_mapper[key].value.objectValue->_class->invokeDefault(alpha_mapper[key].value.objectValue, args, argCount, result);
}
}
}
return true;
}
bool GenericNPObject::InvokeDefault(const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (invalid) return false;
if (defInvoker) {
defInvoker(defInvokerObject, args, argCount, result);
}
return true;
}
// This method is also called before the JS engine attempts to add a new
// property, most likely it's trying to check that the key is supported.
// It only returns false if the string name was not found, or does not
// hold a callable object
bool GenericNPObject::HasProperty(NPIdentifier name) {
if (invalid) return false;
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(immutables[key])) {
return (NULL == immutables[key].value.objectValue->_class->invokeDefault);
}
}
else if (alpha_mapper.count(key) > 0) {
if (NPVARIANT_IS_OBJECT(alpha_mapper[key])) {
return (NULL == alpha_mapper[key].value.objectValue->_class->invokeDefault);
}
}
return false;
}
return true;
}
static bool CopyNPVariant(NPVariant *dst, const NPVariant *src)
{
dst->type = src->type;
if (NPVARIANT_IS_STRING(*src)) {
NPUTF8 *str = (NPUTF8 *)NPNFuncs.memalloc((src->value.stringValue.UTF8Length + 1) * sizeof(NPUTF8));
if (NULL == str) {
return false;
}
dst->value.stringValue.UTF8Length = src->value.stringValue.UTF8Length;
memcpy(str, src->value.stringValue.UTF8Characters, src->value.stringValue.UTF8Length);
str[dst->value.stringValue.UTF8Length] = 0;
dst->value.stringValue.UTF8Characters = str;
}
else if (NPVARIANT_IS_OBJECT(*src)) {
NPNFuncs.retainobject(NPVARIANT_TO_OBJECT(*src));
dst->value.objectValue = src->value.objectValue;
}
else {
dst->value = src->value;
}
return true;
}
#define MIN(x, y) ((x) < (y)) ? (x) : (y)
bool GenericNPObject::GetProperty(NPIdentifier name, NPVariant *result) {
if (invalid) return false;
try {
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
if (!CopyNPVariant(result, &(immutables[key]))) {
return false;
}
}
else if (alpha_mapper.count(key) > 0) {
if (!CopyNPVariant(result, &(alpha_mapper[key]))) {
return false;
}
}
}
else {
// assume int...
unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name);
if (numeric_mapper.size() > key) {
if (!CopyNPVariant(result, &(numeric_mapper[key]))) {
return false;
}
}
}
}
catch (...) {
}
return true;
}
bool GenericNPObject::SetProperty(NPIdentifier name, const NPVariant *value) {
if (invalid) return false;
try {
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (immutables.count(key) > 0) {
// the key is already defined as immutable, check the new value type
if (value->type != immutables[key].type) {
return false;
}
// Seems ok, copy the new value
if (!CopyNPVariant(&(immutables[key]), value)) {
return false;
}
}
else if (!CopyNPVariant(&(alpha_mapper[key]), value)) {
return false;
}
}
else {
// assume int...
NPVariant var;
if (!CopyNPVariant(&var, value)) {
return false;
}
unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name);
if (key >= numeric_mapper.size()) {
// there's a gap we need to fill
NPVariant pad;
VOID_TO_NPVARIANT(pad);
numeric_mapper.insert(numeric_mapper.end(), key - numeric_mapper.size() + 1, pad);
}
numeric_mapper.at(key) = var;
NPVARIANT_TO_INT32(immutables["length"])++;
}
}
catch (...) {
}
return true;
}
bool GenericNPObject::RemoveProperty(NPIdentifier name) {
if (invalid) return false;
try {
if (NPNFuncs.identifierisstring(name)) {
char *key = NPNFuncs.utf8fromidentifier(name);
if (alpha_mapper.count(key) > 0) {
NPNFuncs.releasevariantvalue(&(alpha_mapper[key]));
alpha_mapper.erase(key);
}
}
else {
// assume int...
unsigned long key = (unsigned long)NPNFuncs.intfromidentifier(name);
if (numeric_mapper.size() > key) {
NPNFuncs.releasevariantvalue(&(numeric_mapper[key]));
numeric_mapper.erase(numeric_mapper.begin() + key);
}
NPVARIANT_TO_INT32(immutables["length"])--;
}
}
catch (...) {
}
return true;
}
bool GenericNPObject::Enumerate(NPIdentifier **identifiers, uint32_t *identifierCount) {
if (invalid) return false;
try {
*identifiers = (NPIdentifier *)NPNFuncs.memalloc(sizeof(NPIdentifier) * numeric_mapper.size());
if (NULL == *identifiers) {
return false;
}
*identifierCount = 0;
std::vector<NPVariant>::iterator it;
unsigned int i = 0;
char str[10] = "";
for (it = numeric_mapper.begin(); it < numeric_mapper.end(); ++it, ++i) {
// skip empty (padding) elements
if (NPVARIANT_IS_VOID(*it)) continue;
_snprintf(str, sizeof(str), "%u", i);
(*identifiers)[(*identifierCount)++] = NPNFuncs.getstringidentifier(str);
}
}
catch (...) {
}
return true;
}
| zzhongster-wxtlactivex | ffactivex/GenericNPObject.cpp | C++ | mpl11 | 13,001 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "Host.h"
#include "npactivex.h"
#include "ObjectManager.h"
#include "objectProxy.h"
#include <npapi.h>
#include <npruntime.h>
CHost::CHost(NPP npp)
: ref_cnt_(1),
instance(npp),
lastObj(NULL)
{
}
CHost::~CHost(void)
{
UnRegisterObject();
np_log(instance, 3, "CHost::~CHost");
}
void CHost::AddRef()
{
++ref_cnt_;
}
void CHost::Release()
{
--ref_cnt_;
if (!ref_cnt_)
delete this;
}
NPObject *CHost::GetScriptableObject() {
return lastObj;
}
NPObject *CHost::RegisterObject() {
lastObj = CreateScriptableObject();
if (!lastObj)
return NULL;
lastObj->host = this;
// It doesn't matter which npp in setting.
return lastObj;
}
void CHost::UnRegisterObject() {
return;
NPObjectProxy embed;
NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed);
NPVariant var;
VOID_TO_NPVARIANT(var);
NPNFuncs.removeproperty(instance, embed, NPNFuncs.getstringidentifier("object"));
np_log(instance, 3, "UnRegisterObject");
lastObj = NULL;
}
NPP CHost::ResetNPP(NPP newNPP) {
// Doesn't support now..
_asm{int 3};
NPP ret = instance;
UnRegisterObject();
instance = newNPP;
np_log(newNPP, 3, "Reset NPP from 0x%08x to 0x%08x", ret, newNPP);
RegisterObject();
return ret;
}
CHost *CHost::GetInternalObject(NPP npp, NPObject *embed_element)
{
NPVariantProxy var;
if (!NPNFuncs.getproperty(npp, embed_element, NPNFuncs.getstringidentifier("__npp_instance__"), &var))
return NULL;
if (NPVARIANT_IS_INT32(var)) {
return (CHost*)((NPP)var.value.intValue)->pdata;
} else if (NPVARIANT_IS_DOUBLE(var)) {
return (CHost*)((NPP)((int32)var.value.doubleValue))->pdata;
}
return NULL;
}
ScriptBase *CHost::GetMyScriptObject() {
NPObjectProxy embed;
NPNFuncs.getvalue(instance, NPNVPluginElementNPObject, &embed);
return GetInternalObject(instance, embed)->lastObj;
} | zzhongster-wxtlactivex | ffactivex/Host.cpp | C++ | mpl11 | 4,946 |
comment ?
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
.386
.model flat
__except_handler proto
.safeseh __except_handler
?
.386
.model flat
PUBLIC __KiUserExceptionDispatcher_hook
.data
public __KiUserExceptionDispatcher_origin
__KiUserExceptionDispatcher_origin dd 0
public __KiUserExceptionDispatcher_ATL_p
__KiUserExceptionDispatcher_ATL_p dd 0
.code
__KiUserExceptionDispatcher_hook proc
; The arguments are already on the stack
call __KiUserExceptionDispatcher_ATL_p
push __KiUserExceptionDispatcher_origin
ret
__KiUserExceptionDispatcher_hook endp
end
| zzhongster-wxtlactivex | ffactivex/atlthunk_asm.asm | Assembly | mpl11 | 2,081 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor:
* Chuan Qiu <qiuc12@gmail.com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <Windows.h>
#define ATL_THUNK_APIHOOK
EXCEPTION_DISPOSITION
__cdecl
_except_handler(
struct _EXCEPTION_RECORD *ExceptionRecord,
void * EstablisherFrame,
struct _CONTEXT *ContextRecord,
void * DispatcherContext );
typedef EXCEPTION_DISPOSITION
(__cdecl *_except_handler_type)(
struct _EXCEPTION_RECORD *ExceptionRecord,
void * EstablisherFrame,
struct _CONTEXT *ContextRecord,
void * DispatcherContext );
typedef struct tagATL_THUNK_PATTERN
{
LPBYTE pattern;
int pattern_size;
(void)(*enumerator)(struct _CONTEXT *);
}ATL_THUNK_PATTERN;
void InstallAtlThunkEnumeration();
void UninstallAtlThunkEnumeration(); | zzhongster-wxtlactivex | ffactivex/atlthunk.h | C | mpl11 | 2,219 |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include "Host.h"
namespace ATL
{
template <typename T>
class CComObject;
}
class CControlEventSink;
class CControlSite;
class PropertyList;
class CAxHost : public CHost{
private:
CAxHost(const CAxHost &);
bool isValidClsID;
bool isKnown;
bool noWindow;
protected:
// The window handle to our plugin area in the browser
HWND Window;
WNDPROC OldProc;
// The class/prog id of the control
CLSID ClsID;
LPCWSTR CodeBaseUrl;
CComObject<CControlEventSink> *Sink;
RECT lastRect;
PropertyList *Props_;
public:
CAxHost(NPP inst);
~CAxHost();
static CLSID ParseCLSIDFromSetting(LPCSTR clsid, int length);
virtual NPP ResetNPP(NPP npp);
CComObject<CControlSite> *Site;
void SetNPWindow(NPWindow *window);
void ResetWindow();
PropertyList *Props() {
return Props_;
}
void Clear();
void setWindow(HWND win);
HWND getWinfow();
void UpdateRect(RECT rcPos);
bool verifyClsID(LPOLESTR oleClsID);
bool setClsID(const char *clsid);
bool setClsID(const CLSID& clsid);
CLSID getClsID() {
return this->ClsID;
}
void setNoWindow(bool value);
bool setClsIDFromProgID(const char *progid);
void setCodeBaseUrl(LPCWSTR clsid);
bool hasValidClsID();
bool CreateControl(bool subscribeToEvents);
void UpdateRectSize(LPRECT origRect);
void SetRectSize(LPSIZEL size);
bool AddEventHandler(wchar_t *name, wchar_t *handler);
HRESULT GetControlUnknown(IUnknown **pObj);
short HandleEvent(void *event);
ScriptBase *CreateScriptableObject();
};
| zzhongster-wxtlactivex | ffactivex/axhost.h | C++ | mpl11 | 3,248 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is RSJ Software GmbH code.
*
* The Initial Developer of the Original Code is
* RSJ Software GmbH.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributors:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
BOOL TestAuthorization (NPP Instance,
int16 ArgC,
char *ArgN[],
char *ArgV[],
const char *MimeType); | zzhongster-wxtlactivex | ffactivex/authorize.h | C | mpl11 | 2,050 |